Example #1
0
        protected static ISessionFactory BuildSessionFactory()
        {
            IDictionary <string, string> props = new Dictionary <string, string>();

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

            cfg.SetInterceptor(new Intercepter());



            try
            {
                //var ch = Fluently.Configure()
                //        .Database(MySQLConfiguration.Standard
                //        .ConnectionString(c => c.FromAppSetting("NHBCon")))
                //        .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
                //        .BuildSessionFactory();

                var ch = Fluently.Configure().Database(MySQLConfiguration.Standard.ConnectionString(c => c.FromAppSetting("NHBCon"))
                                                       .ShowSql())
                         .Mappings(m => m.FluentMappings.AddFromAssemblyOf <User>())
                         .ExposeConfiguration(conf => new SchemaUpdate(conf).Execute(true, true))
                         .BuildSessionFactory();
                return(ch);
            }
            catch (Exception e)
            {
                // inner exception
                // No such host is known
                // Unable to connect to any of the specified MySql hosts
            }


            return(null);
        }
Example #2
0
 private void BuildSchema(Configuration config)
 {
     SchemaExport schema = new SchemaExport(config);
     schema.Drop(this._criaScript, this._exportaScriptBD);
     schema.Create(this._criaScript, this._exportaScriptBD);
     config.SetInterceptor(new SqlStatementInterceptor());
 }
        private Configuration GetConfiguration()
        {
            var config = new Configuration().Configure();
            this.mappingAssemblies.ForEach(ma => config.AddAssembly(ma));
            config.SetInterceptor(new SqlQueryInterceptor());

            return config;
        }
        public static CoreNHibernate.ISessionFactory CreateSessionFactory(DBTypes dbType)
        {
            FluentConfiguration config = Fluently.Configure();

            switch (dbType)
            {
            case DBTypes.Oracle:
                config = OracleHelper.ConfigurationFactory();
                break;

            case DBTypes.MSSQL:
                config = MsSqlHelper.ConfigurationFactory();
                break;

            case DBTypes.SQLite:
                config = SQLiteHelper.ConfigurationFactory();
                break;

            case DBTypes.MySQL:
            default:
                throw new NotImplementedException("Not implemented yet...");
            }

            var enversConf = new EnversNHibernate.Configuration.Fluent.FluentConfiguration();

            List <Type> domainEntities = Assembly.GetAssembly(typeof(Clients)).GetTypes() // Assembly.Load("bilisimHR.DataLayer.Core").GetTypes()
                                         .Where(t => (typeof(Entity <int>).IsAssignableFrom(t) && !t.IsGenericType))
                                         .ToList();

            foreach (Type type in domainEntities)
            {
                enversConf.Audit(type);
            }

            CoreNHibernate.Cfg.Configuration cfg = new CoreNHibernate.Cfg.Configuration();
            cfg = config.BuildConfiguration();

            cfg.BuildMappings();
            cfg.SetInterceptor(new TrackingInterceptor());

            //Envers RevType Values
            //0(ADD), 1(MODIFY) and 2(DELETE)
            ConfigurationKey.AuditTableSuffix.SetUserValue(cfg, "_LOG");
            IRevisionInfoService revInfoService = new RevisionInfoService();

            // Service Locator Registry
            ServiceLocator.RegisterService(revInfoService);
            ServiceLocator.RegisterService(new HttpRequestMessageService());

            enversConf.SetRevisionEntity <CustomRevInfo>(e => e.Id, e => e.RevisionDate, new CustomRevInfoListener());
            cfg.IntegrateWithEnvers(enversConf);

            config.ExposeConfiguration(exp => new SchemaUpdate(cfg).Execute(false, true))
            .ExposeConfiguration(c => { c.CurrentSessionContext <CoreNHibernate.Context.CallSessionContext>(); });
            //config.ExposeConfiguration(exp => new SchemaExport(cfg).Execute(true, true, false));
            return(config.BuildSessionFactory());
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="TemporaryDatabase"/> class.
 /// </summary>
 public TemporaryDatabase()
 {
     _database = new TemporarySqlDatabase();
     var configuration = new Configuration();
     configuration.SetInterceptor(new PostSaveInterceptor());
     configuration.SetProperty("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
     configuration.SetProperty("connection.driver_class", "NHibernate.Driver.SqlClientDriver");
     configuration.SetProperty("connection.connection_string", _database.ConnectionString);
     configuration.SetProperty("dialect", "NHibernate.Dialect.MsSql2005Dialect");
     configuration.SetProperty("show_sql", "true");
     configuration.AddAssembly(typeof(IRepository).Assembly);
     _sessionFactory = configuration.BuildSessionFactory();
     var upgradeManager = new DatabaseManager(_database.ConnectionString);
     upgradeManager.PerformUpgrade();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="TestableDatabase"/> class.
 /// </summary>
 public TestableDatabase()
 {
     _database = new TemporarySqlDatabase();
     var configuration = new Configuration();
     configuration.SetInterceptor(new PostSaveInterceptor());
     configuration.SetProperty("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
     configuration.SetProperty("connection.driver_class", "NHibernate.Driver.SqlClientDriver");
     configuration.SetProperty("connection.connection_string", _database.ConnectionString);
     configuration.SetProperty("dialect", "NHibernate.Dialect.MsSql2005Dialect");
     configuration.SetProperty("show_sql", "true");
     configuration.AddMappingsFromAssembly(Cms.Domain.Properties.AssemblyReference.Assembly);
     _sessionFactory = configuration.BuildSessionFactory();
     var upgradeManager = new ApplicationDatabase(_database.ConnectionString);
     upgradeManager.PerformUpgrade();
 }
 public Configuration GetConfiguration()
 {
     if (m_Configuration == null)
     {
         lock (m_Locker)
         {
             if (m_Configuration == null)
             {
                 m_Configuration = Configuration;
                 m_Configuration.SetInterceptor(Interceptor);
                 foreach (IRegisterEventListener registerListener in RegisterEventListeners)
                 {
                     registerListener.Register(m_Configuration);
                 }
             }
         }
     }
     return m_Configuration;
 }
        public static Configuration BuildConfiguration(string mappingAssembliesFile, string hibernateConfigurationFile, string applicationDirectory, params IInterceptor[] interceptors)
        {
            var mapper = BuildModelMapper(mappingAssembliesFile, applicationDirectory);
            var cfg = new Configuration();

            if (File.Exists(hibernateConfigurationFile))
            {
                cfg.Configure(hibernateConfigurationFile);
            }

            if (mapper != null)
            {
                cfg.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), string.Empty);
            }

            foreach (var interceptor in interceptors)
            {
                cfg.SetInterceptor(interceptor);
            }

            return cfg;
        }
Example #9
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;
        }
Example #10
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;
        }
Example #11
0
        // Call this on unit testing, so we can test caching on each test method independently
        public static NHibernate.ISessionFactory BuildSessionFactory(bool useUnitTest = false)
        {
            var mapper = new NHibernate.Mapping.ByCode.ModelMapper();

            mapper.AddMappings
            (
                typeof(Mapper).Assembly.GetTypes()
                .Where(x => x.BaseType.IsGenericType &&
                       x.BaseType.GetGenericTypeDefinition() == typeof(NHibernate.Mapping.ByCode.Conformist.ClassMapping <>))
            );

            // Or you can manually add the mappings
            // mapper.AddMappings(new[]
            //    {
            //        typeof(PersonMapping)
            //    });


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

            // .DatabaseIntegration! Y U EXTENSION METHOD?
            cfg.DataBaseIntegration(c =>
            {
                var cs = "Server=localhost;Database=test;User Id=sa;password=opensesame93*#;MultipleActiveResultSets=True";

                // SQL Server
                c.Driver <NHibernate.Driver.SqlClientDriver>();
                c.Dialect <NHibernate.Dialect.MsSql2012Dialect>();
                c.ConnectionString = cs;


                c.LogSqlInConsole = true;
                c.LogFormattedSql = true;
            });

            var domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();


            // // AsString is an extension method from NHibernate.Mapping.ByCode:
            // string mappingXml = domainMapping.AsString();

            // // Life without Resharper.
            // string mappingXml = NHibernate.Mapping.ByCode.MappingsExtensions.AsString(domainMapping);

            // System.Console.WriteLine(mappingXml);


            cfg.AddMapping(domainMapping);


            if (useUnitTest)
            {
                cfg.SetInterceptor(new NHSqlInterceptor());
            }

            var sf = cfg.BuildSessionFactory();



            //using (var file = new System.IO.FileStream(@"c:\x\ddl.txt",
            //       System.IO.FileMode.Create,
            //       System.IO.FileAccess.ReadWrite))
            //using (var sw = new System.IO.StreamWriter(file))
            //{
            //    new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg)
            //        .Execute(scriptAction: sw.Write, doUpdate: false);
            //}

            return(sf);
        }
Example #12
0
        public static NHibernate.ISessionFactory BuildSessionFactory(bool useUnitTest = false)
        {
            var mapper = new NHibernate.Mapping.ByCode.ConventionModelMapper();


            mapper.IsEntity((t, declared) => t.Namespace == "Domain");

            mapper.BeforeMapClass     += mapper_BeforeMapClass;
            mapper.BeforeMapProperty  += mapper_BeforeMapProperty;
            mapper.BeforeMapManyToOne += mapper_BeforeMapManyToOne;
            mapper.BeforeMapBag       += mapper_BeforeMapBag;

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



            // .DatabaseIntegration! Y U EXTENSION METHOD?!
            cfg.DataBaseIntegration(c =>
            {
                var cs = System.Configuration.ConfigurationManager.ConnectionStrings["TheSpaConnection"].ConnectionString;


                // SQL Server
                c.Driver <NHibernate.Driver.SqlClientDriver>();
                c.Dialect <NHibernate.Dialect.MsSql2008Dialect>();
                c.ConnectionString = "Server=.;Database=SpaArchitectureMvp;Trusted_Connection=True";

                //// PostgreSQL               
                //c.Driver<NHibernate.Driver.NpgsqlDriver>();
                //c.Dialect<NHibernate.Dialect.PostgreSQLDialect>();
                //c.ConnectionString = cs;

                if (useUnitTest)
                {
                    c.LogSqlInConsole = true;
                    c.LogFormattedSql = true;
                }
            });


            System.Collections.Generic.IEnumerable <System.Type> entities = typeof(Domain.PersonDomain.Person).Assembly.GetExportedTypes()
                                                                            .Where(x => !(x.IsAbstract && x.IsSealed)); // exclude static



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

            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);



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

                    // 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
                {
                    // This is more stable in unit testing
                    x.Provider <NHibernate.Cache.HashtableCacheProvider>();
                }


                // 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;
            });



            if (useUnitTest)
            {
                cfg.SetInterceptor(new NHSQLInterceptor());
            }



            //new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg).Execute(useStdOut: false, doUpdate: true);


            //using (var file = new System.IO.FileStream(@"c:\x\ddl.txt",
            //       System.IO.FileMode.Create,
            //       System.IO.FileAccess.ReadWrite))
            //using (var sw = new System.IO.StreamWriter(file))
            //{
            //    new SchemaUpdate(cfg)
            //        .Execute(sw.Write, false);
            //}


            var sf = cfg.BuildSessionFactory();



            return(sf);
        }
		protected override void Configure(Configuration configuration)
		{
			configuration.SetInterceptor(new ProxyInterceptor());
		}
        public static NHibernate.ISessionFactory BuildSessionFactory(bool useUnitTest = false)
        {
            var mapper = new NHibernate.Mapping.ByCode.ConventionModelMapper();


            mapper.IsEntity((t, declared) => t.Namespace == "Domain");

            mapper.BeforeMapClass += mapper_BeforeMapClass;
            mapper.BeforeMapProperty += mapper_BeforeMapProperty;
            mapper.BeforeMapManyToOne += mapper_BeforeMapManyToOne;            
            mapper.BeforeMapBag += mapper_BeforeMapBag;

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



            // .DatabaseIntegration! Y U EXTENSION METHOD?!
            cfg.DataBaseIntegration(c =>
            {
                var cs = System.Configuration.ConfigurationManager.ConnectionStrings["TheSpaConnection"].ConnectionString;


                // SQL Server
                c.Driver<NHibernate.Driver.SqlClientDriver>();
                c.Dialect<NHibernate.Dialect.MsSql2008Dialect>();
                c.ConnectionString = "Server=.;Database=SpaArchitectureMvp;Trusted_Connection=True";

                //// PostgreSQL                
                //c.Driver<NHibernate.Driver.NpgsqlDriver>();
                //c.Dialect<NHibernate.Dialect.PostgreSQLDialect>();
                //c.ConnectionString = cs;

                if (useUnitTest)
                {
                    c.LogSqlInConsole = true;
                    c.LogFormattedSql = true;
                }
            });


            System.Collections.Generic.IEnumerable<System.Type> entities = typeof(Domain.PersonDomain.Person).Assembly.GetExportedTypes()
                .Where(x => !(x.IsAbstract && x.IsSealed)); // exclude static 



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

            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);



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

                    // 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
                {
                    // This is more stable in unit testing
                    x.Provider<NHibernate.Cache.HashtableCacheProvider>();
                }


                // 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;
            });



            if (useUnitTest)
                cfg.SetInterceptor(new NHSQLInterceptor());



            //new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg).Execute(useStdOut: false, doUpdate: true);


            //using (var file = new System.IO.FileStream(@"c:\x\ddl.txt",
            //       System.IO.FileMode.Create,
            //       System.IO.FileAccess.ReadWrite))
            //using (var sw = new System.IO.StreamWriter(file))
            //{
            //    new SchemaUpdate(cfg)
            //        .Execute(sw.Write, false);
            //}


            var sf = cfg.BuildSessionFactory();




            return sf;
        }
Example #15
0
        public NHibernate.Cfg.Configuration GetConfiguration()
        {
            // TODO: It should be possible to define this config in some XML file as well
            // Google to find out how

            var cfg = new NHibernate.Cfg.Configuration();
            {
                // This way of configuring works, but I want to try out the xml config file
                //cfg.DataBaseIntegration(x =>
                //{
                //    x.ConnectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=NHibernate01;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
                //    x.Driver<SqlClientDriver>();
                //    x.Dialect<MsSqlCeDialect>();
                //});

                //cfg.AddAssembly(Assembly.GetExecutingAssembly());
            }
            {
                // Use xml for configuration
                // Add hibernate.cfg.xml as Embedded Resource in a folder named Configuration
                // use cfg.Configure(assembly, resourceName) version
                // The other version cfg.Configure(resourceName) always searches for the file in startup project

                var assembly = Assembly.GetExecutingAssembly();
                var assemblyName = assembly.GetName().Name;
                var manifestResourceName = "Configuration.hibernate.cfg.xml";

                cfg.Configure(assembly, $"{assemblyName}.{manifestResourceName}"); // ORM_NHibernate.Configuration.hibernate.cfg.xml


                //// You can also add Mappings by Code .. Note here that we have not defined any HBM for Teacher class
                //// Also not that we've updated the Student HBM file to set VARCHAR(1000) instead of the default 255
                //var mapper = new NHibernate.Mapping.ByCode.ConventionModelMapper();
                //cfg.AddMapping(mapper.CompileMappingFor(new[] { typeof(BusinessObjects.Teacher) }));

                foreach (var mapping in cfg.ClassMappings)
                {
                    string x = $"(1) {mapping.ClassName}, (2) {mapping.Discriminator}, (3) {mapping.DiscriminatorValue}, (4) {mapping.IsDiscriminatorValueNotNull}";
                    System.Diagnostics.Debug.WriteLine(x);
                }



                var schemaExport = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
                schemaExport.SetOutputFile(@"db.Postgre.sql").Execute(useStdOut: true, execute: true, justDrop: false);

                //// Example Schema Export
                ///
                /*
                 * 
                    create table ActorRole (
                        id INTEGER not null,
                       Actor VARCHAR(255) not null,
                       Role VARCHAR(255) not null,
                       MovieId INTEGER,
                       ActorIndex INTEGER,
                       primary key (id)
                    )

                    create table product (
                        id INTEGER not null,
                       Name VARCHAR(255) not null,
                       description VARCHAR(100),
                       UnitPrice NUMERIC(18,4) not null,
                       primary key (id)
                    )

                    create table Book (
                        Id INTEGER not null,
                       ISBN VARCHAR(255),
                       Author VARCHAR(255),
                       primary key (Id)
                    )

                    create table Movie (
                        Id INTEGER not null,
                       Director VARCHAR(255),
                       primary key (Id)
                    )

                    alter table ActorRole
                        add index (MovieId),
                        add constraint FK_B3337C3E
                        foreign key (MovieId)
                        references Movie (Id)

                    alter table Book
                        add index (Id),
                        add constraint FK_2E5EFA32
                        foreign key (Id)
                        references product (id)

                    alter table Movie
                        add index (Id),
                        add constraint FK_13C98C6D
                        foreign key (Id)
                        references product (id)

                    create table hibernate_unique_key (
                         next_hi INTEGER
                    )

                    insert into hibernate_unique_key values ( 1 )
                 * 
                 * */


                // Alternately, we can use SchemaUpdate.Execute, as in done in 1P
                NHibernate.Tool.hbm2ddl.SchemaUpdate schemaUpdate = new NHibernate.Tool.hbm2ddl.SchemaUpdate(cfg);
                schemaUpdate.Execute(useStdOut: true, doUpdate: true);

                // Note
                // SchemaUpdate.Execute is way cooler than SchemaExport.Filename.Execute
                // When I added a new property in Movie.hbm.xml (and in the .cs), SchemaUpdate automatically created statement 
                // to tell the diff in schema, and only this got executed:
                /*
                    alter table Movie
                        add column NewProp VARCHAR(255)
                 * 
                 * */
                //
                // However, it does not work as expected all the times, for eg, 
                // if I rename a column in HBM, it just adds a new column with new name
                // if I change the sql-type from VARCHAR(255) to VARCHAR(100), nothing is executed and the column type remains unchanged
                // So we will need manual scripts for migration
                //

                cfg.SetInterceptor(new AuditInterceptor());
            }

            return cfg;
        }
Example #16
0
 private static void SetInterceptors(Configuration cfg)
 {
     cfg.SetInterceptor(new SqlStatementInterceptor());
 }
        private static Configuration CreateConfiguration()
        {
            var cfg = new Configuration();
            //cfg.SetNamingStrategy(new NamingConvention());
            cfg.DataBaseIntegration(properties =>
            {
                //properties.SchemaAction = SchemaAutoAction.Validate;
                properties.Dialect<NHibernate.Dialect.MsSql2008Dialect>();
                properties.ConnectionStringName = Environment.MachineName;
            });
            cfg.AddAssembly(Assembly.GetExecutingAssembly());
            cfg.SetInterceptor(new DontMakeMeCRY());

            cfg.SetProperty(
                NHibernate.Cfg.Environment.DefaultBatchFetchSize,
                "25");
            return cfg;
        }
		protected override void Configure(Configuration configuration)
		{
			configuration.SetInterceptor(new EntityNameInterceptor());
		}
Example #19
0
 private static Configuration CreateNHibernateConfiguration(IUnityContainer container)
 {
     var cfg = new Configuration().Configure();
     cfg.SetInterceptor(new BuildWithProviderInterceptor(container.Resolve<IServiceProvider>(), cfg.ClassMappings));
     return cfg;
 }
        /// <summary>
        /// The session factory.
        /// </summary>
        /// <returns>A session factory.</returns>
        protected override ISessionFactory CreateSessionFactory()
        {
            ISessionFactory factory;
            if (!NHibernateEntityContext.sessionFactories.TryGetValue(ENABLED_ENVIRONMENT_MARKER, out factory))
            {
                IPersistenceConfigurer persistence = null;

                switch (ApplicationModelConfiguration.Configuration.Server.Environments.GetEnabledEnvironment().DataSource.Dialect)
                {
                    case "MsSql2005":
                        {
                            string connectionString = ApplicationModelConfiguration.Configuration.Server.Environments.GetEnabledEnvironment().DataSource.ConnectionString;
                            persistence = MsSqlConfiguration.MsSql2005.ConnectionString(connectionString);
                        }
                        break;

                    case "MsSql2008":
                        {
                            string connectionString = ApplicationModelConfiguration.Configuration.Server.Environments.GetEnabledEnvironment().DataSource.ConnectionString;
                            persistence = MsSqlConfiguration.MsSql2008.ConnectionString(connectionString);
                        }
                        break;

                    case "SQLite":
                        {
                            string connectionString = ApplicationModelConfiguration.Configuration.Server.Environments.GetEnabledEnvironment().DataSource.ConnectionString;
                            persistence = SQLiteConfiguration.Standard.ConnectionString(connectionString);
                        }
                        break;

                    default:
                        throw new NotImplementedException();
                }

                string mappingAssembly = ApplicationModelConfiguration.Configuration.Server.Environments.GetEnabledEnvironment().Settings[MAPPING_ASSEMBLY_IDENTIFIER].Value;

                Configuration configuration = new Configuration();
                configuration.SetInterceptor(new NhibernateSqlInterceptor());

                FluentConfiguration fluentConfiguration =
                    Fluently.Configure(configuration)
                        .Database(persistence)
                        .Mappings(mappings => mappings.FluentMappings.AddFromAssembly(Assembly.Load(mappingAssembly)));

                NHibernateEntityContext.sessionFactories[ENABLED_ENVIRONMENT_MARKER] = factory = fluentConfiguration.BuildSessionFactory();
            }

            return factory;
        }