Archivio | ottobre, 2008

Create Microsoft sql database before integration test

16 Ott

In my last post I shown how to create a SqlCe database “on the fly” once before all integration tests. Alexander asked me how can do the same thing but using a Microsoft Sql database. Let’ s how we can do it:

using (IDbConnection connection = new SqlCeConnection(masterConnectionString))
{
    connection.Open();
      using (IDbCommand command = connection.CreateCommand())
        {
            command.CommandType = CommandType.Text;
            command.CommandText = "CREATE DATABASE UnitTestDemo";
            command.ExecuteNonQuery();
        }
    }
}
//open a new connection to UnitTestDemo database and create all objects
The only difference here is the statement used for the creation of the database. As you can see we need a connection to the master database in order to execute the CREATE DATABASE statement. Once we have the new empty database we can close this first connection, open a new one to test database and run all the scripts for the objects (tables, views, stored procedures, ecc.) creation.
 

Create SqlCe database before integration test

7 Ott

In these days I’m developing a smart client application that use a Sql Compact Edition database as local storage.
I’m using NHibernate to query the database and one of the things I need to check are my mapping files.
In order to accomplish this task I setup a series of integration tests. Once before all tests I run a method that create an empty database.
In fact using SqlCeEngine class I can create the empty database using CreateDatase method.
Later than with a simple SqlCeConnection I run a set of sql commands saved in .sql file in order to create all the objects inside my database.

const string connectionString = @"Data Source=|DataDirectory|demo.sdf";
var engine = new SqlCeEngine(connectionString);
engine.CreateDatabase(); 

string[] commands = File.ReadAllText(@"C:Projectsdemo002.CreateTables.sqlce").Split(';');
using (IDbConnection connection = new SqlCeConnection(connectionString))
{
    connection.Open();
    foreach (var commandText in commands)
    {
        if (string.IsNullOrEmpty(commandText)) continue;
        using (IDbCommand command = connection.CreateCommand())
        {
            command.CommandType = CommandType.Text;
            command.CommandText = commandText;
            command.ExecuteNonQuery();
        }
    }
} 

Simple, easy & clear.