private void CheckCE()
{
// connect to db using connection string from parent app
using (SqlCeConnection cn = new SqlCeConnection(_cnConfig.ToString()))
{
// try to open db file but if can't locate then create and try again
try
{
cn.Open();
}
catch (Exception ex)
{
if (ex.Message.Contains("The database file cannot be found."))
{
using (SqlCeEngine ce = new SqlCeEngine(_cnConfig.ToString()))
{
ce.CreateDatabase();
}
cn.Open();
}
else
{
throw;
}
}
// check if schema exists - if so there should always be a migration history table
if (!CETableExists("__MigrationHistory", cn) && !CETableExists("MigrationHistory", cn)) NewInstall = true;
// Rename __MigrationHistory table to MigrationHistory (prevents entity framework version check)
if (CETableExists("__MigrationHistory", cn))
{
ExecCENativeSQL(Properties.Resources.RenameMigrationHistory, cn);
}
// if no schema then create entire schema then populate bitmasks
if (NewInstall)
{
// create main schema
_sql = Properties.Resources.CreateEntireSchema;
if (_cnConfig.ProviderName.Equals("System.Data.?SqlClient")) // should never be true - lifted logic as-is from "broken" migration
{ // so exactly matches latest db structure that theoretically should
_sql += Properties.Resources._201306050753190_ProgressiveLoad; // not have the sprocs that ProgressiveLoad introduces.
}
ExecCENativeSQL(_sql, cn);
// populate bitmasks
EnsureBitmasksPopulated();
}
else
{
// schema exists - build list of already executed migration steps
_sql = "SELECT MigrationId AS MigrationTitle FROM [MigrationHistory] WITH (NOLOCK) ORDER BY MigrationId";
using (SqlCeCommand cmd = new SqlCeCommand(_sql, cn))
{
using (SqlCeDataReader rs = cmd.ExecuteResultSet(ResultSetOptions.Scrollable)) //cmd.ExecuteReader())
{
if (rs.HasRows)
{
while (rs.Read())
{
string[] titleParts = rs["MigrationTitle"].ToString().Split('_'); // 0 will be key, 1 will be value (description).
if (!_migrated.ContainsKey(titleParts[0]))
{
_migrated.Add(titleParts[0], titleParts[1]);
}
}
}
}
}
// see if any migration stepa are missing - if so build sql in correct order which should also note step completed in db
_sql = BuildAnyMissingMigrationStepsSQL(_migrated);
// if any steps were missing
if (_sql != "")
{
// execute sql for any missing steps
ExecCENativeSQL(_sql, cn);
// ensure bitmasks are populated/repopulated
EnsureBitmasksPopulated();
}
}
cn.Close();
}
}