Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

IAuditable Interface - .NET Framework

RSS
Modified on Fri, Jun 13, 2014, 1:59 PM by Administrator Categorized as ASP·NET MVC, ASP·NET Web Forms, ·Net Framework

Implementation

When creating a new instance of an entity.

var i = new Invoice();
i.Created(user);

When updating an existing entity

i.Modified(user);

Applying to a database entity.

public partial class Invoice : IAuditable { }

Reusable Code

public interface IAuditable
{
    DateTime UpdatedOn { get; set; }
    string UpdatedBy { get; set; }
    DateTime CreatedOn { get; set; }
    string CreatedBy { get; set; }
}


public static class IAuditableExtension
{
    public static void Audit(this IAuditable e, bool createNew, string byUser)
    {
        if (e == null)
            return;

        var dtNow = DateTime.UtcNow;

        if (createNew)
        {
            e.CreatedOn = dtNow;
            e.CreatedBy = byUser;
        }

        e.UpdatedOn = DateTime.UtcNow;
        e.UpdatedBy = byUser;
    }

}

Future Improvements

An improvement that can be made is that the Audit method automatically "know" if the entity is new or existing. See this article or this one for ideas how to do this.

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.