public NhibernateTestSetupHelper(string dataSource, SupportedNHDrivers supportedNhDrivers, string sessionContext, bool executeSchema, FakeFrameworkContext frameworkContext = null, bool useNhProf = false, bool outputMappings = false, bool leaveSessionOpenOnRepositoryDispose = true, bool useSingleSessionForTest = true) { _useNhProfiler = useNhProf; var builder = new NHibernateConfigBuilder(dataSource, "unit-tester", supportedNhDrivers, sessionContext, outputMappings, _useNhProfiler); NhConfigurationCacheKey cacheKey; Config = builder.BuildConfiguration(false, out cacheKey, "on_close"); SessionFactory = SessionFactoryCache.GetOrAdd(cacheKey, key => Config.BuildSessionFactory()); SessionForTest = SessionFactory.OpenSession(); var schemaWriter = new StringWriter(new StringBuilder()); if (executeSchema) { new SchemaExport(Config).Execute(false, true, false, SessionForTest.Connection, schemaWriter); } FakeFrameworkContext = frameworkContext ?? new FakeFrameworkContext(); //var dataContextFactory = new DataContextFactory(fakeFrameworkContext, SessionForTest, true); //var readWriteRepositoryUnitOfWorkFactory = new ReadWriteUnitOfWorkFactory(); //var writer = new HiveReadWriteProvider(new HiveProviderSetup(fakeFrameworkContext, "r-unit-tester", new FakeHiveProviderBootstrapper(), null, readWriteRepositoryUnitOfWorkFactory, dataContextFactory)); var providerMetadata = new ProviderMetadata("r-unit-tester", new Uri("tester://"), true, false); //var schemaRepositoryFactory = new NullProviderSchemaRepositoryFactory(providerMetadata, fakeFrameworkContext); //var revisionRepositoryFactory = new NullProviderRevisionRepositoryFactory<TypedEntity>(providerMetadata, fakeFrameworkContext); var revisionSchemaSessionFactory = new NullProviderRevisionRepositoryFactory <EntitySchema>(providerMetadata, FakeFrameworkContext); ProviderDependencyHelper helper = null; if (!useSingleSessionForTest) { helper = new DependencyHelper(new NhFactoryHelper(Config, null, leaveSessionOpenOnRepositoryDispose, false, FakeFrameworkContext), providerMetadata); } else { helper = new DependencyHelper(new NhFactoryHelper(null, SessionForTest, leaveSessionOpenOnRepositoryDispose, false, FakeFrameworkContext), providerMetadata); } var revisionRepositoryFactory = new RevisionRepositoryFactory(providerMetadata, FakeFrameworkContext, helper); var schemaRepositoryFactory = new SchemaRepositoryFactory(providerMetadata, revisionSchemaSessionFactory, FakeFrameworkContext, helper); var entityRepositoryFactory = new EntityRepositoryFactory(providerMetadata, revisionRepositoryFactory, schemaRepositoryFactory, FakeFrameworkContext, helper); var readUnitFactory = new ReadonlyProviderUnitFactory(entityRepositoryFactory); var unitFactory = new ProviderUnitFactory(entityRepositoryFactory); ProviderSetup = new ProviderSetup(unitFactory, providerMetadata, FakeFrameworkContext, null, 0); ReadonlyProviderSetup = new ReadonlyProviderSetup(readUnitFactory, providerMetadata, FakeFrameworkContext, null, 0); Func <AbstractMappingEngine> addTypemapper = () => new ManualMapperv2(new NhLookupHelper(entityRepositoryFactory), providerMetadata); FakeFrameworkContext.TypeMappers.Add(new Lazy <AbstractMappingEngine, TypeMapperMetadata>(addTypemapper, new TypeMapperMetadata(true))); }
public NHibernateConfigBuilder(string connectionString, string @alias, SupportedNHDrivers nhDriver, string sessionContext, bool outputNhMappings, bool useNhProfiler) { _sessionContext = sessionContext; _outputNhMappings = outputNhMappings; ConnectionString = connectionString; _alias = alias; _nhDriver = nhDriver; _useNhProfiler = useNhProfiler; }
public NhConfigurationCacheKey(SupportedNHDrivers driver, string connectionString, Assembly fluentMappingsAssembly, bool showSql, bool enablePostCommitListener, string sessionContextType, bool outputMappings) { Driver = driver; ConnectionString = connectionString; FluentMappingsAssembly = fluentMappingsAssembly; ShowSql = showSql; EnablePostCommitListener = enablePostCommitListener; SessionContextType = sessionContextType; OutputMappings = outputMappings; _toString = null; }
public static void AddConventions <T>(SupportedNHDrivers nhDriver, SetupConventionFinder <T> conventions) { switch (nhDriver) { case SupportedNHDrivers.SqlLite: case SupportedNHDrivers.MsSqlCe4: case SupportedNHDrivers.MySql: conventions.Add(new NormalizedDateTimeUserTypeConvention(), new NormalizedNullableDateTimeUserTypeConvention()); break; } }
public NhibernateTestSetupHelper(string dataSource, SupportedNHDrivers supportedNhDrivers, string sessionContext, bool executeSchema, FakeFrameworkContext frameworkContext = null, bool useNhProf = false, bool outputMappings = false, bool leaveSessionOpenOnRepositoryDispose = true, bool useSingleSessionForTest = true) { _useNhProfiler = useNhProf; var builder = new NHibernateConfigBuilder(dataSource, "unit-tester", supportedNhDrivers, sessionContext, outputMappings, _useNhProfiler); NhConfigurationCacheKey cacheKey; Config = builder.BuildConfiguration(false, out cacheKey, "on_close"); SessionFactory = SessionFactoryCache.GetOrAdd(cacheKey, key => Config.BuildSessionFactory()); SessionForTest = SessionFactory.OpenSession(); var schemaWriter = new StringWriter(new StringBuilder()); if (executeSchema) new SchemaExport(Config).Execute(false, true, false, SessionForTest.Connection, schemaWriter); FakeFrameworkContext = frameworkContext ?? new FakeFrameworkContext(); //var dataContextFactory = new DataContextFactory(fakeFrameworkContext, SessionForTest, true); //var readWriteRepositoryUnitOfWorkFactory = new ReadWriteUnitOfWorkFactory(); //var writer = new HiveReadWriteProvider(new HiveProviderSetup(fakeFrameworkContext, "r-unit-tester", new FakeHiveProviderBootstrapper(), null, readWriteRepositoryUnitOfWorkFactory, dataContextFactory)); var providerMetadata = new ProviderMetadata("r-unit-tester", new Uri("tester://"), true, false); //var schemaRepositoryFactory = new NullProviderSchemaRepositoryFactory(providerMetadata, fakeFrameworkContext); //var revisionRepositoryFactory = new NullProviderRevisionRepositoryFactory<TypedEntity>(providerMetadata, fakeFrameworkContext); var revisionSchemaSessionFactory = new NullProviderRevisionRepositoryFactory<EntitySchema>(providerMetadata, FakeFrameworkContext); ProviderDependencyHelper helper = null; if (!useSingleSessionForTest) { helper = new DependencyHelper(new NhFactoryHelper(Config, null, leaveSessionOpenOnRepositoryDispose, false, FakeFrameworkContext), providerMetadata); } else { helper = new DependencyHelper(new NhFactoryHelper(null, SessionForTest, leaveSessionOpenOnRepositoryDispose, false, FakeFrameworkContext), providerMetadata); } var revisionRepositoryFactory = new RevisionRepositoryFactory(providerMetadata, FakeFrameworkContext, helper); var schemaRepositoryFactory = new SchemaRepositoryFactory(providerMetadata, revisionSchemaSessionFactory, FakeFrameworkContext, helper); var entityRepositoryFactory = new EntityRepositoryFactory(providerMetadata, revisionRepositoryFactory, schemaRepositoryFactory, FakeFrameworkContext, helper); var readUnitFactory = new ReadonlyProviderUnitFactory(entityRepositoryFactory); var unitFactory = new ProviderUnitFactory(entityRepositoryFactory); ProviderSetup = new ProviderSetup(unitFactory, providerMetadata, FakeFrameworkContext, null, 0); ReadonlyProviderSetup = new ReadonlyProviderSetup(readUnitFactory, providerMetadata, FakeFrameworkContext, null, 0); Func<AbstractMappingEngine> addTypemapper = () => new ManualMapperv2(new NhLookupHelper(entityRepositoryFactory), providerMetadata); FakeFrameworkContext.TypeMappers.Add(new Lazy<AbstractMappingEngine, TypeMapperMetadata>(addTypemapper, new TypeMapperMetadata(true))); }
public static global::NHibernate.Cfg.Configuration CreateConfiguration(SupportedNHDrivers nhDriver, string connectionString, Assembly fluentMappingsAssembly, bool showSql, bool enablePostCommitListener, string sessionContext, bool outputNhMappings, bool useNhProfiler, out NhConfigurationCacheKey configurationCacheKey) { Mandate.ParameterNotNullOrEmpty(connectionString, "connectionString"); Mandate.ParameterNotNull(fluentMappingsAssembly, "fluentMappingsAssembly"); Mandate.ParameterCondition(nhDriver != SupportedNHDrivers.Unknown, "nhDriver"); configurationCacheKey = new NhConfigurationCacheKey( nhDriver, connectionString, fluentMappingsAssembly, showSql, enablePostCommitListener, sessionContext, outputNhMappings); return(ConfigurationCache.GetOrAdd( configurationCacheKey, y => { using (new WriteLockDisposable(MappingLocker)) { if (useNhProfiler) { try { NHibernateProfiler.Initialize(); NhProfilerLogging.Enabled = true; } catch (InvalidOperationException ex) { //swallow security exceptions, happens if running in Medium trust if (!(ex.InnerException is SecurityException)) { throw ex; } } } // Figure out the FluentNH persistence configurer based on the desired driver var persistenceConfigurer = GetPersistenceConfigurer(nhDriver, connectionString); // Configure NH using FluentNH var fluentConfig = Fluently.Configure().Database(persistenceConfigurer) //.Cache(x => // x.UseMinimalPuts() // .UseQueryCache() // .UseSecondLevelCache() // .ProviderClass(typeof(global::NHibernate.Caches.SysCache2.SysCacheProvider).AssemblyQualifiedName)) .ExposeConfiguration(c => c.SetProperty(Environment.ReleaseConnections, "on_close")) // after_transaction does not work for unit tests with Sqlite .ExposeConfiguration( c => c.SetProperty(Environment.CurrentSessionContextClass, sessionContext)). ExposeConfiguration(c => c.SetProperty(Environment.GenerateStatistics, useNhProfiler.ToString().ToLower())). ExposeConfiguration(c => c.SetProperty(Environment.BatchSize, "20")).ExposeConfiguration ( c => c.SetProperty( Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName)).Mappings( x => { var container = x.FluentMappings.AddFromAssembly(fluentMappingsAssembly); AddConventions(nhDriver, container.Conventions); }); if (showSql) { fluentConfig.ExposeConfiguration(c => c.SetProperty(Environment.ShowSql, "true")); } try { // Generate the NHibernate configuration object from FluentNH var nhConfig = fluentConfig.BuildConfiguration(); // Add a PostCommitInsert listener which is responsible for passing generated IDs back to the // mapped entities for entity insert scenarios (since the NH mapped objects aren't passed outside // of this provider) if (enablePostCommitListener) { var entitySaveEventListener = new NhEventListeners(); nhConfig.SetListener(ListenerType.PostCommitInsert, entitySaveEventListener); nhConfig.SetListener(ListenerType.Delete, entitySaveEventListener); nhConfig.SetListener(ListenerType.Merge, entitySaveEventListener); nhConfig.SetListener(ListenerType.SaveUpdate, entitySaveEventListener); nhConfig.SetListener(ListenerType.Flush, entitySaveEventListener); nhConfig.SetListener(ListenerType.Evict, entitySaveEventListener); } // Add the FluentNH persistence model and configure NH to use it var fluentAutoModel = new AutoPersistenceModel(); fluentAutoModel.AddMappingsFromAssembly(fluentMappingsAssembly); fluentAutoModel.BuildMappings(); fluentAutoModel.Configure(nhConfig); if (outputNhMappings) { var codeBase = Assembly.GetExecutingAssembly().CodeBase; var uri = new Uri(codeBase); var path = uri.LocalPath; var binFolder = new DirectoryInfo(Path.GetDirectoryName(path)); string nhibernateOutputFolder; if (binFolder.Name == "Debug") { nhibernateOutputFolder = Path.Combine( binFolder.Parent.Parent.FullName, "App_Data", "Logs", "NHibernateConfig"); } else { //its just 'bin' nhibernateOutputFolder = Path.Combine( binFolder.Parent.FullName, "App_Data", "Logs", "NHibernateConfig"); } Directory.CreateDirectory(nhibernateOutputFolder); fluentAutoModel.WriteMappingsTo(nhibernateOutputFolder); } return nhConfig; } catch (Exception ex) { throw new InvalidOperationException("Cannot build NHibernate configuration", ex); } } })); }
public static IPersistenceConfigurer GetPersistenceConfigurer(SupportedNHDrivers nhDriver, string connString) { IPersistenceConfigurer persistenceConfigurer; switch (nhDriver) { default: case SupportedNHDrivers.MsSql2008: persistenceConfigurer = MsSqlConfiguration .MsSql2008 .ConnectionString(connString) .DefaultSchema("dbo") .FormatSql() .UseOuterJoin() .UseReflectionOptimizer() .Cache(x => x.UseMinimalPuts() .UseQueryCache() .ProviderClass( typeof(global::NHibernate.Caches.SysCache2.SysCacheProvider).AssemblyQualifiedName)); break; case SupportedNHDrivers.SqlLite: persistenceConfigurer = SQLiteConfiguration.Standard.ConnectionString(connString) .Cache(x => x.UseMinimalPuts() .UseQueryCache() .ProviderClass( typeof(global::NHibernate.Caches.SysCache2.SysCacheProvider).AssemblyQualifiedName)); break; case SupportedNHDrivers.MsSqlCe4: var directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase); var directoryPath = new Uri(directoryName).LocalPath; var connectionString = connString.Replace("{bin}", directoryPath); persistenceConfigurer = MsSqlCe4Configuration .Standard .ConnectionString(connectionString) .AdoNetBatchSize(20) .Cache(x => x.UseMinimalPuts() .UseQueryCache() .ProviderClass( typeof(global::NHibernate.Caches.SysCache2.SysCacheProvider).AssemblyQualifiedName)); break; case SupportedNHDrivers.MySql: persistenceConfigurer = MySQLConfiguration.Standard.ConnectionString(connString) .Cache(x => x.UseMinimalPuts() .UseQueryCache() .ProviderClass( typeof(global::NHibernate.Caches.SysCache2.SysCacheProvider).AssemblyQualifiedName)); break; case SupportedNHDrivers.Unknown: throw new InvalidOperationException( "Cannot get FluentNHibernate Persistence Configurer as the call to this method didn't specify a known driver"); } return(persistenceConfigurer); }
public NhibernateTestSetupHelper(FakeFrameworkContext frameworkContext = null, bool useNhProf = false, string dataSource = "data source=:memory:", SupportedNHDrivers supportedNhDrivers = SupportedNHDrivers.SqlLite) : this(dataSource, supportedNhDrivers, "call", true, frameworkContext, useNhProf: useNhProf) { }
public NhibernateTestSetupHelper(FakeFrameworkContext frameworkContext = null, bool useNhProf = false, string dataSource = "data source=:memory:", SupportedNHDrivers supportedNhDrivers = SupportedNHDrivers.SqlLite) : this(dataSource, supportedNhDrivers, "call", true, frameworkContext, useNhProf : useNhProf) { }
public static global::NHibernate.Cfg.Configuration CreateConfiguration(SupportedNHDrivers nhDriver, string connectionString, Assembly fluentMappingsAssembly, bool showSql, bool enablePostCommitListener, string sessionContext, bool outputNhMappings, bool useNhProfiler, out NhConfigurationCacheKey configurationCacheKey, string connReleaseMode) { Mandate.ParameterNotNullOrEmpty(connectionString, "connectionString"); Mandate.ParameterNotNull(fluentMappingsAssembly, "fluentMappingsAssembly"); Mandate.ParameterCondition(nhDriver != SupportedNHDrivers.Unknown, "nhDriver"); configurationCacheKey = new NhConfigurationCacheKey( nhDriver, connectionString, fluentMappingsAssembly, showSql, enablePostCommitListener, sessionContext, outputNhMappings); return(ConfigurationCache.GetOrAdd( configurationCacheKey, y => { using (new WriteLockDisposable(MappingLocker)) { if (useNhProfiler) { try { NHibernateProfiler.Initialize(); } catch (InvalidOperationException ex) { //swallow security exceptions, happens if running in Medium trust if (!(ex.InnerException is SecurityException)) { throw ex; } } } // Check if we already have a serialized Configuration object // for this assembly version and assembly last-write date using (new WriteLockDisposable(ConfigCacheLocker)) if (ConfigCacheFileExists(connectionString)) { var cachedConfig = DeserializeConfig(connectionString); if (cachedConfig != null) { return cachedConfig; } } // We haven't cached config before, or couldn't load it, so dynamically create it // Figure out the FluentNH persistence configurer based on the desired driver var persistenceConfigurer = GetPersistenceConfigurer(nhDriver, connectionString); // Figure out the connection release mode to use, because SqlCe needs "on_close" for perf reasons, // whereas we should use "auto" for everything else to avoid long-running connections var trueConnReleaseMode = connReleaseMode; // Could have been set already by a unit test if (connReleaseMode == NHibernateConfigBuilder.CustomConnReleaseMode) // Only modify if it's a value teling us to modify { if (nhDriver == SupportedNHDrivers.MsSqlCe4) { trueConnReleaseMode = "on_close"; } else { trueConnReleaseMode = "auto"; } } // Configure NH using FluentNH var fluentConfig = Fluently.Configure().Database(persistenceConfigurer) //.Cache(x => // x.UseMinimalPuts() // .UseQueryCache() // .UseSecondLevelCache() // .ProviderClass(typeof(global::NHibernate.Caches.SysCache2.SysCacheProvider).AssemblyQualifiedName)) // after_transaction does not work for unit tests with Sqlite .ExposeConfiguration(c => c.SetProperty(Environment.ReleaseConnections, trueConnReleaseMode) .SetProperty(Environment.CurrentSessionContextClass, sessionContext) .SetProperty(Environment.GenerateStatistics, useNhProfiler.ToString().ToLower()) .SetProperty(Environment.BatchSize, "20") .SetProperty(Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName)) .Mappings(x => { // Add named queries from our embedded mappings file x.HbmMappings.AddFromAssembly(fluentMappingsAssembly); // Add class mappings var container = x.FluentMappings.AddFromAssembly(fluentMappingsAssembly); AddConventions(nhDriver, container.Conventions); }); if (showSql) { fluentConfig.ExposeConfiguration(c => c.SetProperty(Environment.ShowSql, "true")); } try { // Generate the NHibernate configuration object from FluentNH var nhConfig = fluentConfig.BuildConfiguration(); // Add a PostCommitInsert listener which is responsible for passing generated IDs back to the // mapped entities for entity insert scenarios (since the NH mapped objects aren't passed outside // of this provider) if (enablePostCommitListener) { var entitySaveEventListener = new NhEventListeners(); nhConfig.SetListener(ListenerType.PostInsert, entitySaveEventListener); nhConfig.SetListener(ListenerType.PostUpdate, entitySaveEventListener); nhConfig.SetListener(ListenerType.PostCommitInsert, entitySaveEventListener); nhConfig.SetListener(ListenerType.PreDelete, entitySaveEventListener); nhConfig.SetListener(ListenerType.Delete, entitySaveEventListener); nhConfig.SetListener(ListenerType.Merge, entitySaveEventListener); nhConfig.SetListener(ListenerType.SaveUpdate, entitySaveEventListener); nhConfig.SetListener(ListenerType.Flush, entitySaveEventListener); nhConfig.SetListener(ListenerType.Evict, entitySaveEventListener); nhConfig.SetListener(ListenerType.PreDelete, entitySaveEventListener); } // Add the Aggregate interceptor for running trigger-like actions that NH can't handle // Disabled, done by event listener instead now: nhConfig.SetInterceptor(new AggregateDataInterceptor()); // Add the FluentNH persistence model and configure NH to use it var fluentAutoModel = new AutoPersistenceModel(); fluentAutoModel.AddMappingsFromAssembly(fluentMappingsAssembly); fluentAutoModel.BuildMappings(); fluentAutoModel.Configure(nhConfig); if (outputNhMappings) { var codeBase = Assembly.GetExecutingAssembly().CodeBase; var uri = new Uri(codeBase); var path = uri.LocalPath; var binFolder = new DirectoryInfo(Path.GetDirectoryName(path)); string nhibernateOutputFolder; if (binFolder.Name == "Debug") { nhibernateOutputFolder = Path.Combine( binFolder.Parent.Parent.FullName, "App_Data", "Logs", "NHibernateConfig"); } else { //its just 'bin' nhibernateOutputFolder = Path.Combine( binFolder.Parent.FullName, "App_Data", "Logs", "NHibernateConfig"); } Directory.CreateDirectory(nhibernateOutputFolder); fluentAutoModel.WriteMappingsTo(nhibernateOutputFolder); } SaveConfigurationToFile(nhConfig, connectionString); return nhConfig; } catch (Exception ex) { throw new InvalidOperationException("Cannot build NHibernate configuration", ex); } } })); }