public SqlErrorStore(string connectionString, string connectionKey, int displayCount = DefaultDisplayCount, int rollupSeconds = DefaultRollupSeconds) : base(rollupSeconds) { displayCount = Math.Min(displayCount, MaximumDisplayCount); if (connectionString.IsNullOrEmpty()) { var cs = SqlConnections.GetConnectionString(connectionKey); this.connectionString = cs.ConnectionString; this.providerName = cs.ProviderName; isSqlServer = cs.Dialect.ServerType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase); } else { this.connectionString = connectionString; this.providerName = connectionKey; isSqlServer = providerName.IndexOf("SqlClient", StringComparison.OrdinalIgnoreCase) >= 0; } // check that provider name is valid SqlConnections.GetFactory(this.providerName); if (this.connectionString.IsNullOrEmpty()) { throw new ArgumentOutOfRangeException("settings", "A connection string or connection string name must be specified when using a SQL error store"); } }
private static void RunMigrations() { var defaultConnection = SqlConnections.GetConnectionString("Default"); // safety check to ensure that we are not modifying another database if (defaultConnection.ConnectionString.IndexOf(typeof(SiteInitialization).Namespace + @"_Default_v1") < 0) { return; } using (var sw = new StringWriter()) { var announcer = new TextWriterWithGoAnnouncer(sw) { ShowSql = true }; var runner = new RunnerContext(announcer) { Database = "SqlServer", Connection = defaultConnection.ConnectionString, Target = typeof(SiteInitialization).Assembly.Location, Task = "migrate:up", WorkingDirectory = Path.GetDirectoryName(typeof(SiteInitialization).Assembly.Location), Namespace = "Cengaver.Migrations.DefaultDB" }; new TaskExecutor(runner).Execute(); } }
private static void EnsureDatabase() { using (var connection = SqlConnections.NewByKey("Default")) try { connection.Open(); } catch { var cb = new DbConnectionStringBuilder(); cb.ConnectionString = SqlConnections.GetConnectionString("Default").ConnectionString; var catalog = cb["Initial Catalog"]; cb["Initial Catalog"] = null; cb["AttachDBFilename"] = null; using (var serverConnection = new SqlConnection(cb.ConnectionString)) { serverConnection.Open(); serverConnection.Execute(String.Format( @"CREATE DATABASE [{0}] ON PRIMARY (Name = N'{0}', FILENAME = '{1}\{0}.mdf') LOG ON (NAME = N'{0}_log', FILENAME = '{1}\{0}.ldf');", catalog, HostingEnvironment.MapPath("~/App_Data"))); } SqlConnection.ClearAllPools(); } RunMigrations(); }
private static void RunMigrations(string databaseKey) { var cs = SqlConnections.GetConnectionString(databaseKey); var connection = cs.ConnectionString; string serverType = cs.Dialect.ServerType; bool isSqlServer = serverType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase); bool isOracle = !isSqlServer && serverType.StartsWith("Oracle", StringComparison.OrdinalIgnoreCase); // safety check to ensure that we are not modifying an arbitrary database. // remove these lines if you want SmartCar migrations to run on your DB. /*if (!isOracle && cs.ConnectionString.IndexOf(typeof(SiteInitialization).Namespace + * @"_" + databaseKey + "_v1", StringComparison.OrdinalIgnoreCase) < 0) * { * SkippedMigrations = true; * return; * }*/ string databaseType = isOracle ? "OracleManaged" : serverType; var connectionString = cs.ConnectionString; using (var sw = new StringWriter()) { Announcer announcer = isOracle ? new TextWriterAnnouncer(sw) { ShowSql = true } : new TextWriterWithGoAnnouncer(sw) { ShowSql = true }; var runner = new RunnerContext(announcer) { Database = databaseType, Connection = connectionString, Targets = new string[] { typeof(SiteInitialization).Assembly.Location }, Task = "migrate:up", WorkingDirectory = Path.GetDirectoryName(typeof(SiteInitialization).Assembly.Location), Namespace = "SmartCar.Migrations." + databaseKey + "DB", Timeout = 90 }; try { new TaskExecutor(runner).Execute(); } catch (Exception ex) { throw new Exception("Error executing migration:\r\n" + sw.ToString(), ex); } } }
private static void RunMigrations(string databaseKey) { var cs = SqlConnections.GetConnectionString(databaseKey); var connection = cs.ConnectionString; bool isOracle = cs.Dialect.GetType() == typeof(OracleDialect); // safety check to ensure that we are not modifying an arbitrary database. // remove these lines if you want TestThisSerene migrations to run on your DB. if (!isOracle && cs.ConnectionString.IndexOf(typeof(SiteInitialization).Namespace + @"_" + databaseKey + "_v1", StringComparison.OrdinalIgnoreCase) < 0) { SkippedMigrations = true; return; } string databaseType = "SqlServer"; if (String.Equals(cs.ProviderName, "npgsql", StringComparison.OrdinalIgnoreCase)) databaseType = "Postgres"; else if (String.Equals(cs.ProviderName, "MySql.Data.MySqlClient", StringComparison.OrdinalIgnoreCase)) databaseType = "MySql"; else if (isOracle) databaseType = "OracleManaged"; using (var sw = new StringWriter()) { Announcer announcer = isOracle ? new TextWriterAnnouncer(sw) { ShowSql = true } : new TextWriterWithGoAnnouncer(sw) { ShowSql = true }; var runner = new RunnerContext(announcer) { Database = databaseType, Connection = cs.ConnectionString, Targets = new string[] { typeof(SiteInitialization).Assembly.Location }, Task = "migrate:up", WorkingDirectory = Path.GetDirectoryName(typeof(SiteInitialization).Assembly.Location), Namespace = "TestThisSerene.Migrations." + databaseKey + "DB" }; try { new TaskExecutor(runner).Execute(); } catch (Exception ex) { throw new Exception("Error executing migration:\r\n" + sw.ToString(), ex); } } }
private static void RunMigrations(string databaseKey) { var cs = SqlConnections.GetConnectionString(databaseKey); var connection = cs.ConnectionString; // safety check to ensure that we are not modifying an arbitrary database. // remove these two lines if you want MovieTutorial migrations to run on your DB. if (cs.ConnectionString.IndexOf(typeof(SiteInitialization).Namespace + @"_" + databaseKey + "_v1", StringComparison.OrdinalIgnoreCase) < 0) { SkippedMigrations = true; return; } string databaseType = "SqlServer"; if (String.Equals(cs.ProviderName, "npgsql", StringComparison.OrdinalIgnoreCase)) { databaseType = "Postgres"; } else if (String.Equals(cs.ProviderName, "MySql.Data.MySqlClient", StringComparison.OrdinalIgnoreCase)) { databaseType = "MySql"; } using (var sw = new StringWriter()) { var announcer = new TextWriterWithGoAnnouncer(sw) { }; var runner = new RunnerContext(announcer) { Database = databaseType, Connection = cs.ConnectionString, Targets = new string[] { typeof(SiteInitialization).Assembly.Location }, Task = "migrate:up", WorkingDirectory = Path.GetDirectoryName(typeof(SiteInitialization).Assembly.Location), Namespace = "MovieTutorial.Migrations." + databaseKey + "DB" }; new TaskExecutor(runner).Execute(); } }
public static void ApplicationStart() { try { SqlSettings.AutoQuotedIdentifiers = true; Serenity.Web.CommonInitialization.Run(); var registrar = Dependency.Resolve <IDependencyRegistrar>(); registrar.RegisterInstance <IAuthorizationService>(new Administration.AuthorizationService()); registrar.RegisterInstance <IAuthenticationService>(new Administration.AuthenticationService()); registrar.RegisterInstance <IPermissionService>(new LogicOperatorPermissionService(new Administration.PermissionService())); registrar.RegisterInstance <IUserRetrieveService>(new Administration.UserRetrieveService()); if (!ConfigurationManager.AppSettings["LDAP"].IsTrimmedEmpty()) { registrar.RegisterInstance <IDirectoryService>(new LdapDirectoryService()); } if (!ConfigurationManager.AppSettings["ActiveDirectory"].IsTrimmedEmpty()) { registrar.RegisterInstance <IDirectoryService>(new ActiveDirectoryService()); } SqlConnections.GetConnectionString("Default").Dialect = SqlServer2008Dialect.Instance; //SqlConnections.GetConnectionString("Northwind").Dialect = SqlServer2008Dialect.Instance; SqlConnections.GetConnectionString("Document").Dialect = SqlServer2008Dialect.Instance; SqlConnections.GetConnectionString("Finance").Dialect = SqlServer2008Dialect.Instance; InitializeExceptionLog(); } catch (Exception ex) { ex.Log(); throw; } foreach (var databaseKey in databaseKeys) { EnsureDatabase(databaseKey); RunMigrations(databaseKey); } }
private IEnumerable <IDisposable> GetHangfireServers() { GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() // Reference the Default connection. If you want to add a new connection to // Hangfire's database then remember to add this connection in your Web.config .UseSqlServerStorage(SqlConnections.GetConnectionString("Default").ConnectionString, new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true, UsePageLocksOnDequeue = true, DisableGlobalLocks = true }); yield return(new BackgroundJobServer()); }
/// <summary> /// Automatically creates a database for the template if it doesn't already exists. /// You might delete this method to disable auto create functionality. /// </summary> private static void EnsureDatabase(string databaseKey) { var cs = SqlConnections.GetConnectionString(databaseKey); var serverType = cs.Dialect.ServerType; bool isSql = serverType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase); bool isPostgres = serverType.StartsWith("Postgres", StringComparison.OrdinalIgnoreCase); bool isMySql = serverType.StartsWith("MySql", StringComparison.OrdinalIgnoreCase); bool isSqlite = serverType.StartsWith("Sqlite", StringComparison.OrdinalIgnoreCase); bool isFirebird = serverType.StartsWith("Firebird", StringComparison.OrdinalIgnoreCase); if (isSqlite) { var contentRoot = Serenity.Dependency.Resolve <IWebHostEnvironment>().ContentRootPath; Directory.CreateDirectory(Path.Combine(contentRoot, "App_Data")); return; } var cb = cs.ProviderFactory.CreateConnectionStringBuilder(); cb.ConnectionString = cs.ConnectionString; if (isFirebird) { if (cb.ConnectionString.IndexOf(@"localhost") < 0 && cb.ConnectionString.IndexOf(@"127.0.0.1") < 0) { return; } var database = cb["Database"] as string; if (string.IsNullOrEmpty(database)) { return; } database = Path.GetFullPath(database); if (File.Exists(database)) { return; } Directory.CreateDirectory(Path.GetDirectoryName(database)); using (var fbConnection = SqlConnections.New(cb.ConnectionString, cs.ProviderName)) { ((WrappedConnection)fbConnection).ActualConnection.GetType() .GetMethod("CreateDatabase", new Type[] { typeof(string), typeof(bool) }) .Invoke(null, new object[] { fbConnection.ConnectionString, false }); } return; } if (!isSql && !isPostgres && !isMySql) { return; } string catalogKey = "?"; foreach (var ck in new[] { "Initial Catalog", "Database", "AttachDBFilename" }) { if (cb.ContainsKey(ck)) { catalogKey = ck; break; } } var catalog = cb[catalogKey] as string; cb[catalogKey] = null; using (var serverConnection = SqlConnections.New(cb.ConnectionString, cs.ProviderName)) { try { serverConnection.Open(); } catch (SqlException ex) { if (ex.Number != -2146232060) { throw; } const string oldVer = @"\v11.0"; if (cb.ConnectionString.IndexOf(oldVer) >= 0) { throw new Exception( "You don't seem to have SQL Express LocalDB 2012 installed.\r\n\r\n" + "If you have Visual Studio 2015 (with SQL LocalDB 2014) " + "try changing '" + databaseKey + "' connection string in WEB.CONFIG to:\r\n\r\n" + cs.ConnectionString.Replace(oldVer, @"\MSSqlLocalDB") + "\r\n\r\nor:\r\n\r\n" + cs.ConnectionString.Replace(oldVer, @"\v12.0") + "';\r\n\r\n" + "You can also try another SQL server type like .\\SQLExpress."); } throw; } string databasesQuery = "SELECT * FROM sys.databases WHERE NAME = @name"; string createDatabaseQuery = @"CREATE DATABASE [{0}]"; if (isPostgres) { databasesQuery = "select * from postgres.pg_catalog.pg_database where datname = @name"; createDatabaseQuery = "CREATE DATABASE \"{0}\""; } else if (isMySql) { databasesQuery = "SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @name"; createDatabaseQuery = "CREATE DATABASE `{0}`"; } if (serverConnection.Query(databasesQuery, new { name = catalog }).Any()) { return; } var isLocalServer = isSql && ( serverConnection.ConnectionString.IndexOf(@"(localdb)\", StringComparison.OrdinalIgnoreCase) >= 0 || serverConnection.ConnectionString.IndexOf(@".\") >= 0 || serverConnection.ConnectionString.IndexOf(@"localhost") >= 0 || serverConnection.ConnectionString.IndexOf(@"127.0.0.1") >= 0); string command; if (isLocalServer) { string baseDirectory; var hostingEnvironment = Serenity.Dependency.TryResolve <IWebHostEnvironment>(); if (hostingEnvironment != null) { baseDirectory = hostingEnvironment.ContentRootPath; } else { baseDirectory = AppDomain.CurrentDomain.BaseDirectory; } var filename = Path.Combine(Path.Combine(baseDirectory, "App_Data/".Replace('/', Path.DirectorySeparatorChar)), catalog); Directory.CreateDirectory(Path.GetDirectoryName(filename)); command = String.Format(@"CREATE DATABASE [{0}] ON PRIMARY (Name = N'{0}', FILENAME = '{1}.mdf') LOG ON (NAME = N'{0}_log', FILENAME = '{1}.ldf')", catalog, filename); if (File.Exists(filename + ".mdf")) { command += " FOR ATTACH"; } } else { command = String.Format(createDatabaseQuery, catalog); } serverConnection.Execute(command); SqlConnection.ClearAllPools(); } }
private static void RunMigrations(string databaseKey) { var cs = SqlConnections.GetConnectionString(databaseKey); var connection = cs.ConnectionString; string serverType = cs.Dialect.ServerType; bool isSqlServer = serverType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase); bool isOracle = serverType.StartsWith("Oracle", StringComparison.OrdinalIgnoreCase); bool isFirebird = serverType.StartsWith("Firebird", StringComparison.OrdinalIgnoreCase); // safety check to ensure that we are not modifying an arbitrary database. // remove these lines if you want Serene migrations to run on your DB. if (!isOracle && cs.ConnectionString.IndexOf(typeof(DataMigrations).Namespace + @"_" + databaseKey + "_v1", StringComparison.OrdinalIgnoreCase) < 0) { SkippedMigrations = true; return; } string databaseType = isOracle ? "OracleManaged" : serverType; using (var sw = new StringWriter()) { Announcer announcer = isOracle || isFirebird ? new TextWriterAnnouncer(sw) { ShowSql = true } : new TextWriterWithGoAnnouncer(sw) { ShowSql = true }; var runner = new RunnerContext(announcer) { Database = databaseType, Connection = cs.ConnectionString, #if COREFX TargetAssemblies = new[] { typeof(DataMigrations).Assembly }, #else Targets = new string[] { typeof(DataMigrations).Assembly.Location }, #endif Task = "migrate:up", WorkingDirectory = Path.GetDirectoryName(typeof(DataMigrations).Assembly.Location), Namespace = "Serene.Migrations." + databaseKey + "DB", Timeout = 90 }; var culture = CultureInfo.CurrentCulture; try { if (isFirebird) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; } new TaskExecutor(runner) { #if COREFX ConnectionString = cs.ConnectionString #endif }.Execute(); } catch (Exception ex) { var output = sw.ToString().Trim(); if (output.StartsWith("/*")) { var idx = output.IndexOf("*/"); output = output.Substring(idx + 2); } throw new Exception("Error executing migration:\r\n" + output, ex); } finally { if (isFirebird) { Thread.CurrentThread.CurrentCulture = culture; } } } }
/// <summary> /// Automatically creates a database for the template if it doesn't already exists. /// You might delete this method to disable auto create functionality. /// </summary> private static void EnsureDatabase(string databaseKey) { var cs = SqlConnections.GetConnectionString(databaseKey); var serverType = cs.Dialect.ServerType; bool isSql = serverType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase); bool isPostgres = !isSql& serverType.StartsWith("Postgres", StringComparison.OrdinalIgnoreCase); bool isMySql = !isSql && !isPostgres && serverType.StartsWith("MySql", StringComparison.OrdinalIgnoreCase); bool isSqlite = !isSql && !isPostgres && !isMySql && serverType.StartsWith("Sqlite", StringComparison.OrdinalIgnoreCase); if (!isSql && !isPostgres && !isMySql && !isSqlite) { return; } var cb = cs.ProviderFactory.CreateConnectionStringBuilder(); cb.ConnectionString = cs.ConnectionString; string catalogKey = "?"; if (isSqlite) { catalogKey = "Data Source"; if (!cb.ContainsKey(catalogKey)) { return; } var dataFile = cb[catalogKey] as string; if (string.IsNullOrEmpty(dataFile)) { return; } dataFile = dataFile.Replace("|DataDirectory|", HostingEnvironment.MapPath("~/App_Data/")); if (File.Exists(dataFile)) { return; } Directory.CreateDirectory(Path.GetDirectoryName(dataFile)); using (var sqliteConn = SqlConnections.New(cb.ConnectionString, cs.ProviderName)) { var createFile = ((WrappedConnection)sqliteConn).ActualConnection.GetType().GetMethod("CreateFile", BindingFlags.Static); if (createFile != null) { createFile.Invoke(null, new object[] { dataFile }); } } SqlConnection.ClearAllPools(); return; } foreach (var ck in new[] { "Initial Catalog", "Database", "AttachDBFilename" }) { if (cb.ContainsKey(ck)) { catalogKey = ck; break; } } var catalog = cb[catalogKey] as string; cb[catalogKey] = null; using (var serverConnection = SqlConnections.New(cb.ConnectionString, cs.ProviderName)) { try { serverConnection.Open(); } catch (SqlException ex) { if (ex.ErrorCode != -2146232060) { throw; } const string oldVer = @"\v11.0"; if (cb.ConnectionString.IndexOf(oldVer) >= 0) { throw new Exception( "You don't seem to have SQL Express LocalDB 2012 installed.\r\n\r\n" + "If you have Visual Studio 2015 (with SQL LocalDB 2014) " + "try changing '" + databaseKey + "' connection string in WEB.CONFIG to:\r\n\r\n" + cs.ConnectionString.Replace(oldVer, @"\MSSqlLocalDB") + "\r\n\r\nor:\r\n\r\n" + cs.ConnectionString.Replace(oldVer, @"\v12.0") + "';\r\n\r\n" + "You can also try another SQL server type like .\\SQLExpress."); } throw; } string databasesQuery = "SELECT * FROM sys.databases WHERE NAME = @name"; string createDatabaseQuery = @"CREATE DATABASE [{0}]"; if (isPostgres) { databasesQuery = "select * from postgres.pg_catalog.pg_database where datname = @name"; createDatabaseQuery = "CREATE DATABASE \"{0}\""; } else if (isMySql) { databasesQuery = "SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @name"; createDatabaseQuery = "CREATE DATABASE `{0}`"; } if (serverConnection.Query(databasesQuery, new { name = catalog }).Any()) { return; } var isLocalServer = isSql && serverConnection.ConnectionString.IndexOf(@"(localdb)\", StringComparison.OrdinalIgnoreCase) >= 0 || serverConnection.ConnectionString.IndexOf(@".\") >= 0; string command; if (isLocalServer) { var filename = Path.Combine(HostingEnvironment.MapPath("~/App_Data"), catalog); command = String.Format(@"CREATE DATABASE [{0}] ON PRIMARY (Name = N'{0}', FILENAME = '{1}.mdf') LOG ON (NAME = N'{0}_log', FILENAME = '{1}.ldf')", catalog, filename); if (File.Exists(filename + ".mdf")) { command += " FOR ATTACH"; } } else { command = String.Format(createDatabaseQuery, catalog); } serverConnection.Execute(command); SqlConnection.ClearAllPools(); } }
/// <summary> /// Automatically creates a database for the template if it doesn't already exists. /// You might delete this method to disable auto create functionality. /// </summary> private static void EnsureDatabase(string databaseKey) { var cs = SqlConnections.GetConnectionString(databaseKey); if (cs.Dialect.GetType() == typeof(OracleDialect)) { return; } var cb = cs.ProviderFactory.CreateConnectionStringBuilder(); cb.ConnectionString = cs.ConnectionString; string catalogKey = "?"; foreach (var ck in new[] { "Initial Catalog", "Database", "AttachDBFilename" }) { if (cb.ContainsKey(ck)) { catalogKey = ck; break; } } var catalog = cb[catalogKey] as string; cb[catalogKey] = null; using (var serverConnection = SqlConnections.New(cb.ConnectionString, cs.ProviderName)) { try { serverConnection.Open(); } catch (SqlException ex) { if (ex.ErrorCode != -2146232060) { throw; } const string oldVer = @"\v11.0"; if (cb.ConnectionString.IndexOf(oldVer) >= 0) { throw new Exception( "You don't seem to have SQL Express LocalDB 2012 installed.\r\n\r\n" + "If you have Visual Studio 2015 (with SQL LocalDB 2014) " + "try changing '" + databaseKey + "' connection string in WEB.CONFIG to:\r\n\r\n" + cs.ConnectionString.Replace(oldVer, @"\MSSqlLocalDB") + "\r\n\r\nor:\r\n\r\n" + cs.ConnectionString.Replace(oldVer, @"\v12.0") + "';\r\n\r\n" + "You can also try another SQL server type like .\\SQLExpress."); } throw; } string databasesQuery = "SELECT * FROM sys.databases WHERE NAME = @name"; string createDatabaseQuery = @"CREATE DATABASE [{0}]"; if (String.Equals(cs.ProviderName, "npgsql", StringComparison.OrdinalIgnoreCase)) { databasesQuery = "select * from postgres.pg_catalog.pg_database where datname = @name"; createDatabaseQuery = "CREATE DATABASE \"{0}\""; } if (String.Equals(cs.ProviderName, "MySql.Data.MySqlClient", StringComparison.OrdinalIgnoreCase)) { databasesQuery = "SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = @name"; createDatabaseQuery = "CREATE DATABASE `{0}`"; } if (serverConnection.Query(databasesQuery, new { name = catalog }).Any()) { return; } var isLocalServer = serverConnection.ConnectionString.IndexOf(@"(localdb)\", StringComparison.OrdinalIgnoreCase) >= 0 || serverConnection.ConnectionString.IndexOf(@".\") >= 0; string command; if (isLocalServer) { var filename = Path.Combine(HostingEnvironment.MapPath("~/App_Data"), catalog); command = String.Format(@"CREATE DATABASE [{0}] ON PRIMARY (Name = N'{0}', FILENAME = '{1}.mdf') LOG ON (NAME = N'{0}_log', FILENAME = '{1}.ldf')", catalog, filename); if (File.Exists(filename + ".mdf")) { command += " FOR ATTACH"; } } else { command = String.Format(createDatabaseQuery, catalog); } serverConnection.Execute(command); SqlConnection.ClearAllPools(); } }
private static void RunMigrations(string databaseKey) { var cs = SqlConnections.GetConnectionString(databaseKey); var connection = cs.ConnectionString; string serverType = cs.Dialect.ServerType; bool isSqlServer = serverType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase); bool isOracle = serverType.StartsWith("Oracle", StringComparison.OrdinalIgnoreCase); bool isFirebird = serverType.StartsWith("Firebird", StringComparison.OrdinalIgnoreCase); string databaseType = isOracle ? "OracleManaged" : serverType; using (var sw = new StringWriter()) { Announcer announcer = isOracle || isFirebird ? new TextWriterAnnouncer(sw) { ShowSql = true } : new TextWriterWithGoAnnouncer(sw) { ShowSql = true }; var runner = new RunnerContext(announcer) { Database = databaseType, Connection = cs.ConnectionString, #if COREFX TargetAssemblies = new[] { typeof(DataMigrations).Assembly }, #else Targets = new string[] { typeof(DataMigrations).Assembly.Location }, #endif Task = "migrate:up", WorkingDirectory = Path.GetDirectoryName(typeof(DataMigrations).Assembly.Location), Namespace = "BenoyInsPortal.Migrations." + databaseKey + "DB", Timeout = 90 }; var culture = CultureInfo.CurrentCulture; try { if (isFirebird) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; } new TaskExecutor(runner) { #if COREFX ConnectionString = cs.ConnectionString #endif }.Execute(); } catch (Exception ex) { throw new Exception("Error executing migration:\r\n" + sw.ToString(), ex); } finally { if (isFirebird) { Thread.CurrentThread.CurrentCulture = culture; } } } }
/// <summary> /// Automatically creates a database for the template if it doesn't already exists. /// You might delete this method to disable auto create functionality. /// </summary> private static void EnsureDatabase() { var cs = SqlConnections.GetConnectionString("Default"); var cb = new DbConnectionStringBuilder(); cb.ConnectionString = cs.ConnectionString; var catalog = cb["Initial Catalog"] as string; cb["Initial Catalog"] = null; cb["AttachDBFilename"] = null; using (var serverConnection = new SqlConnection(cb.ConnectionString)) { try { serverConnection.Open(); } catch (SqlException ex) { if (ex.ErrorCode != -2146232060) { throw; } const string oldVer = @"\v11.0"; if (cb.ConnectionString.IndexOf(oldVer) >= 0) { throw new Exception( "You don't seem to have SQL Express LocalDB 2012 installed.\r\n\r\n" + "If you have Visual Studio 2015 (with SQL LocalDB 2014) " + "try changing 'Default' connection string in WEB.CONFIG to:\r\n\r\n" + cs.ConnectionString.Replace(oldVer, @"\MSSqlLocalDB") + "\r\n\r\nor:\r\n\r\n" + cs.ConnectionString.Replace(oldVer, @"\v12.0") + "';\r\n\r\n" + "You can also try another SQL server type like .\\SQLExpress."); } throw; } if (serverConnection.Query("SELECT * FROM sys.databases WHERE NAME = @name", new { name = catalog }).Any()) { return; } var isLocalServer = serverConnection.ConnectionString.IndexOf(@"(localdb)\", StringComparison.OrdinalIgnoreCase) >= 0 || serverConnection.ConnectionString.IndexOf(@".\") >= 0; string command; if (isLocalServer) { var filename = Path.Combine(HostingEnvironment.MapPath("~/App_Data"), catalog); command = String.Format(@"CREATE DATABASE [{0}] ON PRIMARY (Name = N'{0}', FILENAME = '{1}.mdf') LOG ON (NAME = N'{0}_log', FILENAME = '{1}.ldf')", catalog, filename); if (File.Exists(filename + ".mdf")) { command += " FOR ATTACH"; } } else { command = String.Format(@"CREATE DATABASE [{0}]", catalog); } serverConnection.Execute(command); SqlConnection.ClearAllPools(); } }
private static void RunMigrations(string databaseKey) { var cs = SqlConnections.GetConnectionString(databaseKey); var connection = cs.ConnectionString; string serverType = cs.Dialect.ServerType; bool isSqlServer = serverType.StartsWith("SqlServer", StringComparison.OrdinalIgnoreCase); bool isOracle = serverType.StartsWith("Oracle", StringComparison.OrdinalIgnoreCase); bool isFirebird = serverType.StartsWith("Firebird", StringComparison.OrdinalIgnoreCase); //// safety check to ensure that we are not modifying an arbitrary database. //// remove these lines if you want PatientManagement migrations to run on your DB. //if (!isOracle && cs.ConnectionString.IndexOf(typeof(DataMigrations).Namespace + // @"_" + databaseKey + "_v1", StringComparison.OrdinalIgnoreCase) < 0) //{ // SkippedMigrations = true; // return; //} string databaseType = isOracle ? "OracleManaged" : serverType; using (var sw = new StringWriter()) { Announcer announcer = isOracle || isFirebird ? new TextWriterAnnouncer(sw) { ShowSql = true } : new TextWriterWithGoAnnouncer(sw) { ShowSql = true }; var runner = new RunnerContext(announcer) { Database = databaseType, Connection = cs.ConnectionString, TargetAssemblies = new[] { typeof(DataMigrations).GetAssembly() }, Task = "migrate:up", WorkingDirectory = Path.GetDirectoryName(typeof(DataMigrations).GetAssembly().Location), Namespace = "PatientManagement.Migrations." + databaseKey + "DB", Timeout = 90 }; var culture = CultureInfo.CurrentCulture; try { if (isFirebird) { CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; } new TaskExecutor(runner) { ConnectionString = cs.ConnectionString }.Execute(); } catch (Exception ex) { throw new Exception("Error executing migration:\r\n" + sw.ToString(), ex); } finally { if (isFirebird) { CultureInfo.CurrentCulture = culture; } } } }