public override IDatabaseSchema Load(DbConfiguration cfg) { var databaseSchema = new DatabaseSchema(); ColumnInfo[] allColumns = null; ForeignKeyInfo[] allFks = null; using (var ctx = cfg.CreateDbContext()) { InitConnection(ctx.Connection); using (var reader = ctx.DbHelper.ExecuteReader(AllColumnsSql)) allColumns = reader.ToList<ColumnInfo>().ToArray(); using (var reader = ctx.DbHelper.ExecuteReader(AllFKsSql)) allFks = reader.ToList<ForeignKeyInfo>().ToArray(); } Dictionary<string, TableSchema> tables = new Dictionary<string,TableSchema>(); foreach (var c in allColumns) { TableSchema table = null; if (!tables.TryGetValue(c.TableName, out table)) { table = new TableSchema { TableName = c.TableName, IsView = c.IsView }; tables[c.TableName] = table; } var key = allFks.FirstOrDefault(p => p.Type == "P" && p.ThisTableName == c.TableName && p.ThisKey == c.ColumnName); c.IsPrimaryKey = key != null; var column = ToColumn(c); table.AddColumn(column); } foreach(var item in allFks.Where(p=>p.OtherTableName.HasValue())) { TableSchema thisTable = tables[item.OtherTableName]; TableSchema otherTable = tables[item.ThisTableName]; IColumnSchema thisKey = thisTable.AllColumns.FirstOrDefault(p=>p.ColumnName == item.OtherKey); IColumnSchema otherKey = otherTable.AllColumns.FirstOrDefault(p => p.ColumnName == item.ThisKey); thisTable.AddFK(new ForeignKeySchema { ThisTable = thisTable, Name = item.Name , ThisKey = thisKey, OtherTable = otherTable, OtherKey = otherKey }); } databaseSchema.Tables = tables.Values.Where(p => !p.IsView).ToArray(); databaseSchema.Views = tables.Values.Where(p => p.IsView).ToArray(); return databaseSchema; }
public DLinqConnection() { const string connectionStringName = "Northwind"; //DbConfiguration.InitializeDLinq<System.Data.Linq.Binary>(); if (!DbConfiguration.Items.TryGetValue(connectionStringName, out dbConfiguration)) { dbConfiguration = DbConfiguration.Configure(connectionStringName) .SetSqlLogger(() => new SqlLog(Console.Out)) .AddFromAssemblyOf<NLite.Data.Test.LinqToSql.Customers>(p => p.HasAttribute<System.Data.Linq.Mapping.TableAttribute>(false)); } var customerMapper = dbConfiguration.GetClass<Customers>(); Assert.IsNotNull(customerMapper); var orderMapper = dbConfiguration.GetClass<Orders>(); Assert.IsNotNull(orderMapper); var employeesMapper = dbConfiguration.GetClass<Employees>(); Assert.IsNotNull(employeesMapper); var employeeTerritoriesMapper = dbConfiguration.GetClass<EmployeeTerritories>(); Assert.IsNotNull(employeeTerritoriesMapper); var ProductsMapper = dbConfiguration.GetClass<Products>(); Assert.IsNotNull(ProductsMapper); var SuppliersMapper = dbConfiguration.GetClass<Suppliers>(); Assert.IsNotNull(SuppliersMapper); var TerritoriesMapper = dbConfiguration.GetClass<Territories>(); Assert.IsNotNull(TerritoriesMapper); }
public override void DeleteDatabase(DbConfiguration dbConfiguration) { var connectionStringBuilder = dbConfiguration.DbProviderFactory.CreateConnectionStringBuilder(); connectionStringBuilder.ConnectionString = dbConfiguration.ConnectionString; var dbName = GetDatabaseName(connectionStringBuilder); var dbPassword = GetPWD(connectionStringBuilder); var deleteDatabase = "Drop USER " + dbName + " CASCADE"; dbConfiguration.sqlLogger().LogMessage(deleteDatabase); connectionStringBuilder["USER ID"] = "SYSTEM"; connectionStringBuilder["Password"] = dbPassword; var log = dbConfiguration.sqlLogger(); using (var ctx = dbConfiguration.CreateDbContext()) { var conn = ctx.Connection; conn.ConnectionString = connectionStringBuilder.ConnectionString; var cmd = conn.CreateCommand(); cmd.CommandText = deleteDatabase; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } }
static teaCRMDBContext() { dbConfiguration = DbConfiguration .Configure(connectionStringName) .SetSqlLogger(() => SqlLog.Debug) .AddFromAssemblyOf <teaCRMDBContext>(t => t.HasAttribute <TableAttribute>(false)) ; }
public void SetDbConfiguration(string sqlStrategyTypeName) { if (!string.IsNullOrWhiteSpace(sqlStrategyTypeName)) { var dbConfig = new SqlDbConfiguration(sqlStrategyTypeName); DbConfiguration.SetConfiguration(dbConfig); } }
public override void PreInitialize() { DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); Database.SetInitializer(new CreateDatabaseIfNotExists <TaiKangDbContext>()); //web.config (or app.config for non-web projects) file should contain a connection string named "Default". Configuration.DefaultNameOrConnectionString = "MySqlDbContext"; }
public DBZugriff() { DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); Init(); PreLoadContext(); }
/// <summary> /// Initializes a new instance of the <see cref="MySqlDbContext" /> class. /// </summary> /// <param name="nameOrConnectionString">Database connection string or configuration file key name</param> public MySqlDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); Configuration.AutoDetectChangesEnabled = true; Configuration.ProxyCreationEnabled = false; Database.SetInitializer(new MigrateDatabaseToLatestVersion <MySqlDbContext, Configuration>(nameOrConnectionString)); }
// public StatisticContext(string n) //: base("StatisticContext") // { // DbConfiguration.SetConfiguration(new SQLiteConfiguration()); // } public StatisticContext() : base(new SQLiteConnection() { ConnectionString = "Data Source=.\\Data\\data.db" }, true) { DbConfiguration.SetConfiguration(new SQLiteConfiguration()); }
/// <summary> /// Initializes an instance of the <see cref="DesignTimeDbContextFactoryBase{TContext}"/> class. /// </summary> /// <param name="dbConfigurationOptions">The options.</param> /// <param name="loggerFactory">The logger factory.</param> protected DesignTimeDbContextFactoryBase(IOptions <DbConfiguration> dbConfigurationOptions, ILoggerFactory loggerFactory) { _dbConfiguration = dbConfigurationOptions == null ? GetDbConfiguration() : dbConfigurationOptions.Value; _loggerFactory = loggerFactory; }
static DatabaseManager() { DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); Settings.TryAdd(ConnectionType.Account, new ConnectionSettings("localhost", "root", "1234", "account_cq", 3306)); Settings.TryAdd(ConnectionType.Game, new ConnectionSettings("localhost", "root", "1234", "cq", 3306)); Settings.TryAdd(ConnectionType.Log, new ConnectionSettings("localhost", "root", "1234", "cq", 3306)); }
/** * Mencari string pada newsList dengan urutan judul baru kemudian isi. * * @param newsList list berita dari database * @param searchQuery search pattern yang digunakan * @return List berita yang lolos search dengan lokasi ditemukannya */ public ActionResult Index(string searchQuery, int searchType) { DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); String connectionString = "server=127.0.0.1;User Id=root;password=password;database=db_newscrawler"; MySqlConnection connection = new MySqlConnection(connectionString); NewsCrawlerDB dbNews = new NewsCrawlerDB(connection, false); dbNews.Database.CreateIfNotExists(); connection.Open(); // Empty tables MySqlCommand cmd = new MySqlCommand("delete from News", connection); cmd.ExecuteNonQuery(); dbNews.SaveChanges(); MySqlTransaction transaction = connection.BeginTransaction(); dbNews.Database.UseTransaction(transaction); // Get data from RSS Loader.loadRSS("http://rss.detik.com/index.php/detikcom", dbNews); Loader.loadRSS("http://tempo.co/rss/terkini", dbNews); Loader.loadRSS("http://rss.vivanews.com/get/all", dbNews); transaction.Commit(); // Convert news list to array News[] newsArray = dbNews.News.SqlQuery("select * from News").ToArray(); List <NewsFound> newsFound = new List <NewsFound>(); // Do Search if (searchType == 0) { newsFound = searchKMP(newsArray, searchQuery); } else if (searchType == 1) { newsFound = searchBM(newsArray, searchQuery); } else if (searchType == 2) { newsFound = searchRegex(newsArray, searchQuery); } else if (searchType == 3) { //debug to show all news newsFound = showAll(newsArray); } ViewBag.regexQuery = Searcher.regexConvert(searchQuery); ViewBag.searchQuery = searchQuery; ViewBag.searchType = searchType; ViewBag.searchResult = newsFound; ViewBag.searchCount = newsFound.Count; return(View()); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); //Reglas.RNUsuario.Register(new Entidades.Usuario() //{ // Activo = true, // Password = "******", // Username = "******", // Nombre = "Damian", // Email = "*****@*****.**", // Apellido = "Guillermi", // Descripcion = "Vendedor de cursos online de programacion.", // Vendedor = true //} // ); //Reglas.RNUsuario.Register(new Entidades.Usuario() //{ // Activo = true, // Password = "******", // Username = "******", // Nombre = "Mateo", // Email = "*****@*****.**", // Apellido = "Tozzini", // Descripcion = "Vendedor de cursos online de cocina.", // Vendedor = true //} // ); //Reglas.RNUsuario.Register(new Entidades.Usuario() //{ // Activo = true, // Password = "******", // Username = "******", // Nombre = "Lucas", // Email = "*****@*****.**", // Apellido = "Denicola", // Descripcion = "Vendedor de cursos online de Anime.", // Vendedor = true //} // ); //Reglas.RNUsuario.Register(new Entidades.Usuario() //{ // Activo = true, // Password = "******", // Username = "******", // Nombre = "Ezequiel", // Email = "*****@*****.**", // Apellido = "Fleire", // Descripcion = "Vendedor de cursos online de guitarra.", // Vendedor = true //} // ); }
protected DbContextBase(IConfiguration configuration, TenancyConfiguration tenancyConfiguration, IGuidGenerator generator, params IConfigurationModule[] modules) : base(configuration.DatabaseConnection) { DbConfiguration.SetConfiguration(tenancyConfiguration); _generator = generator; _modules = modules; }
public Configuration2() { DbConfiguration.SetConfiguration(new DbConfigurationBase("SQLCE")); DbInterception.Add(new NLogCommandInterceptor()); // guardar logs AutomaticMigrationsEnabled = true; AutomaticMigrationDataLossAllowed = true; }
private void SetupDbContext(string databaseName) { var connectionString = $"Host=localhost;Database={databaseName};Username=docker;Password=docker"; var builder = new DbContextOptionsBuilder <GetIntoTeachingDbContext>(); DbConfiguration.ConfigPostgres(connectionString, builder); DbContext = new GetIntoTeachingDbContext(builder.Options); }
public override DbMigrator GetMigrator() { DbConfiguration.SetConfiguration(new EmptyConfiguration()); var config = new Yaaf.Xmpp.MessageArchiveManager.Sql.Migrations.Configuration(); config.TargetDatabase = new DbConnectionInfo(this.Database.Connection.ConnectionString, "System.Data.SqlClient"); return(new DbMigrator(config)); }
public Configuration() { AutomaticMigrationsEnabled = false; CommandTimeout = 3600; DbConfiguration.SetConfiguration(new MySql.Data.Entity.MySqlEFConfiguration()); SetSqlGenerator(MySql.Data.Entity.MySqlProviderInvariantName.ProviderName, new MySql.Data.Entity.MySqlMigrationSqlGenerator()); SetHistoryContextFactory(MySql.Data.Entity.MySqlProviderInvariantName.ProviderName, (connection, schema) => new MySql.Data.Entity.MySqlHistoryContext(connection, schema)); }
/// <summary> /// Initializes an instance of the <see cref="DesignTimeDbContextFactoryBase{TContext}"/> class. /// </summary> /// <param name="dbConfigurationOptions">The options.</param> /// <param name="loggerFactory">The logger factory.</param> /// <param name="enableSensitiveLogging">The enable sensitive logging flag.</param> protected DesignTimeDbContextFactoryBase(IOptions <DbConfiguration> dbConfigurationOptions, ILoggerFactory loggerFactory, bool enableSensitiveLogging) { _dbConfiguration = dbConfigurationOptions == null ? GetDbConfiguration() : dbConfigurationOptions.Value; _loggerFactory = loggerFactory; _enableSensitiveLogging = enableSensitiveLogging; }
private static void SetDbConfiguration(EfCfDbConfiguration efCfDbConfiguration) { DbConfiguration.SetConfiguration(efCfDbConfiguration); // Used to allow a non-static logger for Entity Framework 'ExecutionStrategy.ShouldRetryOn()' method logging. var efCfDbConfigurationLabel = efCfDbConfiguration.ToString(); var traceMsg = string.Format("SetDbConfiguration() called DbConfiguration.SetConfiguration({0}).", efCfDbConfigurationLabel); System.Diagnostics.Trace.WriteLine(traceMsg); }
public override DbMigrator GetMigrator() { DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); var config = new Yaaf.Xmpp.IM.Sql.MySql.Migrations.Configuration(); config.TargetDatabase = new DbConnectionInfo(this.Database.Connection.ConnectionString, "MySql.Data.MySqlClient"); return(new DbMigrator(config)); }
public override void CreateDatabase(DbConfiguration dbConfiguration, DatabaseScriptEntry script) { var connectionStringBuilder = dbConfiguration.DbProviderFactory.CreateConnectionStringBuilder(); connectionStringBuilder.ConnectionString = dbConfiguration.ConnectionString; var dbName = GetDatabaseName(connectionStringBuilder); var dbPassword = GetPWD(connectionStringBuilder); var createDatabase = "CREATE USER " + dbName + " IDENTIFIED BY " + dbPassword; var systemUser = "******"; dbConfiguration.sqlLogger().LogMessage(createDatabase); connectionStringBuilder["USER ID"] = systemUser; connectionStringBuilder["Password"] = dbPassword; var log = dbConfiguration.sqlLogger(); using (var ctx = dbConfiguration.CreateDbContext()) { var conn = ctx.Connection; conn.ConnectionString = connectionStringBuilder.ConnectionString; var cmd = conn.CreateCommand(); cmd.CommandText = createDatabase; conn.Open(); cmd.ExecuteNonQuery(); cmd.CommandText = "GRANT CONNECT,RESOURCE TO " + dbName; cmd.ExecuteNonQuery(); //conn.ChangeDatabase(dbName); conn.Close(); } connectionStringBuilder["USER ID"] = dbName; connectionStringBuilder["Password"] = dbPassword; using (var ctx = dbConfiguration.CreateDbContext()) { var conn = ctx.Connection; conn.ConnectionString = connectionStringBuilder.ConnectionString; conn.Open(); try { ctx.UsingTransaction(() => CreateTables(log, script, ctx)); } catch { conn.Close(); connectionStringBuilder["USER ID"] = systemUser; conn.ConnectionString = connectionStringBuilder.ConnectionString; conn.Open(); var cmd = conn.CreateCommand(); cmd.CommandText = "Drop USER " + dbName + " CASCADE"; cmd.ExecuteNonQuery(); throw; } } }
public GroupContextFactory(IGroupConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException("configuration"); } DbConfiguration.SetConfiguration(new CustomDatabaseConfiguration(configuration)); }
/// <summary> /// 领域层实体映射 /// </summary> private static void EntityMapping() { var mapTypeList = Assembly.GetExecutingAssembly().GetTypes().Where(k => !k.IsGenericType && typeof(IEntityTypeBuilder).IsAssignableFrom(k)).ToList(); foreach (var item in mapTypeList) { DbConfiguration.UseTypeBuilders(item); } }
public AppDbContext() : base("name=AppDbContext") { Database.SetInitializer <AppDbContext>(null); DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); //var objectContext = (this as IObjectContextAdapter).ObjectContext; //objectContext.CommandTimeout = 600; }
protected void Application_Start() { DbConfiguration.SetConfiguration(new AvaliacoesConfiguration()); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); ModelBinders.Binders.Add(typeof(Cos), new CosLegatura()); DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); }
public List <Neighborhood> GetAllNeighborhood() { using (DbConfiguration db = new DbConfiguration()) { return(( from n in db.neighborhoods.Include(n => n.City.Province.Country) select n).ToList()); } }
public void Init() { DbConfiguration.SetConfiguration(new OracleDbConfiguration()); if (Database.Exists(DbConfig)) { Database.Delete(DbConfig); Database.SetInitializer(new DropCreateDatabaseAlways <OracleFullContext>()); } }
public DbCompiledModel GetCompiledDbModel() { if (_compiledModel == null) { DbConfiguration.SetConfiguration(new DbConfigurationSupportedCustomExecutionStrategy()); CreateModel(); } return(_compiledModel); }
public GlimpseDbDependencyResolver(DbConfiguration originalDbConfiguration) { // Get the original resolver var internalConfigProp = originalDbConfiguration.GetType().GetProperty("InternalConfiguration", BindingFlags.Instance | BindingFlags.NonPublic); var internalConfig = internalConfigProp.GetValue(originalDbConfiguration, null); var rootResolverProp = internalConfig.GetType().GetProperty("RootResolver", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); rootResolver = (IDbDependencyResolver)rootResolverProp.GetValue(internalConfig, null); }
public void Start() { DbConfiguration.SetConfiguration(new DefaultDbConfig()); using (var context = new SamplesContext()) { var xx = context.Players.ToArray(); context.SaveChanges(); } }
public Configuration() { AutomaticMigrationsEnabled = false; DbConfiguration.SetConfiguration(new MySqlEFConfiguration()); CodeGenerator = new MySqlMigrationCodeGenerator(); SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator()); SetHistoryContextFactory(MySqlProviderInvariantName.ProviderName, (connection, schema) => new MySqlHistoryContext(connection, schema)); }
// we need to inject DbCofiguration here in order to globally initialize configuration before doing any operations // on EF objects public MetadataWorkspaceFileProvider(RhetosAppOptions rhetosAppOptions, ILogProvider logProvider, ConnectionString connectionString, DbConfiguration dbConfiguration) { _rhetosAppOptions = rhetosAppOptions; _connectionString = connectionString; _performanceLogger = logProvider.GetLogger("Performance." + GetType().Name); _logger = logProvider.GetLogger(nameof(MetadataWorkspaceFileProvider)); _loadedMetadata = new Lazy <MetadataWorkspace>(LoadFromFiles); }
public virtual void CreateTables(DbConfiguration dbConfiguration, DatabaseScriptEntry script) { var log = dbConfiguration.sqlLogger(); using (var ctx = dbConfiguration.CreateDbContext()) { ctx.UsingTransaction(() => { CreateTables(log, script, ctx); }); } }
protected override void OnCreateDatabase(DbConfiguration dbConfiguration, string dbName) { var type = dbConfiguration.DbProviderFactory.GetType().Module.GetType("System.Data.SQLite.SQLiteConnection"); var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod; try { type.InvokeMember("CreateFile", flags, null, null, new object[] { dbName }); } catch (TargetInvocationException ex) { throw ex.InnerException; } }
protected override void OnCreateDatabase(DbConfiguration dbConfiguration, string dbName) { var type = dbConfiguration.DbProviderFactory.GetType().Module.GetType("System.Data.SqlServerCe.SqlCeEngine"); var engine = Activator.CreateInstance(type, dbConfiguration.ConnectionString); var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod; try { type.InvokeMember("CreateDatabase", flags, null, engine, new object[0]); } catch (TargetInvocationException ex) { throw ex.InnerException; } }
public override bool DatabaseExists(DbConfiguration dbConfiguration) { try { using (var conn = dbConfiguration.DbProviderFactory.CreateConnection()) { conn.ConnectionString = dbConfiguration.ConnectionString; conn.Open(); conn.Close(); return true; } } catch { return false; } }
static Northwind() { if (!DbConfiguration.Items.TryGetValue(connectionStringName, out dbConfiguration)) { dbConfiguration = DbConfiguration .Configure(connectionStringName) // .SetSqlLogger(() =>SqlLog.Trace) .SetMappingConversion(MappingConversion.Plural) .AddClass<Customer>()//注册映射类 .AddClass<Order>()//注册映射类 .AddClass<OrderDetail>(p => { p.TableName("Order Details"); })//注册映射类 .AddClass<Product>()//注册映射类 // .AddFile("Model\\Northwind.mapping.xml") ; } }
public override void CreateDatabase(DbConfiguration dbConfiguration, DatabaseScriptEntry script) { var dbName = dbConfiguration.DatabaseName; if (File.Exists(dbName)) throw new InvalidOperationException(string.Format("Unable to create database because the database '{0}' already exists.", dbName)); OnCreateDatabase(dbConfiguration, dbName); try { CreateTables(dbConfiguration, script); } catch { try { DeleteDatabase(dbConfiguration); } catch { } throw; } }
public override void CreateDatabase(DbConfiguration dbConfiguration, DatabaseScriptEntry script) { var connectionStringBuilder = dbConfiguration.DbProviderFactory.CreateConnectionStringBuilder(); connectionStringBuilder.ConnectionString = dbConfiguration.ConnectionString; var dbName = dbConfiguration.DatabaseName; var createDatabase = "CREATE DATABASE " + dbName; dbConfiguration.sqlLogger().LogMessage(createDatabase); connectionStringBuilder["Database"] = "mysql"; var log = dbConfiguration.sqlLogger(); using (var ctx = dbConfiguration.CreateDbContext()) { var conn = ctx.Connection; conn.ConnectionString = connectionStringBuilder.ConnectionString; var cmd = conn.CreateCommand(); cmd.CommandText = createDatabase; conn.Open(); cmd.ExecuteNonQuery(); conn.ChangeDatabase(dbName); try { ctx.UsingTransaction(() => { CreateTables(log, script, ctx); }); } catch { conn.ChangeDatabase("mysql"); cmd.CommandText = string.Format("Drop DataBase {0}", dbName); cmd.ExecuteNonQuery(); throw; } } }
public override void DeleteDatabase(DbConfiguration dbConfiguration) { var connectionStringBuilder = dbConfiguration.DbProviderFactory.CreateConnectionStringBuilder(); connectionStringBuilder.ConnectionString = dbConfiguration.ConnectionString; var dbName = dbConfiguration.DatabaseName; var dropDatabase = "DROP DATABASE " + dbConfiguration.Dialect.Quote(dbName); dropDatabase = string.Format(DropDatabaseScriptTemplate, dbName); dbConfiguration.sqlLogger().LogMessage(dropDatabase); using (var ctx = dbConfiguration.CreateDbContext()) using (var cmd = ctx.Connection.CreateCommand()) { connectionStringBuilder["Database"] = "master"; ctx.Connection.ConnectionString = connectionStringBuilder.ConnectionString; cmd.CommandText = dropDatabase; ctx.Connection.Open(); try { cmd.ExecuteNonQuery(); } catch { } try { ctx.Connection.ChangeDatabase(dbName); throw new ApplicationException("drop database failed."); } catch { } } }
protected override void OnCreateDatabase(DbConfiguration dbConfiguration, string dbName) { var asm = Assembly.Load("Interop.ADOX"); Guard.NotNull(asm, "asm"); var type = asm.GetType("ADOX.CatalogClass"); Guard.NotNull(type, "type"); var flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod; try { var catalog = Activator.CreateInstance(type); var method = type.GetMethod("Create"); Guard.NotNull(method, "method"); method.Invoke(catalog, new object[] { dbConfiguration.ConnectionString }); // type.InvokeMember("Create", flags, null, catalog, new object[] { dbConfiguration.ConnectionString }); } catch (TargetInvocationException ex) { throw ex.InnerException; } }
private static TableSchema[] LoadData(DbConfiguration cfg, Dictionary<string, List<ForeignKeyInfo>> allFks, Dictionary<string, DataTable> allColumns) { TableSchema[] tables = null; using (var conn = cfg.DbProviderFactory.CreateConnection()) { const BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance; if (GetSchemaTableMethod == null) lock (Mutext) GetSchemaTableMethod = conn.GetType().Module .GetType("System.Data.SQLite.SQLiteDataReader") .GetMethod("GetSchemaTable", flags) .GetFunc(); conn.ConnectionString = cfg.ConnectionString; conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"SELECT case when type LIKE 'view' then 1 else 0 end as Isview , name as TableName FROM main.sqlite_master WHERE ([type] LIKE 'table' OR [type] LIKE 'view') and [name] not like 'sqlite%'"; using (var reader = cmd.ExecuteReader()) tables = reader.ToList<TableSchema>().ToArray(); foreach (var t in tables) { cmd.CommandText = string.Format("select * from main.[{0}]", t.TableName); using (var reader = cmd.ExecuteReader(System.Data.CommandBehavior.SchemaOnly)) allColumns.Add(t.TableName, GetSchemaTableMethod(reader, true, true) as DataTable); cmd.CommandText = string.Format("PRAGMA main.foreign_key_list([{0}])", t.TableName); using (var reader = cmd.ExecuteReader()) { var fks = new List<ForeignKeyInfo>(); allFks.Add(t.TableName, fks); while (reader.Read()) fks.Add(new ForeignKeyInfo { ThisTableName = t.TableName, ThisKey = reader.GetString(3), OtherTableName = reader.GetString(2), OtherKey = reader.GetString(4), }); } } } } return tables; }
public abstract void CreateDatabase(DbConfiguration dbConfiguration, DatabaseScriptEntry script);
public abstract void DeleteDatabase(DbConfiguration dbConfiguration);
public abstract bool DatabaseExists(DbConfiguration dbConfiguration);
/// <summary> /// Registers the provider services replacer. /// </summary> private static void RegisterProviderServicesReplacer(DbConfiguration config, IDbCachingPolicy policy, DbCache efCache, DbTransactionInterceptor txHandler) { EventHandler<DbConfigurationLoadedEventArgs> onLoaded = null; onLoaded = (sender, args) => { // Replace provider services for specific instance only and unsubscribe. if (ReferenceEquals(config, sender)) { // SetProviderServices is not suitable. We should replace whatever provider there is with our proxy. args.ReplaceService<DbProviderServices>( (services, a) => new DbProviderServicesProxy(services, policy, efCache, txHandler)); Loaded -= onLoaded; } }; Loaded += onLoaded; }
protected abstract void OnCreateDatabase(DbConfiguration dbConfiguration, string dbName);
public void SwitchInRootResolver_swicthes_in_given_root_resolver() { var configuration = new DbConfiguration().InternalConfiguration; var mockRootResolver = new Mock<RootDependencyResolver>(); configuration.SwitchInRootResolver(mockRootResolver.Object); Assert.Same(mockRootResolver.Object, configuration.RootResolver); configuration.DependencyResolver.GetService<object>("Foo"); mockRootResolver.Verify(m => m.GetService(typeof(object), "Foo")); }
public override IDatabaseSchema Load(DbConfiguration cfg) { var databaseSchema = new DatabaseSchema(); Dictionary<string, List<ForeignKeyInfo>> allFks = new Dictionary<string, List<ForeignKeyInfo>>(); Dictionary<string, DataTable> allColumns = new Dictionary<string, DataTable>(); var tables = LoadData(cfg, allFks, allColumns); foreach (var tb in tables) { foreach (var row in allColumns[tb.TableName].Rows.Cast<DataRow>()) { var typeName = row["DataTypeName"] as string; if (string.IsNullOrEmpty(typeName)) continue; var type = row["DataType"] as Type; var dbType = ParseDbType(typeName); int precision, scale; if (string.IsNullOrEmpty(row["NumericPrecision"] as string)) precision = 0; else precision = (int)row["NumericPrecision"]; if (string.IsNullOrEmpty(row["NumericScale"] as string)) scale = 0; else scale = (int)row["NumericScale"]; var c = new ColumnSchema { ColumnName = row["ColumnName"] as string, IsPrimaryKey = (bool)row["IsKey"], IsGenerated = (bool)row["IsAutoIncrement"], Table = tb, IsUniqule = (bool)row["IsUnique"], //Comment = row["DESCRIPTION"] as string, DefaultValue = row["DefaultValue"] as string, Order = (int)row["ColumnOrdinal"], Precision = precision, Scale = scale, IsNullable = (bool)row["AllowDBNull"], DbType = dbType, Type = type, }; tb.AddColumn(c); } } foreach (var tbName in allFks.Keys) { var items = allFks[tbName]; var tb = tables.FirstOrDefault(p => p.TableName == tbName); foreach (var item in items) { var otherTable = tables.FirstOrDefault(p => p.TableName == item.OtherTableName); tb.AddFK(new ForeignKeySchema { ThisTable = tb, ThisKey = tb.AllColumns.FirstOrDefault(p => p.ColumnName == item.ThisKey), OtherTable = otherTable, OtherKey = otherTable.AllColumns.FirstOrDefault(p => p.ColumnName == item.OtherKey), }); } } databaseSchema.Tables = tables.Where(p => !p.IsView).ToArray(); databaseSchema.Views = tables.Where(p => p.IsView).ToArray(); return databaseSchema; }
public void ResolverSnapshot_returns_copy_of_resolver_chain() { var configuration = new DbConfiguration().InternalConfiguration; var resolver1 = new Mock<IDbDependencyResolver>(); configuration.AddDependencyResolver(resolver1.Object); var snapshot = configuration.ResolverSnapshot; var resolver2 = new Mock<IDbDependencyResolver>(); configuration.AddDependencyResolver(resolver2.Object); snapshot.GetService<object>("Foo"); resolver1.Verify(m => m.GetService(typeof(object), "Foo"), Times.Once()); resolver2.Verify(m => m.GetService(typeof(object), "Foo"), Times.Never()); }
public override IDatabaseSchema Load(DbConfiguration cfg) { var databaseSchema = new DatabaseSchema(); DataTable allColumns = null; DataTable pkTable = null; DataTable fkTable = null; DataTable viewTable = null; using (var conn = new OleDbConnection(cfg.ConnectionString)) { conn.Open(); allColumns = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Columns, null); pkTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, null); fkTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Foreign_Keys, null); viewTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Views, null); } Dictionary<string, TableSchema> tables = new Dictionary<string, TableSchema>(); foreach (var item in allColumns.Rows.Cast<DataRow>()) { var tableName = item["TABLE_NAME"] as string; var tableSchema = item["TABLE_SCHEMA"] as string; var tableCatalog = item["TABLE_CATALOG"] as string; var c = new ColumnSchema(); c.ColumnName = item["COLUMN_NAME"] as string; c.Order = Convert.ToInt32(item["ORDINAL_POSITION"]); if (string.IsNullOrEmpty(item["NUMERIC_PRECISION"] as string)) c.Precision = 0; else c.Precision = (int)item["NUMERIC_PRECISION"]; if (string.IsNullOrEmpty(item["NUMERIC_SCALE"] as string)) c.Scale = 0; else c.Scale = (int)(item["NUMERIC_SCALE"]); if (string.IsNullOrEmpty(item["CHARACTER_MAXIMUM_LENGTH"] as string)) c.Length = 0; else c.Length = (int)item["CHARACTER_MAXIMUM_LENGTH"]; c.DefaultValue = item["COLUMN_DEFAULT"] as string; c.Comment = item["DESCRIPTION"] as string; c.DbType = ParseDbType((int)item["DATA_TYPE"]); c.Type = ParseType(c.DbType); foreach (var p in pkTable.Rows.Cast<DataRow>()) { if (tableName == p["TABLE_NAME"] as string && c.ColumnName == p["COLUMN_NAME"] as string) { c.IsPrimaryKey = true; break; } } if (!item.IsNull("IS_NULLABLE")) c.IsNullable = (bool)item["IS_NULLABLE"]; TableSchema table = null; string key = string.Concat(tableCatalog, tableSchema, tableName); if (!tables.TryGetValue(key, out table)) { table = new TableSchema { TableName = tableName, Schema = tableSchema }; tables[tableName] = table; } table.AddColumn(c); } foreach (var item in fkTable.Rows.Cast<DataRow>()) { var tableSchema = item["PK_TABLE_SCHEMA"] as string; var tableCatalog = item["PK_TABLE_CATALOG"] as string; TableSchema thisTable = null; TableSchema otherTable = null; IColumnSchema thisKey = null; IColumnSchema otherKey = null; var key = string.Concat(tableCatalog, tableSchema, item["FK_TABLE_NAME"] as string); if (tables.TryGetValue(key, out thisTable)) thisKey = thisTable.AllColumns.FirstOrDefault(p => p.ColumnName == item["FK_COLUMN_NAME"] as string); key = string.Concat(tableCatalog, tableSchema, item["PK_TABLE_NAME"] as string); if (tables.TryGetValue(key, out otherTable)) otherKey = otherTable.AllColumns.FirstOrDefault(p => p.ColumnName == item["PK_COLUMN_NAME"] as string); thisTable.AddFK(new ForeignKeySchema { ThisTable = thisTable, Name = item["FK_NAME"] as string, ThisKey = thisKey, OtherTable = otherTable, OtherKey = otherKey }); } foreach (var item in viewTable.Rows.Cast<DataRow>()) { var tableName = item["TABLE_NAME"] as string; var tableSchema = item["TABLE_SCHEMA"] as string; var tableCatalog = item["TABLE_CATALOG"] as string; TableSchema table = null; var key = string.Concat(tableCatalog, tableSchema, tableName); if (tables.TryGetValue(key, out table)) table.IsView = true; } databaseSchema.Tables = tables.Values.Where(p => !p.IsView).ToArray(); databaseSchema.Views = tables.Values.Where(p => p.IsView).ToArray(); //allColumns.WriteXmlSchema(Console.Out); //pkTable.WriteXmlSchema(Console.Out); //fkTable.WriteXmlSchema(Console.Out); //viewTable.WriteXmlSchema(Console.Out); return databaseSchema; }
public override bool DatabaseExists(DbConfiguration dbConfiguration) { var dbName = dbConfiguration.DatabaseName; return File.Exists(dbName); }
/// <summary> /// Initializes Ignite caching for specified <see cref="DbConfiguration"/>. /// This method should be used when it is not possible to use or inherit <see cref="IgniteDbConfiguration"/>. /// </summary> /// <param name="dbConfiguration"><see cref="DbConfiguration"/> instance to be initialized /// for Ignite caching.</param> /// <param name="ignite">The ignite instance to use.</param> /// <param name="metaCacheConfiguration"> /// Configuration of the metadata cache which holds entity set information. Null for default configuration. /// <para /> /// This cache holds small amount of data, but should not lose entries. At least one backup recommended. /// </param> /// <param name="dataCacheConfiguration"> /// Configuration of the data cache which holds query results. Null for default configuration. /// <para /> /// This cache tolerates lost data and can have no backups. /// </param> /// <param name="policy">The caching policy. Null for default <see cref="DbCachingPolicy" />.</param> public static void InitializeIgniteCaching(DbConfiguration dbConfiguration, IIgnite ignite, CacheConfiguration metaCacheConfiguration, CacheConfiguration dataCacheConfiguration, IDbCachingPolicy policy) { IgniteArgumentCheck.NotNull(ignite, "ignite"); IgniteArgumentCheck.NotNull(dbConfiguration, "configuration"); IgniteArgumentCheck.Ensure(!(dbConfiguration is IgniteDbConfiguration), "dbConfiguration", "IgniteDbConfiguration.InitializeIgniteCaching should not be called for IgniteDbConfiguration " + "instance. This method should be used only when IgniteDbConfiguration can't be inherited."); InitializeIgniteCachingInternal(dbConfiguration, ignite, metaCacheConfiguration, dataCacheConfiguration, policy); }
/// <summary> /// Initializes Ignite caching for specified <see cref="DbConfiguration"/>. /// This method should be used when it is not possible to use or inherit <see cref="IgniteDbConfiguration"/>. /// </summary> /// <param name="dbConfiguration"><see cref="DbConfiguration"/> instance to be initialized /// for Ignite caching.</param> /// <param name="ignite">The ignite instance to use.</param> /// <param name="metaCacheConfiguration"> /// Configuration of the metadata cache which holds entity set information. Null for default configuration. /// <para /> /// This cache holds small amount of data, but should not lose entries. At least one backup recommended. /// </param> /// <param name="dataCacheConfiguration"> /// Configuration of the data cache which holds query results. Null for default configuration. /// <para /> /// This cache tolerates lost data and can have no backups. /// </param> /// <param name="policy">The caching policy. Null for default <see cref="DbCachingPolicy" />.</param> private static void InitializeIgniteCachingInternal(DbConfiguration dbConfiguration, IIgnite ignite, CacheConfiguration metaCacheConfiguration, CacheConfiguration dataCacheConfiguration, IDbCachingPolicy policy) { Debug.Assert(ignite != null); Debug.Assert(dbConfiguration != null); metaCacheConfiguration = metaCacheConfiguration ?? GetDefaultMetaCacheConfiguration(); dataCacheConfiguration = dataCacheConfiguration ?? GetDefaultDataCacheConfiguration(); var efCache = new DbCache(ignite, metaCacheConfiguration, dataCacheConfiguration); var txHandler = new DbTransactionInterceptor(efCache); AddInterceptorDelegate(dbConfiguration, txHandler); RegisterProviderServicesReplacer(dbConfiguration, policy, efCache, txHandler); }
public void SwitchInRootResolver_leaves_other_resolvers_intact() { var configuration = new DbConfiguration().InternalConfiguration; var mockResolver = new Mock<IDbDependencyResolver>(); configuration.AddDependencyResolver(mockResolver.Object); configuration.SwitchInRootResolver(new Mock<RootDependencyResolver>().Object); configuration.DependencyResolver.GetService<object>("Foo"); mockResolver.Verify(m => m.GetService(typeof(object), "Foo")); }
public override void DeleteDatabase(DbConfiguration dbConfiguration) { var dbName = dbConfiguration.DatabaseName; File.Delete(dbName); }
public void ResolverSnapshot_returns_resolvers_in_correct_order() { var callOrder = ""; var configResolver = new Mock<IDbDependencyResolver>(); configResolver.Setup(m => m.GetService(typeof(object), "Foo")).Callback(() => callOrder += " Config"); var configChain = new ResolverChain(); configChain.Add(configResolver.Object); var rootResolver = new Mock<RootDependencyResolver>(); rootResolver.Setup(m => m.GetService(typeof(object), "Foo")).Callback(() => callOrder += " Root"); var configuration = new DbConfiguration( new InternalConfiguration( configChain, new ResolverChain(), rootResolver.Object, new Mock<AppConfigDependencyResolver>().Object)).InternalConfiguration; var normalResolver = new Mock<IDbDependencyResolver>(); normalResolver.Setup(m => m.GetService(typeof(object), "Foo")).Callback(() => callOrder += " Normal"); configuration.AddDependencyResolver(normalResolver.Object); var overrideResolver = new Mock<IDbDependencyResolver>(); overrideResolver.Setup(m => m.GetService(typeof(object), "Foo")).Callback(() => callOrder += " Override"); configuration.AddDependencyResolver(overrideResolver.Object, overrideConfigFile: true); configuration.ResolverSnapshot.GetService<object>("Foo"); Assert.Equal(" Override Config Normal Root", callOrder); }
protected override Configuration CreateConfigObject() { DbConfiguration dc = new DbConfiguration(SystemName); dc.Initialize(_db); return dc; }