Blogger Widgets
  • Sharing Photos using SignalR
  • TFS Extenstion - allows copy work items between projects
  • Displaying jquery progressbar with ajax call on a modal dialog
  • Managing windows services of a server via a website
  • Exploring technologies available to date. TechCipher is one place that any professional would like to visit, either to get an overview or to have better understanding.

Search This Blog

Friday, 26 April 2013

Set deadlock priority with NHibernate

Sometimes you would want to explicitly set dead lock priority as part of a transaction which is not possible if you are using NHibernate as of now. In such cases you can define a custom Interceptor which does the trick. Here is a small snippet of code that can help you achieve that:
public class DeadLockPriorityInterceptor : EmptyInterceptor
 private ISession session;
 private string priority;

 public DeadLockPriorityInterceptor(string Priority)
  priority = Priority;

 public override void AfterTransactionBegin(ITransaction tx)
  using (var command = session.Connection.CreateCommand())
   string sql = string.Format("SET DEADLOCK_PRIORITY {0}", priority);
   // Create a SQL Command
   //System.Data.IDbCommand command = session.Connection.CreateCommand();
   // Set the query you're going to run
   command.CommandText = sql;
   // Run the query

 public override void SetSession(ISession sessionLocal)
  session = sessionLocal;
Now your interceptor is ready. So if you would like to set your deadlock priority to High (ie.. SET DEADLOCK_PRIORITY HIGH), then just use following single line of code shown below:

ISession session = sessionFactory.OpenSession(new DeadLockPriorityInterceptor("HIGH"));

This is how it works

1. sessionFactory.OpenSession will pass the interceptor to session.
2. OpenSession() verifies if there are any interceptors defined in this case it will be "DeadLockPriorityInterceptor".
3. Executes SetSession() as it is overridden by an interceptor.
4. session.BeginTransaction() will start the transaction.
5. BeginTransaction() verifies if an interceptor is defined by OpenSession().
6. Executes AfterTransactionBegin() as it is overridden by an interceptor.

That's it. NHibernate offers various interceptor points which will become quite handy at times.

“Simplicity, carried to the extreme, becomes elegance.” – Jon Franklin


Copyright © 2013 Template Doctor . Designed by Malith Madushanka - Cool Blogger Tutorials | Code by CBT | Images by by HQ Wallpapers