Esempio n. 1
0
        public static void Initialize()
        {
            if (configuration != null)
                throw new InvalidOperationException(Resources.YouCanCallConfigurationManagerInitializeOnlyOnce);

            try
            {
                _configMutex.WaitOne();

                configuration = new Configuration();
                configuration.LinqToHqlGeneratorsRegistry<ExtendedLinqtoHqlGeneratorsRegistry>();

                if (PreCustomConfiguration != null)
                    PreCustomConfiguration(configuration);

                configuration = Fluently.Configure(configuration)
                        .Mappings(m =>
                        {
                            m.FluentMappings
                                .Conventions.Setup(s => s.Add(AutoImport.Never()))
                                .AddFromAssembly(AssemblyToConfigure);
                            m.HbmMappings
                                .AddFromAssembly(AssemblyToConfigure);
                        }).BuildConfiguration();

                if (PosCustomConfiguration != null)
                    PosCustomConfiguration(configuration);
            }
            finally
            {
                _configMutex.ReleaseMutex();
            }
        }
Esempio n. 2
0
        /// <summary>Adds properties to NHibernate configuration.</summary>
        /// <param name="cfg"></param>
        protected virtual void AddProperties(NHibernate.Cfg.Configuration cfg)
        {
            cfg.LinqToHqlGeneratorsRegistry <WhereDetailHqlGeneratorRegistry>();

            foreach (KeyValuePair <string, string> pair in Properties)
            {
                cfg.SetProperty(pair.Key, pair.Value);
            }
        }
        public static void RegisterHierarchySupport(Configuration cfg)
        {
            if (!_criterionRegistered)
            {
                lock (LockObject)
                {
                    if (!_criterionRegistered)
                    {
                        RegisterCriterionSupport();
                        _criterionRegistered = true;
                    }
                }
            }

            #region HQL
            // hid.ToString()
            cfg.SqlFunctions.Add("to_string", new SQLFunctionTemplate(NHibernateUtil.String, "?1.ToString()"));            

            // hid.IsDescendantOf(parent) = 1
            cfg.SqlFunctions.Add("hid_IsDescendantOf", new SQLFunctionTemplate(NHibernateUtil.Boolean, "?1.IsDescendantOf(?2) = 1"));

            // hid.GetAncestor(level)
            cfg.SqlFunctions.Add("hid_GetAncestor", new SQLFunctionTemplate(NHibernateUtil.String, "?1.GetAncestor(?2)"));

            // hid.GetDescendant(child1, child2)
            cfg.SqlFunctions.Add("hid_GetDescendant", new SQLFunctionTemplate(NHibernateUtil.String, "?1.GetDescendant(?2, ?3)"));

            // hid.GetLevel()
            cfg.SqlFunctions.Add("hid_GetLevel", new SQLFunctionTemplate(NHibernateUtil.Int32, "?1.GetLevel()"));

            // hid.GetReparentedValue(old, new)
            cfg.SqlFunctions.Add("hid_GetReparentedValue", new SQLFunctionTemplate(NHibernateUtil.String, "?1.GetReparentedValue(?2, ?3)"));            

            // hierarchyid::Parse
            cfg.SqlFunctions.Add("hid_Parse", new SQLFunctionTemplate(NHibernateUtil.String, "hierarchyid::Parse(?1)"));
            #endregion

            cfg.LinqToHqlGeneratorsRegistry<HierarchyHqlGeneratorRegistry>();            
        }        
Esempio n. 4
0
 protected override void Configure(NHibernate.Cfg.Configuration configuration)
 {
     configuration.LinqToHqlGeneratorsRegistry <MyLinqToHqlGeneratorsRegistry>();
 }
 public void ExtendConfiguration(Configuration configuration)
 {
     configuration.LinqToHqlGeneratorsRegistry<MyLinqToHqlGeneratorsRegistry>();
 }
        public static NHibernate.ISessionFactory BuildSessionFactory(
            string connectionString,
            bool useCache,
            bool useUnitTest = false)
        {
            var mapper = new PostgresNamingConventionAutomapper(useCache); //  NHibernate.Mapping.ByCode.ConventionModelMapper();


            var cfg = new NHibernate.Cfg.Configuration();


            cfg.DataBaseIntegration(c =>
            {
                // PostgreSQL
                c.Driver <AspNetCoreExample.Infrastructure.NHibernateNpgsqlInfra.NpgsqlDriverExtended>();
                c.Dialect <AspNetCoreExample.Infrastructure.NHibernateInfra.PostgresDialectExtension>();

                c.ConnectionString = connectionString;

                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;

#if DEBUG
                c.LogSqlInConsole = true;
                c.LogFormattedSql = true;
#endif
            });


            System.Collections.Generic.IEnumerable <System.Type> entities =
                typeof(AspNetCoreExample.Ddd.IdentityDomain.User)
                .Assembly.GetExportedTypes()
                .Where(x => !(x.IsAbstract && x.IsSealed)); // exclude static



            NHibernate.Cfg.MappingSchema.HbmMapping mapping =
                mapper.CompileMappingFor(entities);

            // The class name Template exits on both namespace RichDomainModel.Document and RichDomainModel.Notification
            // Solution found on:
            // http://stackoverflow.com/questions/1156281/nhibernate-duplicatemappingexception-when-two-classes-have-the-same-name-but-dif
            mapping.autoimport = false;

            cfg.AddMapping(mapping);



            // http://www.ienablemuch.com/2013/06/multilingual-and-caching-on-nhibernate.html
            //var filterDef = new NHibernate.Engine.FilterDefinition("lf", /*default condition*/ null,
            //                                           new Dictionary<string, NHibernate.Type.IType>
            //                                                           {
            //                                                               { "LanguageCultureCode", NHibernate.NHibernateUtil.String}
            //                                                           }, useManyToOne: false);
            //cfg.AddFilterDefinition(filterDef);



            if (useCache)
            {
                cfg.Cache(x =>
                {
                    // SysCache is not stable on unit testing
                    if (!useUnitTest)
                    {
                        x.Provider <NHibernate.Caches.CoreMemoryCache.CoreMemoryCacheProvider>();

                        // I don't know why SysCacheProvider is not stable on simultaneous unit testing,
                        // might be SysCacheProvider is just giving one session factory, so simultaneous test see each other caches
                        // This solution doesn't work: http://stackoverflow.com/questions/700043/mstest-executing-all-my-tests-simultaneously-breaks-tests-what-to-do
                    }
                    else
                    {
                        x.Provider <NHibernate.Caches.CoreMemoryCache.CoreMemoryCacheProvider>();
                    }


                    // http://stackoverflow.com/questions/2365234/how-does-query-caching-improves-performance-in-nhibernate

                    // Need to be explicitly turned on so the .Cacheable directive on Linq will work:
                    x.UseQueryCache = true;
                });
            }


            ////// temporarily set to true so we can see the SQL when we are in web, when we are not in unit test.
            //if (true || useUnitTest)
            //{
            //    cfg.SetInterceptor(new NHSQLInterceptor());
            //}


            cfg.LinqToHqlGeneratorsRegistry <
                AspNetCoreExample.Infrastructure.NHibernateInfra.PostgresLinqToHqlGeneratorsRegistry
                >();

            var sf = cfg.BuildSessionFactory();


            return(sf);
        }
Esempio n. 7
0
 public static void Configure()
 {
     NHConguration = new Configuration().Configure();
     NHConguration.CurrentSessionContext<WcfOperationSessionContext>();
     NHConguration.LinqToHqlGeneratorsRegistry<NHibernateLinqToHqlGeneratorsRegistry>();
     sessionFactory = NHConguration.BuildSessionFactory();
 }
		public void FullConfiguration()
		{
			var configure = new Configuration();
			configure.SessionFactoryName("SomeName");
			configure.Cache(c =>
												{
													c.UseMinimalPuts = true;
													c.DefaultExpiration = 15;
													c.RegionsPrefix = "xyz";
													c.Provider<HashtableCacheProvider>();
													c.QueryCache<StandardQueryCache>();
												});
			configure.CollectionTypeFactory<DefaultCollectionTypeFactory>();
			configure.HqlQueryTranslator<ClassicQueryTranslatorFactory>();
			configure.LinqToHqlGeneratorsRegistry<DefaultLinqToHqlGeneratorsRegistry>();
			configure.Proxy(p =>
												{
													p.Validation = false;
													p.ProxyFactoryFactory<DefaultProxyFactoryFactory>();
												});
			configure.Mappings(m=>
			                   	{
			                   		m.DefaultCatalog = "MyCatalog";
			                   		m.DefaultSchema = "MySche";
			                   	});
			configure.DataBaseIntegration(db =>
			                              	{
			                              		db.Dialect<MsSql2000Dialect>();
			                              		db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
			                              		db.Batcher<SqlClientBatchingBatcherFactory>();
			                              		db.BatchSize = 15;
			                              		db.ConnectionProvider<DebugConnectionProvider>();
			                              		db.Driver<SqlClientDriver>();
			                              		db.ConnectionReleaseMode = ConnectionReleaseMode.AfterTransaction;
			                              		db.IsolationLevel = IsolationLevel.ReadCommitted;
			                              		db.ConnectionString = "The connection string";
			                              		db.AutoCommentSql = true;
			                              		db.ExceptionConverter<SQLStateConverter>();
			                              		db.PrepareCommands = true;
			                              		db.Timeout = 10;
			                              		db.MaximumDepthOfOuterJoinFetching = 11;
			                              		db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'";
			                              		db.SchemaAction = SchemaAutoAction.Validate;
			                              	});

			Assert.That(configure.Properties[Environment.SessionFactoryName], Is.EqualTo("SomeName"));
			Assert.That(configure.Properties[Environment.CacheProvider],
									Is.EqualTo(typeof(HashtableCacheProvider).AssemblyQualifiedName));
			Assert.That(configure.Properties[Environment.CacheRegionPrefix], Is.EqualTo("xyz"));
			Assert.That(configure.Properties[Environment.QueryCacheFactory],
									Is.EqualTo(typeof(StandardQueryCache).AssemblyQualifiedName));
			Assert.That(configure.Properties[Environment.UseMinimalPuts], Is.EqualTo("true"));
			Assert.That(configure.Properties[Environment.CacheDefaultExpiration], Is.EqualTo("15"));
			Assert.That(configure.Properties[Environment.CollectionTypeFactoryClass],
									Is.EqualTo(typeof(DefaultCollectionTypeFactory).AssemblyQualifiedName));
			Assert.That(configure.Properties[Environment.UseProxyValidator], Is.EqualTo("false"));
			Assert.That(configure.Properties[Environment.ProxyFactoryFactoryClass],
						Is.EqualTo(typeof(DefaultProxyFactoryFactory).AssemblyQualifiedName));
			Assert.That(configure.Properties[Environment.QueryTranslator],
						Is.EqualTo(typeof(ClassicQueryTranslatorFactory).AssemblyQualifiedName));
			Assert.That(configure.Properties[Environment.DefaultCatalog], Is.EqualTo("MyCatalog"));
			Assert.That(configure.Properties[Environment.DefaultSchema], Is.EqualTo("MySche"));
			Assert.That(configure.Properties[Environment.Dialect],
						Is.EqualTo(typeof(MsSql2000Dialect).AssemblyQualifiedName));
			Assert.That(configure.Properties[Environment.Hbm2ddlKeyWords], Is.EqualTo("auto-quote"));
			Assert.That(configure.Properties[Environment.BatchStrategy],
						Is.EqualTo(typeof(SqlClientBatchingBatcherFactory).AssemblyQualifiedName));
			Assert.That(configure.Properties[Environment.BatchSize], Is.EqualTo("15"));
			Assert.That(configure.Properties[Environment.ConnectionProvider],
						Is.EqualTo(typeof(DebugConnectionProvider).AssemblyQualifiedName));
			Assert.That(configure.Properties[Environment.ConnectionDriver],
						Is.EqualTo(typeof(SqlClientDriver).AssemblyQualifiedName));
			Assert.That(configure.Properties[Environment.ReleaseConnections],
									Is.EqualTo(ConnectionReleaseModeParser.ToString(ConnectionReleaseMode.AfterTransaction)));
			Assert.That(configure.Properties[Environment.Isolation], Is.EqualTo("ReadCommitted"));
			Assert.That(configure.Properties[Environment.ConnectionString], Is.EqualTo("The connection string"));
			Assert.That(configure.Properties[Environment.UseSqlComments], Is.EqualTo("true"));
			Assert.That(configure.Properties[Environment.SqlExceptionConverter],
									Is.EqualTo(typeof(SQLStateConverter).AssemblyQualifiedName));
			Assert.That(configure.Properties[Environment.PrepareSql], Is.EqualTo("true"));
			Assert.That(configure.Properties[Environment.CommandTimeout], Is.EqualTo("10"));
			Assert.That(configure.Properties[Environment.MaxFetchDepth], Is.EqualTo("11"));
			Assert.That(configure.Properties[Environment.QuerySubstitutions], Is.EqualTo("true 1, false 0, yes 'Y', no 'N'"));
			Assert.That(configure.Properties[Environment.Hbm2ddlAuto], Is.EqualTo("validate"));
			configure.Properties[Environment.LinqToHqlGeneratorsRegistry].Should().Be(typeof(DefaultLinqToHqlGeneratorsRegistry).AssemblyQualifiedName);
		}
Esempio n. 9
0
		protected override void Configure(Configuration configuration)
		{
			configuration.LinqToHqlGeneratorsRegistry<MyLinqToHqlGeneratorsRegistry>();
			base.Configure(configuration);
		}
Esempio n. 10
0
 protected virtual void OnConfigurationExposed(NHibernate.Cfg.Configuration config)
 {
     config.LinqToHqlGeneratorsRegistry <ExtendedLinqtoHqlGeneratorsRegistry>();
 }
        protected virtual void BuildSchema(Configuration config, bool blowDbAway, bool showSql, string schemaExportLocation, ISessionEventSubscriber sessionEventSubscriber, Action<Configuration> nhibConfigCallback)
        {

            config.LinqToHqlGeneratorsRegistry<NhibExtensionsRegistry>();
            if (sessionEventSubscriber != null && sessionEventSubscriber.GetType() != typeof(NoOpSessionEventSubscriber))
            {
                config.Interceptor = new SessionEventPublishingInterceptor(sessionEventSubscriber);
            }
            else
            {
                if (showSql) config.Interceptor = new LoggingInterceptor();
            }

            if (nhibConfigCallback != null)
            {
                nhibConfigCallback.Invoke(config);
            }

            if (!blowDbAway) return;
            var schemaExport = new SchemaExport(config);
            if (!string.IsNullOrEmpty(schemaExportLocation))
                schemaExport.SetOutputFile(schemaExportLocation);

            schemaExport.Execute(!string.IsNullOrEmpty(schemaExportLocation), true, false);

        }