Beispiel #1
0
 private static void Configure()
 {
     cfg = new Configuration();
     //cfg.SetProperty("hibernate.search.default.directory_provider", typeof(RAMDirectoryProvider).AssemblyQualifiedName);
     cfg.SetProperty("hibernate.search.default.directory_provider", typeof(FSDirectoryProvider).AssemblyQualifiedName);
     cfg.SetProperty(NHibernate.Search.Environment.AnalyzerClass, typeof(StopAnalyzer).AssemblyQualifiedName);
     cfg.SetListener(NHibernate.Event.ListenerType.PostUpdate, new FullTextIndexEventListener());
     cfg.SetListener(NHibernate.Event.ListenerType.PostInsert, new FullTextIndexEventListener());
     cfg.SetListener(NHibernate.Event.ListenerType.PostDelete, new FullTextIndexEventListener());
     cfg.Configure();
     sf = cfg.BuildSessionFactory();
 }
Beispiel #2
0
        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;
        }
Beispiel #3
0
        public void TestEvent2()
        {
            var config = new NHibernate.Cfg.Configuration();

            config.Configure();
            config.DataBaseIntegration(db =>
            {
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

            config.SetListener(ListenerType.PreUpdate, new TestUpdateEventListener());

            config.AddDeserializedMapping(InternalHelper.GetAllMapper(), "Models");

            var factory = config.BuildSessionFactory();

            using (var session = factory.OpenSession())
            {
                session.Save(new Message()
                {
                    Content = "Message1", Creator = "Leoli_EventTest"
                });
                session.Flush();
            }

            using (var session = factory.OpenSession())
            {
                var message = session.Get <Message>(1);
                message.Content = "Message_Leoli2";
                session.Save(message);
                session.Flush();
                Assert.AreEqual(message.LastEditor, "Leoli_Update_Event");
            }
        }
Beispiel #4
0
		protected override void Configure(Configuration configuration)
		{
			configuration.SetProperty(Environment.UseSecondLevelCache, "false");
			configuration.SetProperty(Environment.UseQueryCache, "false");
			configuration.SetProperty(Environment.CacheProvider, null);
			configuration.SetListener(ListenerType.PostCommitDelete, new PostCommitDelete());
		}
        public void TestEvent2()
        {
            var config = new NHibernate.Cfg.Configuration();
            config.Configure();
            config.DataBaseIntegration(db =>
            {
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

            config.SetListener(ListenerType.PreUpdate, new TestUpdateEventListener());

            config.AddDeserializedMapping(InternalHelper.GetAllMapper(), "Models");

            var factory = config.BuildSessionFactory();

            using (var session = factory.OpenSession())
            {
                session.Save(new Message() { Content = "Message1", Creator = "Leoli_EventTest" });
                session.Flush();
            }

            using (var session = factory.OpenSession())
            {
                var message = session.Get<Message>(1);
                message.Content = "Message_Leoli2";
                session.Save(message);
                session.Flush();
                Assert.AreEqual(message.LastEditor, "Leoli_Update_Event");
            }
        }
        public NHibernate.Cfg.Configuration Configure()
        {
            var config = new NHibernate.Cfg.Configuration();
            config.SetProperty(Environment.ReleaseConnections, "on_close")
                .SetProperty(Environment.Dialect, typeof (NHibernate.Spatial.Dialect.MsSql2008GeographyDialect).AssemblyQualifiedName)
                .SetProperty(Environment.ConnectionDriver, typeof (NHibernate.Driver.SqlClientDriver).AssemblyQualifiedName);

            var modelMapper = new ModelMapper(new ModelInspector());
            modelMapper.AddMappings(typeof(ModelInspector).Assembly.GetExportedTypes());

            var mapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
            config.AddMapping(mapping);

            config.SetListener(NHibernate.Event.ListenerType.PostUpdate, new FullTextIndexEventListener());
            config.SetListener(NHibernate.Event.ListenerType.PostInsert, new FullTextIndexEventListener());
            config.SetListener(NHibernate.Event.ListenerType.PostDelete, new FullTextIndexEventListener());

            return config;
        }
Beispiel #7
0
        private void AppendListeners(NHibernate.Cfg.Configuration configuration)
        {
            configuration.AppendListeners(ListenerType.PreInsert,
                                          new[]
            {
                new SetCoreProperties()
            });
            SoftDeleteListener softDeleteListener = new SoftDeleteListener();

            configuration.SetListener(ListenerType.Delete, softDeleteListener);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="config"></param>
        protected override void PostProcessConfiguration(Configuration config)
        {
            if (FluentNhibernateMappingAssemblies != null)
            {
                foreach (var assemblyName in FluentNhibernateMappingAssemblies)
                {
                    config.AddMappingsFromAssembly(Assembly.Load(assemblyName));
                }
            }

            config.Properties.Add("nhibernate.envers.Diversia_with_modified_flag", "true");
                //log property data for revisions
            config.IntegrateWithEnvers(new AttributeConfiguration());
            config.SetListener(ListenerType.PreInsert, new DiversiaAuditEventListener());
            config.SetListener(ListenerType.PreUpdate, new DiversiaAuditEventListener());
            config.SetListener(ListenerType.PreDelete, new DiversiaAuditEventListener());
            config.SetListener(ListenerType.PreCollectionRecreate, new DiversiaAuditEventListener());
            config.SetListener(ListenerType.PreCollectionUpdate, new DiversiaAuditEventListener());
            config.SetListener(ListenerType.PreCollectionRemove, new DiversiaAuditEventListener());
            config.Cache(c =>
            {
                c.UseMinimalPuts = true;
                c.UseQueryCache = true;
                c.Provider<SysCacheProvider>();
            });
        }
        public NHibernate.Cfg.Configuration Configure()
        {
            var config = new NHibernate.Cfg.Configuration();

            config.SetProperty(Environment.ReleaseConnections, "on_close")
            .SetProperty(Environment.Dialect, typeof(NHibernate.Spatial.Dialect.MsSql2008GeographyDialect).AssemblyQualifiedName)
            .SetProperty(Environment.ConnectionDriver, typeof(NHibernate.Driver.SqlClientDriver).AssemblyQualifiedName);

            var modelMapper = new ModelMapper(new ModelInspector());

            modelMapper.AddMappings(typeof(ModelInspector).Assembly.GetExportedTypes());

            var mapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();

            config.AddMapping(mapping);

            config.SetListener(NHibernate.Event.ListenerType.PostUpdate, new FullTextIndexEventListener());
            config.SetListener(NHibernate.Event.ListenerType.PostInsert, new FullTextIndexEventListener());
            config.SetListener(NHibernate.Event.ListenerType.PostDelete, new FullTextIndexEventListener());

            return(config);
        }
 public static void SetListener(Configuration configure)
 {
     configure.SetListener(ListenerType.PostUpdate, new FullTextIndexEventListener());
     configure.SetListener(ListenerType.PostInsert, new FullTextIndexEventListener());
     configure.SetListener(ListenerType.PostDelete, new FullTextIndexEventListener());
     configure.SetListener(ListenerType.PostCollectionRecreate, new FullTextIndexCollectionEventListener());
     configure.SetListener(ListenerType.PostCollectionRemove, new FullTextIndexCollectionEventListener());
     configure.SetListener(ListenerType.PostCollectionUpdate, new FullTextIndexCollectionEventListener());
 }
 private void AddSearchListeners(Configuration cfg)
 {
     cfg.SetListener(ListenerType.PostUpdate, new FullTextIndexEventListener());
     cfg.SetListener(ListenerType.PostInsert, new FullTextIndexEventListener());
     cfg.SetListener(ListenerType.PostDelete, new FullTextIndexEventListener());
     cfg.SetListener(ListenerType.PostCollectionRecreate, new FullTextIndexCollectionEventListener());
     cfg.SetListener(ListenerType.PostCollectionRemove, new FullTextIndexCollectionEventListener());
     cfg.SetListener(ListenerType.PostCollectionUpdate, new FullTextIndexCollectionEventListener());
 }
Beispiel #12
0
        /// <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;
        }
        private static ISessionFactory CreateSessionFactory()
        {
            var cfg = new Configuration()
                .SetInterceptor(new DontHurtMe())
                .SetProperty(NHibernate.Cfg.Environment.Hbm2ddlAuto, "update")
                .SetProperty(NHibernate.Cfg.Environment.DefaultBatchFetchSize, "10")
                .DataBaseIntegration(db =>
                {
                    db.ConnectionString = @"Data Source=.\sqlexpress;Initial Catalog=nh;Integrated Security=SSPI";
                    db.Dialect<MsSql2008Dialect>();
                })
                .AddAssembly(Assembly.GetExecutingAssembly());

            cfg
                .SetListener(ListenerType.PreUpdate, new AuditListener());

            return cfg.BuildSessionFactory();
        }
        private ISessionFactory GetSessionFactory()
        {
            Configuration = new Configuration().Configure("NHibernate.config");
            string path = Environment.CurrentDirectory + "\\TestDB.db3";
            Configuration.Properties["connection.connection_string"] = "Data Source=" + path + ";Version=3;";

            FluentConfiguration fluentConfiguration = Fluently.Configure(Configuration);
            Configuration.SetListener(ListenerType.Delete, new MyDeleteEventListener());
            Configuration.SetListener(ListenerType.Load, new MyLoadEventListener());
            InitMapping(fluentConfiguration);

            var sf= fluentConfiguration.BuildSessionFactory();
            //fluentConfiguration.Mappings(x => x.AutoMappings.ExportTo(@"D:\Temp"));
            CreateHighLowTable(Configuration, new HiloTable() { TableNameColumn = PrimaryKeyConvention.TableColumnName, Name = PrimaryKeyConvention.NHibernateHiLoIdentityTableName, NextHiColumn = PrimaryKeyConvention.NextHiValueColumnName });

            return sf;
        }
Beispiel #15
0
 private static void InitializeSearch(NHibernate.Cfg.Configuration configuration)
 {
     configuration.SetListener(ListenerType.PostUpdate, new AuditEventListener());
     configuration.SetListener(ListenerType.PostInsert, new AuditEventListener());
     configuration.SetListener(ListenerType.PostDelete, new AuditEventListener());
 }
Beispiel #16
0
 private void SetListener(Configuration config, object listener)
 {
     if (listener == null)
         throw new ArgumentNullException("listener");
     foreach (var intf in listener.GetType().GetInterfaces())
         if (ListenerDict.ContainsKey(intf))
             foreach (var t in ListenerDict[intf])
                 config.SetListener(t, listener);
 }
Beispiel #17
0
        /// <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 void Apply(Configuration cfg)
		{
			cfg.SetListener(ListenerType.PostUpdate, new FullTextIndexEventListener());
			cfg.SetListener(ListenerType.PostInsert, new FullTextIndexEventListener());
			cfg.SetListener(ListenerType.PostDelete, new FullTextIndexEventListener());
		}
Beispiel #19
0
		protected override void Configure(Configuration cfg)
		{
			cfg.SetListener(ListenerType.PreInsert, new PreSaveDoVeto());
		}
Beispiel #20
0
		protected override void Configure(Configuration configuration)
		{
			configuration.SetProperty(Environment.FormatSql, "false");
			configuration.SetListener(ListenerType.PostUpdate, new PostUpdateEventListener());
		}
Beispiel #21
0
        private static void Main(string[] args)
        {
            XmlConfigurator.Configure(new FileInfo("nhprof.log4net.config"));

            Configuration cfg = new Configuration()
                .Configure("nhibernate.cfg.xml");

            cfg.SetProperty("hibernate.search.default.directory_provider",
                            typeof (FSDirectoryProvider).AssemblyQualifiedName);
            cfg.SetProperty(Environment.AnalyzerClass,
                            typeof (StopAnalyzer).AssemblyQualifiedName);

            cfg.SetListener(ListenerType.PostUpdate, new FullTextIndexEventListener());
            cfg.SetListener(ListenerType.PostInsert, new FullTextIndexEventListener());
            cfg.SetListener(ListenerType.PostDelete, new FullTextIndexEventListener());

            using (new ConsoleColorer("nhibernate"))
                new SchemaExport(cfg).Execute(true, true, false, true);

            ISessionFactory factory = cfg.BuildSessionFactory();
            using (IFullTextSession s = Search
                .CreateFullTextSession(factory.OpenSession()))
            using (ITransaction tx = s.BeginTransaction())
            {
                s.PurgeAll(typeof (Employee));
                s.PurgeAll(typeof (Salary));

                var salary = new Salary
                                 {
                                     Name = "MinPay",
                                     HourlyRate = 22m
                                 };
                var emp = new Employee
                              {
                                  Name = "ayende",
                                  Salary = salary
                              };
                s.Save(salary);
                s.Save(emp);


                tx.Commit();
            }

            Thread.Sleep(1500);
            Console.Clear();
            using (IFullTextSession s = Search.CreateFullTextSession(factory.OpenSession()))
            using (ITransaction tx = s.BeginTransaction())
            {
                var employees = s.CreateFullTextQuery<Employee>("Name", "a*")
                    .List<Employee>();
                foreach (Employee employee in employees)
                {
                    Console.WriteLine("Employee: " + employee.Name);
                    Console.WriteLine("Salary: {0} - {1:C}",
                                      employee.Salary.Name,
                                      employee.Salary.HourlyRate);
                }

                var salaries = s.CreateFullTextQuery<Salary>("HourlyRate:[20 TO 25]")
                    .List<Salary>();
                foreach (var salary in salaries)
                {
                    Console.WriteLine("Salaray: {0} - {1:C}", salary.Name, salary.HourlyRate);
                }

                tx.Commit();
            }
        }
Beispiel #22
0
 private static void AddAuditor(Configuration config)
 {
     config.SetListener(ListenerType.PostUpdate, new AuditUpdateListener());
 }