Using Reflection to Find the Connection String Being Used By NHibernate

Filed Under (.Net, NHibernate) by John Miller on 14-03-2009

Tagged Under : , ,

In my last post, we discussed how to run a Sql script from C# to insert lookup data when we regenerate our database for integration tests. But we want to make sure that the connection string that’s being used by NHibernate is the same connection string being used by our InsertTestData() method. To do that, we can use reflection to find the value of the ConnectionString property of the ISessionFactory.ConnectionProvider object.

public static class NHibernateHelper
{
    private static readonly ISessionFactory _sessionFactory = Configuration.BuildSessionFactory();
    private static Configuration _configuration;
    public static ISessionFactory SessionFactory
    {
        get { return _sessionFactory; }
    }
    public static Configuration Configuration
    {
        get
        {
            if (_configuration == null)
                _configuration = new Configuration().Configure();
            return _configuration;
        }
    }
    public static string ConnectionString
    {
        get
        {
            var propertyType = typeof (DriverConnectionProvider);
            var propertyInfo = propertyType.GetProperty("ConnectionString"
                                                , BindingFlags.Instance | BindingFlags.NonPublic);
            return (string) propertyInfo.GetValue(SessionFactory.ConnectionProvider, null);
        }
    }
    public static ISession GetSession()
    {
        var session = _sessionFactory.OpenSession();
        session.FlushMode = FlushMode.Never;
        return session;
    }
}

Now we can change the InsertTestData() method to use this connection string.

public void InsertTestData()
{
    using (var conn = new SqlConnection(NHibernateHelper.ConnectionString))
    {
        FileInfo fileInfo = new FileInfo(@"Sql\InsertSeedData.sql");
        var sql = fileInfo.OpenText().ReadToEnd();
        Server server = new Server(new ServerConnection(conn));
        server.ConnectionContext.ExecuteNonQuery(sql);
    }
}

Update:

Matt pointed out below that we really don’t need to use reflection to do this, NHibernate handles it for us. Thanks Matt!
public static string ConnectionString
{
    get
    {
        return Configuration.GetProperty("connection.connection_string");
    }
}

DotNetKicks Image

Share/Save/Bookmark

Running a Sql Script to Insert Lookup Data For Tests From C#

Filed Under (.Net, Unit Testing) by John Miller on 14-03-2009

Tagged Under : , , ,

Earlier this week I needed a way to insert test data into my database that was being regenerated at the start of each test fixture. For most scripts, you can use a simple command with CommandText to get the job done. But this doesn’t work with certain Sql statements, such as GO. Luckily, I stumbled across Microsoft’s Sql Server Management classes which turned out to be exactly what I was looking for.

To use them, we first need to create references to the Microsoft.SqlServer.Smo and Microsoft.SqlServer.ConnectionInfo assemblies.

CreateRef1

CreateRef2

Now, we need to reference those namespaces in our code file.

using System.Data.SqlClient;
using System.IO;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

 

And now for the code to actually run the script. (I’m calling this method from within RebuildDatabase() which is called in the establish_context(), or [TestFixtureSetup], method of the repository tests.)

public void InsertTestData()
{
    using (var conn = new SqlConnection("<connection string>"))
    {
        FileInfo fileInfo = new FileInfo(@"Sql\InsertSeedData.sql");
        var sql = fileInfo.OpenText().ReadToEnd();
        Server server = new Server(new ServerConnection(conn));
        server.ConnectionContext.ExecuteNonQuery(sql);
    }
}

It’s worth noting that I’m including the Sql script that’s being executed here as a linked file inside the project. The physical file is actually located in an upper level directory outside of the project. Including it as a linked file makes sure that the script is included when the test dlls are being ran. (Just be sure to set the “Copy to Output Directory” property of the file to True in Visual Studio.) Alternatively, you could also you an absolute path to point to your Sql script.

DotNetKicks Image

Share/Save/Bookmark

Challenge Yourself This Year: March Goals Progress

Filed Under (Uncategorized) by John Miller on 02-03-2009

Tagged Under : ,

I just saw that Darrell posted his goals progress for the year which reminded me that I promised to do the same. (Thanks for the reminder, Darrell).

But before I go over my status, I want to share a quote I heard on twitter today.

continuous improvement is a personal thing, if you are “continuously” comparing yourself to others, you will “continually” be disappointed…just be better than “yourself” yesterday

That quote came from JP Boodhoo, and sums up perfectly something I personally struggled with in the past. If your drive to learn exists only because you’re trying to keep up with the Jones’, then learning will become a chore instead of something that you get enjoyment from. Life’s too short, make it fun!

Technical Goals

Read the following books:

Become proficient with the following tools & technologies:

  • ASP.Net MVCNo progress made here. Guessing that this one will have to wait til the second half of the year.
  • NHibernateIn progress. Just started a project with NHibernate, although I’m admittedly not use Fluent NHibernate on Linq to NHibernate and I probably should be. Kinda wanted to do my first NHibernate project the “hard way” so I’d have a good understanding of what makes those other tools work.
  • The Castle StackToyed around with ActiveRecord and could see it being used on a smaller project, but given the choice between it and NHibernate, I would rather work with NHibernate. I’m using basic features of Windsor in my current work project, but future projects will probably be using Ninject (gotta support our fellow Ohio developers!). With ASP.Net MVC and FubuMVC out (or almost out), I don’t believe that I’ll be using Monorail in the future, so I’m marking this goal as complete since I probably won’t need to work with these frameworks any more this year.
  • Team CityUsing Team City currently and am very impressed with how easy it was to set up. And the interface is simply awesome, would expect nothing else from the makers of Resharper!
  • Ruby (the basics at a minimum) – In progress. Just starting to get into Ruby and have been very impressed with it thus far. Especially the testing capabilities. RSpec feels much more natural when writing BDD style tests than with the frameworks we have available in .Net. Planning to really sink my teeth into the language over the next couple of weeks.
  • PowershellNo progress here yet.

Get involved:

  • Two blog posts per month – Two per month so far. No less, no more. Surprised at how hard it is to keep up with this. I have a whole new respect for those developers that manage to write 2+ per week!
  • Two technical presentations for coworkers to push agile methodologies at my current company. – After this project, I’m planning on doing a TDD talk with my coworkers. So the first should be coming in the next couple of months.

Certifications:

  • Upgrade MCPD certification from 2.0 to 3.5 – No progress here.

Personal Goals

Family Time

  • Take 2 one week long trips – First trip is scheduled, wife and I are going with her parents to Disney in May.
  • Take 6 weekend getaways – Took a weekend trip to West Virginia in January. Didn’t do much of anything exciting, just relaxed. Which was exactly what we both needed!
  • By the end of the year, work from home regularly two times per week – Only a couple of months in and I’m not seeing me hitting this goal at my current workplace. I work for a consulting company and a lot of our engagements are on site. Maybe some opportunities will open up towards the end of the year.

Belief System

  • Read the Bible completely through – A little behind here but not too bad. Just started Numbers so hitting the end-of-year goal is still certainly doable.

Financial

  • Reduce debt by two-thirds – On track here thus far.
  • Become familiar with some of the ins and outs of day trading, as well as how currency trading works – Learned that it takes nerves off steel to do day trading. Not to mention a lot of time to research trends. I think short term trading is a bit more my style instead of day trading.

Side Projects

  • Finish the project I’ve been working on for the last year! – Sadly no progress here.
  • Start a new venture and grow it to produce $500 per month of automated income by the end of the year. – A buddy and I are starting a new side project (in Ruby on Rails, attempting to kill two birds with one stone) and although we both realize that we probably won’t make any money on it this year, we’re excited to be working towards something. Succeed or fail, we want to give it a shot!
DotNetKicks Image

Share/Save/Bookmark