/// <summary> /// The actual contribution method. /// </summary> /// <param name="configuration">The configuration to be modified.</param> public override void Contribute(Configuration configuration) { if (configuration.Properties.ContainsKey("hibernate.search.analyzer")) { configuration.SetListeners(ListenerType.PostDelete, AddListenerTo(typeof(IPostDeleteEventListener), configuration.EventListeners.PostDeleteEventListeners)); configuration.SetListeners(ListenerType.PostInsert, AddListenerTo(typeof(IPostInsertEventListener), configuration.EventListeners.PostInsertEventListeners)); configuration.SetListeners(ListenerType.PostUpdate, AddListenerTo(typeof(IPostUpdateEventListener), configuration.EventListeners.PostUpdateEventListeners)); } }
public static void AppendTo(Configuration configuration) { configuration.SetListeners( ListenerType.PreInsert, configuration.EventListeners.PreInsertEventListeners.Concat(new IPreInsertEventListener[] { new ValidateEventListener() }).ToArray()); configuration.SetListeners( ListenerType.PreUpdate, configuration.EventListeners.PreUpdateEventListeners.Concat(new IPreUpdateEventListener[] { new ValidateEventListener() }).ToArray()); }
public static Configuration CreateConfiguration() { // XML-Files Configuration config = new Configuration(); config.AddAssembly(Assembly.GetExecutingAssembly()); // Event-Listener config.SetListeners(ListenerType.PostInsert, new[] { new FullTextIndexEventListener() }); config.SetListeners(ListenerType.PostUpdate, new[] { new FullTextIndexEventListener() }); config.SetListeners(ListenerType.PostDelete, new[] { new FullTextIndexEventListener() }); config.SetListener(ListenerType.PostCollectionRecreate, new FullTextIndexCollectionEventListener()); config.SetListener(ListenerType.PostCollectionRemove, new FullTextIndexCollectionEventListener()); config.SetListener(ListenerType.PostCollectionUpdate, new FullTextIndexCollectionEventListener()); return config; }
public static void Initialize(Configuration cfg, ValidatorEngine ve) { //Apply To DDL if (ve.ApplyToDDL) { foreach (PersistentClass persistentClazz in cfg.ClassMappings) { ApplyValidatorToDDL(persistentClazz, ve); } } //Autoregister Listeners if (ve.AutoRegisterListeners) { cfg.SetListeners(ListenerType.PreInsert, cfg.EventListeners.PreInsertEventListeners.Concat(new[] {new ValidatePreInsertEventListener()}).ToArray()); cfg.SetListeners(ListenerType.PreUpdate, cfg.EventListeners.PreUpdateEventListeners.Concat(new[] { new ValidatePreUpdateEventListener() }).ToArray()); } }
/// <summary> /// Initialize the SessionFactory for the given or the /// default location. /// </summary> public virtual void AfterPropertiesSet() { // Create Configuration instance. Configuration config = NewConfiguration(); if (this.dbProvider != null) { config.SetProperty(Environment.ConnectionString, dbProvider.ConnectionString); config.SetProperty(Environment.ConnectionProvider, typeof(DbProviderWrapper).AssemblyQualifiedName); configTimeDbProvider = this.dbProvider; } if (ExposeTransactionAwareSessionFactory) { // Set ICurrentSessionContext implementation, // providing the Spring-managed ISession s current Session. // Can be overridden by a custom value for the corresponding Hibernate property // config.SetProperty(Environment.CurrentSessionContextClass, typeof(SpringSessionContext).AssemblyQualifiedName); config.SetProperty(Environment.CurrentSessionContextClass, typeof(WcfOperationSessionContext).AssemblyQualifiedName); } if (this.entityInterceptor != null) { // Set given entity interceptor at SessionFactory level. config.SetInterceptor(this.entityInterceptor); } if (this.namingStrategy != null) { // Pass given naming strategy to Hibernate Configuration. config.SetNamingStrategy(this.namingStrategy); } if (this.filterDefinitions != null) { // Register specified NHibernate FilterDefinitions. for (int i = 0; i < this.filterDefinitions.Length; i++) { config.AddFilterDefinition(this.filterDefinitions[i]); } } if (this.hibernateProperties != null) { if (config.GetProperty(Environment.ConnectionProvider) != null && hibernateProperties.Contains(Environment.ConnectionProvider)) { #region Logging if (log.IsInfoEnabled) { log.Info("Overriding use of Spring's Hibernate Connection Provider with [" + hibernateProperties[Environment.ConnectionProvider] + "]"); } #endregion config.Properties.Remove(Environment.ConnectionProvider); } Dictionary <string, string> genericHibernateProperties = new Dictionary <string, string>(); foreach (DictionaryEntry entry in hibernateProperties) { genericHibernateProperties.Add((string)entry.Key, (string)entry.Value); } config.AddProperties(genericHibernateProperties); } if (this.mappingAssemblies != null) { foreach (string assemblyName in mappingAssemblies) { config.AddAssembly(assemblyName); } } if (this.mappingResources != null) { IResourceLoader loader = this.ResourceLoader; if (loader == null) { loader = this.applicationContext; } foreach (string resourceName in mappingResources) { config.AddInputStream(loader.GetResource(resourceName).InputStream); } } if (configFilenames != null) { foreach (string configFilename in configFilenames) { config.Configure(configFilename); } } if (this.eventListeners != null) { // Register specified NHibernate event listeners. foreach (DictionaryEntry entry in eventListeners) { ListenerType listenerType; try { listenerType = (ListenerType)Enum.Parse(typeof(ListenerType), (string)entry.Key); } catch { throw new ArgumentException(string.Format("Unable to parse string '{0}' as valid {1}", entry.Key, typeof(ListenerType))); } object listenerObject = entry.Value; if (listenerObject is ICollection) { ICollection listeners = (ICollection)listenerObject; EventListeners listenerRegistry = config.EventListeners; // create the array and check that types are valid at the same time ArrayList items = new ArrayList(listeners); object[] listenerArray = (object[])items.ToArray(listenerRegistry.GetListenerClassFor(listenerType)); config.SetListeners(listenerType, listenerArray); } else { config.SetListener(listenerType, listenerObject); } } } // Perform custom post-processing in subclasses. PostProcessConfiguration(config); // Build SessionFactory instance. log.Info("Building new Hibernate SessionFactory"); this.configuration = config; this.sessionFactory = NewSessionFactory(config); AfterSessionFactoryCreation(); // set config time DB provider back to null configTimeDbProvider = null; }
public static void OverrideIn(Configuration configuration) { configuration.SetListeners( ListenerType.FlushEntity, new IFlushEntityEventListener[] { new AuditFlushEntityEventListener() }); }
public NHContextFactory(DbProvider provider, string connectionString, string cacheProvider, Assembly mappingsAssembly, IoCContainer container) { _DbProvider = provider; _connectionString = connectionString; FluentConfiguration cfg = null; switch (_DbProvider) { case DbProvider.MsSqlProvider: { cfg = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008 .Raw("format_sql", "true") .ConnectionString(_connectionString)) .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.SqlExceptionConverter, typeof(SqlExceptionHandler).AssemblyQualifiedName)) .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.DefaultSchema, "dbo")); break; } case DbProvider.SQLiteProvider: { cfg = Fluently.Configure().Database(SQLiteConfiguration.Standard .Raw("format_sql", "true") .ConnectionString(_connectionString)); _InMemoryDatabase = _connectionString.ToUpperInvariant().Contains(":MEMORY:"); break; } case DbProvider.SqlCe: { cfg = Fluently.Configure().Database(MsSqlCeConfiguration.Standard .Raw("format_sql", "true") .ConnectionString(_connectionString)) .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.SqlExceptionConverter, typeof(SqlExceptionHandler).AssemblyQualifiedName)); _validationSupported = false; break; } case DbProvider.Firebird: { cfg = Fluently.Configure().Database(new FirebirdConfiguration() .Raw("format_sql", "true") .ConnectionString(_connectionString)); break; } case DbProvider.PostgreSQLProvider: { cfg = Fluently.Configure().Database(PostgreSQLConfiguration.PostgreSQL82 .Raw("format_sql", "true") .ConnectionString(_connectionString)); _validationSupported = false; break; } } Guard.IsNotNull(cfg, string.Format("Db provider {0} is currently not supported.", _DbProvider.GetEnumMemberValue())); var pinfo = typeof(FluentConfiguration) .GetProperty("Configuration", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); var nhConfiguration = pinfo.GetValue(cfg, null); container.RegisterInstance<Configuration>(nhConfiguration); cfg.Mappings(m => m.FluentMappings.Conventions.AddAssembly(typeof(NHContextFactory).Assembly)) .Mappings(m => m.FluentMappings.Conventions.AddAssembly(mappingsAssembly)) .Mappings(m => m.FluentMappings.AddFromAssembly(mappingsAssembly)) .Mappings(m => m.HbmMappings.AddFromAssembly(typeof(NHContextFactory).Assembly)) .Mappings(m => m.HbmMappings.AddFromAssembly(mappingsAssembly)) .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.BatchSize, "100")) .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.UseProxyValidator, "true")); if (!string.IsNullOrEmpty(cacheProvider)) { cfg.ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.CacheProvider, cacheProvider)) //"NHibernate.Cache.HashtableCacheProvider" .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.UseSecondLevelCache, "true")) .ExposeConfiguration(c => c.Properties.Add(NHibernate.Cfg.Environment.UseQueryCache, "true")); } _builtConfiguration = cfg.BuildConfiguration(); _builtConfiguration.SetProperty(NHibernate.Cfg.Environment.ProxyFactoryFactoryClass, typeof(NHibernate.ByteCode.Castle.ProxyFactoryFactory).AssemblyQualifiedName); #region Add Listeners to NHibernate pipeline.... _builtConfiguration.SetListeners(ListenerType.FlushEntity, new IFlushEntityEventListener[] { new AuditFlushEntityEventListener() }); _builtConfiguration.SetListeners(ListenerType.PreInsert, _builtConfiguration.EventListeners.PreInsertEventListeners.Concat<IPreInsertEventListener>( new IPreInsertEventListener[] { new ValidateEventListener(), new AuditEventListener() }).ToArray()); _builtConfiguration.SetListeners(ListenerType.PreUpdate, _builtConfiguration.EventListeners.PreUpdateEventListeners.Concat<IPreUpdateEventListener>( new IPreUpdateEventListener[] { new ValidateEventListener(), new AuditEventListener() }).ToArray()); #endregion }
/// <summary> /// Initialize the SessionFactory for the given or the /// default location. /// </summary> public virtual void AfterPropertiesSet() { // Create Configuration instance. Configuration config = NewConfiguration(); if (this.dbProvider != null) { config.SetProperty(Environment.ConnectionString, dbProvider.ConnectionString); config.SetProperty(Environment.ConnectionProvider, typeof(DbProviderWrapper).AssemblyQualifiedName); configTimeDbProvider = this.dbProvider; } if (ExposeTransactionAwareSessionFactory) { // Set ICurrentSessionContext implementation, // providing the Spring-managed ISession s current Session. // Can be overridden by a custom value for the corresponding Hibernate property config.SetProperty(Environment.CurrentSessionContextClass, typeof(SpringSessionContext).AssemblyQualifiedName); } if (this.entityInterceptor != null) { // Set given entity interceptor at SessionFactory level. config.SetInterceptor(this.entityInterceptor); } if (this.namingStrategy != null) { // Pass given naming strategy to Hibernate Configuration. config.SetNamingStrategy(this.namingStrategy); } #if NH_2_1 if (this.typeDefinitions != null) { // Register specified Hibernate type definitions. IDictionary <string, string> typedProperties = new Dictionary <string, string>(); foreach (DictionaryEntry entry in hibernateProperties) { typedProperties.Add((string)entry.Key, (string)entry.Value); } Dialect dialect = Dialect.GetDialect(typedProperties); Mappings mappings = config.CreateMappings(dialect); for (int i = 0; i < this.typeDefinitions.Length; i++) { IObjectDefinition typeDef = this.typeDefinitions[i]; Dictionary <string, string> typedParamMap = new Dictionary <string, string>(); foreach (DictionaryEntry entry in typeDef.PropertyValues) { typedParamMap.Add((string)entry.Key, (string)entry.Value); } mappings.AddTypeDef(typeDef.ObjectTypeName, typeDef.ObjectTypeName, typedParamMap); } } #endif if (this.filterDefinitions != null) { // Register specified NHibernate FilterDefinitions. for (int i = 0; i < this.filterDefinitions.Length; i++) { config.AddFilterDefinition(this.filterDefinitions[i]); } } #if NH_2_1 // check whether proxy factory has been initialized if (config.GetProperty(Environment.ProxyFactoryFactoryClass) == null && (hibernateProperties == null || !hibernateProperties.Contains(Environment.ProxyFactoryFactoryClass))) { // nothing set by user, lets use Spring.NET's proxy factory factory #region Logging if (log.IsInfoEnabled) { log.Info("Setting proxy factory to Spring provided one as user did not specify any"); } #endregion config.Properties.Add( Environment.ProxyFactoryFactoryClass, typeof(Bytecode.ProxyFactoryFactory).AssemblyQualifiedName); } #endif if (this.hibernateProperties != null) { if (config.GetProperty(Environment.ConnectionProvider) != null && hibernateProperties.Contains(Environment.ConnectionProvider)) { #region Logging if (log.IsInfoEnabled) { log.Info("Overriding use of Spring's Hibernate Connection Provider with [" + hibernateProperties[Environment.ConnectionProvider] + "]"); } #endregion config.Properties.Remove(Environment.ConnectionProvider); } Dictionary <string, string> genericHibernateProperties = new Dictionary <string, string>(); foreach (DictionaryEntry entry in hibernateProperties) { genericHibernateProperties.Add((string)entry.Key, (string)entry.Value); } config.AddProperties(genericHibernateProperties); } if (this.mappingAssemblies != null) { foreach (string assemblyName in mappingAssemblies) { config.AddAssembly(assemblyName); } } if (this.mappingResources != null) { IResourceLoader loader = this.ResourceLoader; if (loader == null) { loader = this.applicationContext; } foreach (string resourceName in mappingResources) { config.AddInputStream(loader.GetResource(resourceName).InputStream); } } if (configFilenames != null) { foreach (string configFilename in configFilenames) { config.Configure(configFilename); } } #if NH_2_1 // Tell Hibernate to eagerly compile the mappings that we registered, // for availability of the mapping information in further processing. PostProcessMappings(config); config.BuildMappings(); if (this.entityCacheStrategies != null) { // Register cache strategies for mapped entities. foreach (string className in this.entityCacheStrategies.Keys) { String[] strategyAndRegion = StringUtils.CommaDelimitedListToStringArray(this.entityCacheStrategies.GetProperty(className)); if (strategyAndRegion.Length > 1) { config.SetCacheConcurrencyStrategy(className, strategyAndRegion[0], strategyAndRegion[1]); } else if (strategyAndRegion.Length > 0) { config.SetCacheConcurrencyStrategy(className, strategyAndRegion[0]); } } } if (this.collectionCacheStrategies != null) { // Register cache strategies for mapped collections. foreach (string collRole in collectionCacheStrategies.Keys) { string[] strategyAndRegion = StringUtils.CommaDelimitedListToStringArray(this.collectionCacheStrategies.GetProperty(collRole)); if (strategyAndRegion.Length > 1) { throw new Exception("Collection cache concurrency strategy region definition not supported yet"); //config.SetCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0], strategyAndRegion[1]); } else if (strategyAndRegion.Length > 0) { config.SetCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]); } } } #endif if (this.eventListeners != null) { // Register specified NHibernate event listeners. foreach (DictionaryEntry entry in eventListeners) { ListenerType listenerType; try { listenerType = (ListenerType)Enum.Parse(typeof(ListenerType), (string)entry.Key); } catch { throw new ArgumentException(string.Format("Unable to parse string '{0}' as valid {1}", entry.Key, typeof(ListenerType))); } object listenerObject = entry.Value; if (listenerObject is ICollection) { ICollection listeners = (ICollection)listenerObject; EventListeners listenerRegistry = config.EventListeners; // create the array and check that types are valid at the same time ArrayList items = new ArrayList(listeners); object[] listenerArray = (object[])items.ToArray(listenerRegistry.GetListenerClassFor(listenerType)); config.SetListeners(listenerType, listenerArray); } else { config.SetListener(listenerType, listenerObject); } } } // Perform custom post-processing in subclasses. PostProcessConfiguration(config); #if NH_2_1 if (BytecodeProvider != null) { // set custom IBytecodeProvider Environment.BytecodeProvider = BytecodeProvider; } else { // use Spring's as default // Environment.BytecodeProvider = new Bytecode.BytecodeProvider(this.applicationContext); } #endif // Build SessionFactory instance. log.Info("Building new Hibernate SessionFactory"); this.configuration = config; this.sessionFactory = NewSessionFactory(config); AfterSessionFactoryCreation(); // set config time DB provider back to null configTimeDbProvider = null; }
public static void SetListener(Configuration config, object listener) { if (listener == null) throw new ArgumentNullException("listener"); foreach (var intf in listener.GetType().GetInterfaces()) { var intf1 = intf; var listenerInfo = ListenerInfo.Where(i => i.Intf == intf1); foreach (var i in listenerInfo) { var currentListeners = i.ListenerCollection(config.EventListeners); config.SetListeners(i.ListenerType, AppendToArray(currentListeners, listener)); } } }
public static void OverrideIn(Configuration configuration) { configuration.SetListeners( ListenerType.Flush, new IFlushEventListener[] { new FixedDefaultFlushEventListener() }); }