Let’s talk about NHInsights an OracleManagedDataClientDriver for NHibernate and Application Insights

If you use Oracle and NHibernate and you are trying to use Application Insights to diagnose issues with your database calls you will notice that for ASP.NET applications the out-of-the-box dependency monitor currently reports calls to these types of dependencies:

  • SQL databases
  • ASP.NET web and WCF services that use HTTP-based bindings
  • Local or remote HTTP calls
  • Azure DocumentDb, table, blob storage, and queue

So how can you track your queries as a dependency?

Well I checked the Track Dependency API which is really simple and also remembered that some time ago I had used MiniProfiler together with NHibernate and managed to track SQL Server response times.

I downloaded MiniProfiler source code and learned how they implemented their ProfiledDbCommand and also the MiniProfilerSql2008ClientDriver.

Based on those two great pieces of code and the original OracleManagedDataClientDriver code I managed to create NHInsights.

What’s the secret? to create a driver capable of returning a profiled DbCommand (i.e. InsightsDbCommand):

 1public class OracleManagedDataClientDriver : ReflectionBasedDriver, IEmbeddedBatcherFactoryProvider
 3    ...
 5    public override IDbCommand CreateCommand()
 6    {
 7       var command = base.CreateCommand();
 9       command = new **InsightsDbCommand**((DbCommand)command, (DbConnection)command.Connection) as IDbCommand;
11       return command;
12    }

Go ahead and try it! To start sending your queries as dependencies just install the nuget package:

1Install-Package NHInsights

And then reference the NHInsights.OracleManagedDataClientDriver in your NHibernate configuration:

1<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
2  <session-factory>
3    ...
4    <property name="connection.driver_class">NHInsights.OracleManagedDataClientDriver, NHInsights, Version=, Culture=neutral, PublicKeyToken=null</property>
5    ...
6  </session-factory>

Hope it helps!