public static AutoPersistenceModel Generate() { AutoPersistenceModel automap = new AutoPersistenceModel(new AutoMappingConfig()); automap.Conventions.AddFromAssemblyOf <Entity>();//.IncludeBase<Dictionary>();; automap.UseOverridesFromAssemblyOf <Entity>(); automap.AddEntityAssembly(Assembly.GetAssembly(typeof(Entity))); automap.AddMappingsFromAssembly(Assembly.GetAssembly(typeof(Entity))); return(automap); }
public AutoPersistenceModel BuildPersistenceModel() { var persistenceModel = new AutoPersistenceModel(); persistenceModel.Conventions.Setup(c => { c.Add(typeof(ForeignKeyNameConvention)); c.Add(typeof(ReferenceConvention)); c.Add(typeof(PrimaryKeyNameConvention)); c.Add(typeof(TableNameConvention)); }); persistenceModel.AddMappingsFromAssembly(AssemblyMapper); persistenceModel.WriteMappingsTo(@"./"); return(persistenceModel); }
public AutoPersistenceModel BuildPersistenceModel() { var persistenceModel = new AutoPersistenceModel(); persistenceModel.Conventions.Setup(c => { c.Add(typeof(ForeignKeyNameConvention)); c.Add(typeof(ReferenceConvention)); c.Add(typeof(PrimaryKeyNameConvention)); c.Add(typeof(TableNameConvention)); }); persistenceModel.AddMappingsFromAssembly(AssemblyMapper); persistenceModel.WriteMappingsTo(@"./"); return persistenceModel; }
public static IEnumerable <string> GetHBMFilesForFluentFromCSProj(CSProjFile csproj, string outputPath) { string assemblyName = csproj.GetAssemblyName(); IEnumerable <string> outputPaths = csproj.GetOutputPaths(); DateTime latestAssemblyDate = new DateTime(1900, 1, 1); string latestAssembly = ""; foreach (string folder in outputPaths) { string assemblyPath = Path.Combine(folder, assemblyName); if (File.Exists(assemblyPath)) { DateTime lastWriteTime = File.GetLastWriteTimeUtc(assemblyPath); if (lastWriteTime > latestAssemblyDate) { latestAssemblyDate = lastWriteTime; latestAssembly = assemblyPath; } } } if (string.IsNullOrEmpty(latestAssembly)) { throw new FluentNHibernateCompiledAssemblyMissingException("No compiled assembly found. A compiled assembly is required for Fluent NHibernate. Please recompile your project."); } System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(latestAssembly); FluentCompileLatestAssemblyDir = Path.GetDirectoryName(latestAssembly); try { assembly.ModuleResolve += new System.Reflection.ModuleResolveEventHandler(assembly_ModuleResolve); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve); if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } //var sessionFactory = FluentNHibernate.Cfg.Fluently.Configure() // .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008 // .ConnectionString("Data Source=STN_DEV;Initial Catalog=FNHProviderDB;Integrated Security=SSPI;") // ) // .Mappings(m => m.FluentMappings.AddFromAssembly(assembly).ExportTo(outputPath)) // .BuildConfiguration(); AutoPersistenceModel mappings = new AutoPersistenceModel(); mappings.AddMappingsFromAssembly(assembly); mappings.BuildMappings(); mappings.WriteMappingsTo(outputPath); return(Directory.GetFiles(outputPath).ToList()); } finally { assembly.ModuleResolve -= assembly_ModuleResolve; AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve; AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CurrentDomain_ReflectionOnlyAssemblyResolve; } }
private static AutoPersistenceModel AddMappingAssembliesTo(string instCode, Configuration cfg) { var hc = System.Configuration.ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName) as HibernateConfiguration; if (hc == null) { throw new HibernateConfigException("Cannot process NHibernate Section in config file."); } var mappingAssemblies = new HashSet <string>(); mappingAssemblies.Add(ThisAssembly); // Add yourself // Check for automap overrides, ClassMap<> or .hbm type mapping files if (hc.SessionFactory != null) { foreach (var file in hc.SessionFactory.Mappings.Select(x => x.Assembly)) { mappingAssemblies.Add(file); } } //Doing this ensures that any other specified libraries are captured if (MappingAssemblies.Any()) { foreach (var file in MappingAssemblies) { mappingAssemblies.Add(file); } } var mappingAssembliesLoaded = new List <Assembly>(mappingAssemblies.Count); foreach (var mappingAssemblyCfg in mappingAssemblies) { var assembly = Assembly.Load(mappingAssemblyCfg); mappingAssembliesLoaded.Add(assembly); } var autoMapConfig = new AutomappingConfiguration(); //autoMapConfig.ScanForPotentialClassMaps(mappingAssembliesLoaded); AutoPersistenceModel autoPersistenceModel = new AutoPersistenceModel(autoMapConfig); foreach (var assembly in mappingAssembliesLoaded) { // Looks for any HBMs cfg.AddAssembly(assembly); // Looks for fluent mappings autoPersistenceModel.AddMappingsFromAssembly(assembly); // Looks for auto-mapping overrides autoPersistenceModel.UseOverridesFromAssembly(assembly); } #region Auto-mapping // Check entity assemblies for possible automapping in case the mapping file is not written // Hey, don't forget this assembly and the 'Core' - check them too // 'Core' first var entityAssembly = typeof(Entity).Assembly; autoPersistenceModel.AddEntityAssembly(entityAssembly); // The rest var entityAssemblyName = entityAssembly.GetName().Name; foreach (var assemblyName in EntityAssemblies) { if (assemblyName.Equals(entityAssemblyName, StringComparison.OrdinalIgnoreCase)) { continue; } // Looks for automap var assembly = Assembly.Load(assemblyName); autoPersistenceModel.AddEntityAssembly(assembly); } // The below code does not work because we (may) have user-defined configurations //bool notCoreInst = !instCode.Equals(Utilities.INST_DEFAULT_CODE, StringComparison.OrdinalIgnoreCase); //if (notCoreInst) // => Tenant, so do not map those entities marked as Hosted Centrally //{ // autoPersistenceModel.Where(x => !typeof(IAmHostedCentrally).IsAssignableFrom(x)); //} #endregion cfg.BeforeBindMapping += (sender, args) => args.Mapping.autoimport = false; return(autoPersistenceModel); }
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 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); } } })); }
public static IEnumerable<string> GetHBMFilesForFluentFromCSProj(CSProjFile csproj, string outputPath) { string assemblyName = csproj.GetAssemblyName(); IEnumerable<string> outputPaths = csproj.GetOutputPaths(); DateTime latestAssemblyDate = new DateTime(1900, 1, 1); string latestAssembly = ""; foreach (string folder in outputPaths) { string assemblyPath = Path.Combine(folder, assemblyName); if (File.Exists(assemblyPath)) { DateTime lastWriteTime = File.GetLastWriteTimeUtc(assemblyPath); if (lastWriteTime > latestAssemblyDate) { latestAssemblyDate = lastWriteTime; latestAssembly = assemblyPath; } } } if (string.IsNullOrEmpty(latestAssembly)) throw new FluentNHibernateCompiledAssemblyMissingException("No compiled assembly found. A compiled assembly is required for Fluent NHibernate. Please recompile your project."); System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(latestAssembly); FluentCompileLatestAssemblyDir = Path.GetDirectoryName(latestAssembly); try { assembly.ModuleResolve += new System.Reflection.ModuleResolveEventHandler(assembly_ModuleResolve); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve); if (!Directory.Exists(outputPath)) Directory.CreateDirectory(outputPath); //var sessionFactory = FluentNHibernate.Cfg.Fluently.Configure() // .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008 // .ConnectionString("Data Source=STN_DEV;Initial Catalog=FNHProviderDB;Integrated Security=SSPI;") // ) // .Mappings(m => m.FluentMappings.AddFromAssembly(assembly).ExportTo(outputPath)) // .BuildConfiguration(); AutoPersistenceModel mappings = new AutoPersistenceModel(); mappings.AddMappingsFromAssembly(assembly); mappings.BuildMappings(); mappings.WriteMappingsTo(outputPath); return Directory.GetFiles(outputPath).ToList(); } finally { assembly.ModuleResolve -= assembly_ModuleResolve; AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve; AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= CurrentDomain_ReflectionOnlyAssemblyResolve; } }