This is the third post of a multi-part post series on writing simple auditing functionality for an ASP.NET application using NHibernate. The requirement was that every object modification event in the system should be logged by username and date. Specifically I don’t need to know exactly which properties were changed (just that a user was updated by whom at what time), but if you do need to save the changed properties there are plenty of hooks to do that.
I’ll update this post with links to the next parts when they become available
The AuditObjectModification Method
In Part 2 we wrote a bunch of tests for the AuditObjectModification method in the AuditInterceptor.cs class. This method currently just throws a NotImplementedException:
I won’t go through each test individually (just the first one as an example), but when writing this iteratively you might want to go through each test and get them to pass one at a time.
Satisfying the First Test
Let’s start making by sure that the first test – AuditObjectModificationSouldNotSaveAuditEntity – can pass by making sure we don’t save audit objects:
And after running the tests:
And now the first test passes!
Implementing the Rest
All that is left is to create an instance of the Audit class, fill out some properties, and save it. My implementation is below:
Now we rerun the tests:
Now that’s what I like to see!
Calling the AuditObjectModification method
No we need to call our newly implemented method from the empty overrides of the AuditInterceptor method:
And we are now finished with our Audit Interceptor!
Next time we’ll hook the interceptor into NHibernate and look at the fruits of our labor.