Windows Support Number

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Thursday, 17 September 2009

Auditing with nHibernate...

Posted on 02:02 by Unknown
Long time since I've posted anything but I came across an interesting problem the other day whilst I was working - 'How can I audit changes to specific entities when using nHibernate?'

There are several implementation out there already (see Oren's & others posts) but of ones I've seen they are to low level for my liking - they push the auditing of changes into the NH infrastructure away from the Service implementing the business behaviour. I want my service to control and define what is audited I don't want everything audited in the same manner. Auditing for me is the pushing out of events that have affected entities persisted in an OLTP database to OLAP database ideally in an asynchronous manner via some queuing mechanism (MSMQ).

So how do you get events from NH?

Now if you want to observe changes to entities in NH you have to register you're interest by passing an implementation of an IXXXListener interface to the NH configuration when create the SessionFactory, this is the classic implementation of the observer pattern and I guess it's like this because this is a straight port from java - it doesn't follow the .Net approach of EventHandlers & Events, I'm liking this approach as it gives exposure to a different implementation.

What did interest me about this implementation was that as user of the NH Session I can't register with the Session my interest in observing changes to the entities. I have to do this with the SessionFactory and therefore I'm getting notified of ALL events to ALL entities whilst this SessionFactory is alive.

So you can register your interest by implementing a class and passing this to the NH configuration - I've tried to keep it simple by register for events that tell me when CRUD operations have been completed on entities, this is done by implementing the following NH interfaces:

IPostInsertEventListener,
IPostLoadEventListener,
IPostUpdateEventListener,
IPostDeleteEventListener.
I also created an interface called IObserveNHibernate that fires traditional .Net style events when an NH event has been observed.

I've left out all the XXXEventArgs classes from the post for brevity - I hope you can figure out the structure!

public interface IObserveSession<T> : IDisposable where T : IEntity
{
event EventHandler<SessionEventArgs<T>> EntityLoaded;
event EventHandler<SessionEventArgs<T>> EntityCreated;
event EventHandler<SessionEventArgs<T>> EntityUpdated;
event EventHandler<SessionEventArgs<T>> EntityDeleted;
}
So the class looks like:

public sealed class NHibernateObserver : IObserveNHibernate,
IPostInsertEventListener,
IPostLoadEventListener,
IPostUpdateEventListener,
IPostDeleteEventListener
{
public event EventHandler&lt;NHibernateEventArgs&gt; EntityLoaded = delegate { };
public event EventHandler&lt;NHibernateEventArgs&gt; EntityCreated = delegate { };
public event EventHandler&lt;NHibernateEventArgs&gt; EntityUpdated = delegate { };
public event EventHandler&lt;NHibernateEventArgs&gt; EntityDeleted = delegate { };

public void OnPostDelete(PostDeleteEvent @event)
{
EntityDeleted(this, new NHibernateEventArgs(@event.Entity));
}
public void OnPostInsert(PostInsertEvent @event)
{
EntityCreated(this, new NHibernateEventArgs(@event.Entity));
}
public void OnPostLoad(PostLoadEvent @event)
{
EntityLoaded(this, new NHibernateEventArgs(@event.Entity));
}
public void OnPostUpdate(PostUpdateEvent @event)
{
EntityUpdated(this, new NHibernateEventArgs(@event.Entity));
}
}

And this class is then used when creating the SessionFactory for NH. Now currently I wrap the creation of the NH SessionFactory into a custom SessionFactory - this class usually exists as a singleton in the host process and lifetime is managed by the IoC container (it's marked as a singleton).

This SessionFactory is backed by an interface, that defines 2 methods - one for access to the Session & the other for accessing an implementation of SessionObserver<T> exposed as an IObserveSession<T> interface, where the generic T represents the entity type I'm interested in observing.

So the interface looks like:

public interface IObserveSession&lt;T&gt; : IDisposable where T : IEntity
{
event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityLoaded;
event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityCreated;
event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityUpdated;
event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityDeleted;
}

The interface implements the Dispose pattern so the un-hooking of events automatically happens when you've finished observing NH events. The implementation of the interface is show below:

public sealed class SessionObserver&lt;T&gt; : IObserveSession&lt;T&gt; where T : IEntity
{
public event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityLoaded = delegate {};
public event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityCreated = delegate {};
public event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityUpdated = delegate {};
public event EventHandler&lt;SessionEventArgs&lt;T&gt;&gt; EntityDeleted = delegate {};

private IObserveNHibernate _observer;

public SessionObserver(IObserveNHibernate observer)
{
_observer = observer;
_observer.EntityLoaded += (HandleEntityLoaded);
_observer.EntityCreated += (HandleEntityCreated);
_observer.EntityUpdated += (HandleEntityUpdated);
_observer.EntityDeleted += (HandleEntityDeleted);
}

public void Dispose()
{
_observer.EntityLoaded -= HandleEntityLoaded;
_observer.EntityCreated -= HandleEntityCreated;
_observer.EntityUpdated -= HandleEntityUpdated;
_observer.EntityDeleted -= HandleEntityDeleted;

_observer = null;
EntityCreated = null;
EntityUpdated = null;
EntityDeleted = null;
}

private void HandleEntityDeleted(object sender, NHibernateEventArgs args)
{
if (args.Entity is T)
EntityDeleted(this, new SessionEventArgs&lt;T&gt;((T)args.Entity));
}
private void HandleEntityUpdated(object sender, NHibernateEventArgs args)
{
if (args.Entity is T)
EntityUpdated(this, new SessionEventArgs&lt;T&gt;((T)args.Entity));
}
private void HandleEntityCreated(object sender, NHibernateEventArgs args)
{
if (args.Entity is T)
EntityCreated(this, new SessionEventArgs&lt;T&gt;((T)args.Entity));
}
private void HandleEntityLoaded(object sender, NHibernateEventArgs args)
{
if (args.Entity is T)
EntityLoaded(this, new SessionEventArgs&lt;T&gt;((T)args.Entity));
}
}

So I have a custom SessionFactory that looks something like the following - pretty standard NH Session semantics and the new method SessionObserverT - this creates an instance of the SessionObserver<T> per request.

SessionFactory interface:

public interface IProvideSessions
{
ISession GetSession();
IObserveSession<T> SessionObserver<T>() where T : IEntity;
}
SessionFactory class:

public sealed class SessionFactory : IProvideSessions
{
private readonly ISessionFactory _sessionFactory;
private readonly NHibernateObserver _nHibernateObserver;

public SessionFactory(string connectionString)
{
_nHibernateObserver = new NHibernateObserver();

var cfg = new Configuration();
cfg.EventListeners.PostLoadEventListeners = new IPostLoadEventListener[] { _nHibernateObserver };
cfg.EventListeners.PostInsertEventListeners = new IPostInsertEventListener[] { _nHibernateObserver };
cfg.EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[] { _nHibernateObserver };
cfg.EventListeners.PostDeleteEventListeners = new IPostDeleteEventListener[] { _nHibernateObserver };

_sessionFactory = Fluently.Configure().ExposeConfiguration(c => cfg.Configure())
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(connectionString).ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<IEntity>())
.BuildSessionFactory();
}

public ISession GetSession()
{
return _sessionFactory.GetCurrentSession() ?? _sessionFactory.OpenSession();
}

public IObserveSession<T> SessionObserver<T>() where T : IEntity
{
return new SessionObserver<T>(_nHibernateObserver);
}
}
So an example of how I would use this is show below, it's a little contrived and not tested but I hope you get the idea:

public class CashService
{
private readonly SessionFactory _sessionFactory = new SessionFactory("SOME CONNECTION STRING");

public void Debit(string accountNumber, decimal amount)
{
using(var session = _sessionFactory.GetSession())
using(var trans = session.BeginTransaction())
using(var sessionObserver = _sessionFactory.SessionObserver<Transaction>())
{
sessionObserver.EntityCreated += ((sender, args) => AuditTransaction(args));

var account = session.Get<Account>(accountNumber);

session.Save(new Transaction(account, amount));

trans.Commit();
}
}

private void AuditTransaction(SessionEventArgs<Transaction> args)
{
// Write transaction event to audit queue...
// if fails the throw exception...
}
}

Now I've not tested this fully and I'm not sure of the viablity of this option or whether I like the end usage - I suppose I could wrap the NH Session behind a custom Session class that exposes the events directly. But it's a start at thinking how I'm going to achieve the auditing required.


Wow that was longer thanexpected ;)

Anyway till next time...


Awkward
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in nHibernate Auditing Design Fluent | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Unit testing Rx methods Timeout & Retry with moq
    Earlier this week I was trying to unit test an asynchronous service (Foo) which used another asynchronous service (Bar) internally and ran i...
  • StructureMap: ILifecycle
    The other day I wanted to control the scope of a service inside a web based app with semantics which didn't fit either 'HttpContextS...
  • How many pins can Bing Maps handle in a WP7 app - part 1
    part2 -  http://awkwardcoder.blogspot.com/2011/10/how-many-pins-can-bing-maps-handle-in.html part3 -  http://awkwardcoder.blogspot.com/2011/...
  • MVVM anti-pattern: Injecting the IoC container into a View Model
    This is another anti-pattern I've seen a lot recently, the dynamic use of the IoC container inside a view model to resolve child view mo...
  • faking data in WP7 and other .Net platforms
    I needed to fake some data for a WP7 app yesterday and I was about to write a couple of classes when I thought why not check out what's ...
  • Implementing a busy indicator using a visual overlay in MVVM
    This is a technique we use at work to lock the UI whilst some long running process is happening - preventing the user clicking on stuff whil...
  • Daily Dilbert Service - the most important service I've ever written...
    NuGet package available here ... First off a big shout to  @hamish  &  @leeoades  on this one - I'm just blogging about it. At work ...
  • Implementing a message box using a visual overlay in MVVM
    I've blogged about implementing a busy indicator before, this post is an extension of this pattern to implement a message box - this is...
  • Observations on web service design for mobile devices
    This post was prompted by my use of back end third party services for the FINDaPAD app and my recent set of posts about push pins and Bing ...
  • WP7Contrib: Isolated Storage Cache Provider
    15/04/2001 - The code for this example has been updated - new WP7 build of SilverlightSerializer, this has removed the explicit implementati...

Categories

  • .Net
  • .Net 4.5
  • Abstractions
  • Advertising
  • Agile
  • Agile Courage
  • AOP
  • Async
  • automated testing
  • Azure
  • Azure IIS RESTful development
  • BDD
  • Bing Maps
  • Bounded Context
  • C#
  • C# 5.0
  • Caching
  • Chocolatey
  • CLoud
  • CodePlex
  • Coding
  • Coding Building CI Testing
  • Coding C#
  • coding C# IoC StructureMap
  • Coding Functional-Programming
  • Coding REST Knowledge
  • Coding Services
  • Coding TDD Refactoring Agile
  • Command
  • continuous testing
  • coupling
  • CultureInfo
  • DAL
  • databases
  • DDD
  • DDD Coaching
  • DDD Domain Events Auditing nHibernate
  • DDD Entities Value Objects
  • Debugging
  • Design Patterns
  • Design Patterns Databases Auditing
  • Developement
  • Development
  • Development Coding
  • Development Process
  • Development unit testing
  • Development VS 2011
  • Diagnostics
  • Disposable
  • Exceptions
  • FINDaPAD
  • FindaPad Property Rental Windows Phone 7 Mobile Devices
  • Fun Coding Duct-Tape
  • Hotfixes
  • integration testing
  • IoC
  • jasmine
  • javascript
  • Jobs Development
  • LINQ
  • marketplace
  • Mobile Devices
  • Mocking
  • MSDN Coding
  • MSpec
  • Multilingual
  • MVC
  • MVVM
  • nCrunch
  • nHbiernate Repository Pattern Criteria
  • nHibernate Auditing Design Fluent
  • nHibnerate Entities Events Listeners
  • node.js
  • nodes.js
  • Nokia
  • NoSQL RavenDB Azure Development
  • Observations
  • OO
  • ORM
  • Performance
  • Portable Class Library
  • Portable Library
  • PostSharp
  • Process
  • Rants
  • RavenDB IIS 7.5 Development
  • Reactive
  • Reactive Extension
  • Reactive Extensions
  • ReadOnlyCollections
  • Resharper
  • REST Distributed-Systems
  • REST HTTP
  • rest web
  • RESTful
  • Rx
  • Serialization
  • Silverlight
  • Silverlight Installation
  • Task
  • TDD
  • TDD IoC DI
  • TDD Mocking
  • TDD Team Observation
  • Telerik
  • testing
  • threading
  • TPL
  • UI
  • Undo-Redo
  • unit testing
  • ViewModels
  • VS 2012
  • wcf
  • web api
  • Web Services
  • web services mobile devices data
  • WebAPI
  • Windows
  • Windows 8
  • windows phone
  • Windows Phone 7
  • WP7
  • WP7 Bing Maps Development Network HTTP
  • WP7 Bing Maps Development UK Crime
  • WP7 Bing Maps Development UK Crime Clustering
  • WP7 Bing Maps Development UK Polygons Clustering Performance
  • WP7 cryptography bouncy castle
  • WP7 Cultures C#
  • WP7 feedback development app store
  • WP7 Javascript web browser
  • WP7 MSBuild
  • WP7 ORM Databases performance
  • WP7 Serialisation
  • WP7 SilverlightSerializer C#
  • WP7 sqlite performance development
  • WP7 WP7Contrib Bing Maps Development
  • WP7 WP7Contrib Bing Maps Polygon Development
  • WP7 WP7Contrib CodePlex
  • WP7 WP7Contrib CodePlex Bing Maps Development
  • WP7 WP7Contrib CodePlex ObservableCollection
  • WP7 WP7Contrib ILMerge .Net
  • WP7 WP7Contrib Phone Maps
  • WP7 WP7Contrib SilverlightSerializer C#
  • WP7Contrib
  • WP7Contrib Bing Maps WP7
  • WP7Contrib WP7 Geo-Location development C#
  • WP7Contrib WP7 HTTP Compression
  • WP7Contrib WP7 Url Development Rx
  • WP7Dev
  • WPF
  • WPF Cultures
  • WuApi
  • XAML

Blog Archive

  • ►  2013 (16)
    • ►  November (5)
    • ►  September (3)
    • ►  August (1)
    • ►  July (1)
    • ►  June (3)
    • ►  May (2)
    • ►  January (1)
  • ►  2012 (44)
    • ►  November (2)
    • ►  October (8)
    • ►  September (5)
    • ►  August (2)
    • ►  July (4)
    • ►  June (3)
    • ►  May (1)
    • ►  April (2)
    • ►  March (13)
    • ►  February (4)
  • ►  2011 (52)
    • ►  December (3)
    • ►  November (5)
    • ►  October (7)
    • ►  September (7)
    • ►  August (11)
    • ►  July (4)
    • ►  May (2)
    • ►  April (1)
    • ►  March (5)
    • ►  February (3)
    • ►  January (4)
  • ►  2010 (1)
    • ►  August (1)
  • ▼  2009 (32)
    • ►  December (3)
    • ►  November (7)
    • ►  October (6)
    • ▼  September (11)
      • Mocks, Fakes, Stubs - why bother?
      • Distributed Systems are Coupled - Period!
      • Devlicio.us boys run out of duct tape!
      • Test Harnesses are counter productive...
      • So you thinking you're doing TDD?
      • I know nothing moments...
      • The secret all developers should know...
      • How to test a static dependency used inside a clas...
      • Application auditing - an example why I don't work...
      • Repository pattern - my preferred implementation...
      • Auditing with nHibernate...
    • ►  April (1)
    • ►  March (4)
Powered by Blogger.

About Me

Unknown
View my complete profile