Example #1
0
 public static void Configure(string pathToConfig, Assembly mappingsAssembly)
 {
     _cfg = new Configuration();
     _cfg.Configure(pathToConfig);
     _cfg.AddAssembly(mappingsAssembly);
     _cfg.BuildMappings();
     _sessionFactory = _cfg.BuildSessionFactory();
 }
        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());
        }
        public MigrationGenerator(NHibernate.Cfg.Configuration configuration, Encoding encoding)
        {
            this.Encoding = encoding;
            Configuration = configuration;
            Configuration.BuildMappings(); // necessary to complete columns creation (foreign keys...)

            var mapping = Configuration.CreateMappings(new GenericDialect());

            // extract the tables scheme
            CurrentScheme = new MigrationScheme(mapping.IterateTables.Select(t => new MigrationTable(t)));
            UpdateForeignKeys();

            PreviousSnapshotFileName = string.Format("{0}\\previous.snapshot", Directory.GetCurrentDirectory());
        }
		public void NwaitingForSuper()
		{
			Configuration cfg = new Configuration();

			cfg.AddResource(BaseForMappings + "Extendshbm.Customer.hbm.xml", typeof (ExtendsFixture).Assembly);
			Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Null, "cannot be in the configuration yet!");

			cfg.AddResource(BaseForMappings + "Extendshbm.Employee.hbm.xml", typeof (ExtendsFixture).Assembly);
			Assert.That(cfg.GetClassMapping(typeof (Employee).FullName), Is.Null, "cannot be in the configuration yet!");

			cfg.AddResource(BaseForMappings + "Extendshbm.Person.hbm.xml", typeof (ExtendsFixture).Assembly);

			cfg.BuildMappings();
			Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof (Person).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof (Employee).FullName), Is.Not.Null);
		}
Example #5
0
        public NHibernate.Cfg.Configuration GetConfiguration()
        {
            List <Assembly> assemblies = GetAssemblies();


            IPersistenceConfigurer iPersistenceConfigurer = _databaseProvider.GetPersistenceConfigurer();
            AutoPersistenceModel   autoPersistenceModel   = GetAutoPersistenceModel(assemblies);

            ApplyCoreFilters(autoPersistenceModel);

            NHibernate.Cfg.Configuration config = Fluently.Configure()
                                                  .Database(iPersistenceConfigurer)
                                                  .Mappings(m => m.AutoMappings.Add(autoPersistenceModel))
                                                  .Cache(SetupCache)
                                                  .ExposeConfiguration(AppendListeners)
                                                  .ExposeConfiguration(AppSpecificConfiguration)
                                                  .ExposeConfiguration(c =>
            {
#if DEBUG
                c.SetProperty(Environment.GenerateStatistics, "true");
                c.SetProperty(Environment.ShowSql, "true");
#else
                c.SetProperty(Environment.GenerateStatistics, "false");
#endif
                c.SetProperty(Environment.Hbm2ddlKeyWords, "auto-quote");
                c.SetProperty(Environment.BatchSize, "25");
            })
                                                  .BuildConfiguration();


            _databaseProvider.AddProviderSpecificConfiguration(config);

            ValidateSchema(config);

            config.BuildMappings();

            return(config);
        }
Example #6
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 SetUp()
		{
			cfg = new Configuration()
					.AddResource("NHibernate.Test.MappingTest.Wicked.hbm.xml", GetType().Assembly);
			cfg.BuildMappings();
		}
		public void JoinedSubclassAndEntityNamesOnly()
		{
			Configuration cfg = new Configuration();

			cfg.AddResource(BaseForMappings + "Extendshbm.entitynames.hbm.xml", typeof (ExtendsFixture).Assembly);

			cfg.BuildMappings();
			Assert.That(cfg.GetClassMapping("EntityHasName"), Is.Not.Null);
			Assert.That(cfg.GetClassMapping("EntityCompany"), Is.Not.Null);
		}
		public void UnionSubclass()
		{
			Configuration cfg = new Configuration();

			cfg.AddResource(BaseForMappings + "Extendshbm.unionsubclass.hbm.xml", typeof (ExtendsFixture).Assembly);

			cfg.BuildMappings();

			Assert.That(cfg.GetClassMapping(typeof (Person).FullName), Is.Not.Null);
			Assert.That(cfg.GetClassMapping(typeof (Customer).FullName), Is.Not.Null);
		}
		public void EntityNamesWithPackageFailureExpectedDiffFiles()
		{
			Configuration cfg = new Configuration();
			cfg.AddResource(BaseForMappings + "Extendshbm.packageentitynamesf1.hbm.xml", typeof(ExtendsFixture).Assembly);
			cfg.AddResource(BaseForMappings + "Extendshbm.packageentitynamesf2.hbm.xml", typeof(ExtendsFixture).Assembly);

			cfg.BuildMappings();

			Assert.That(cfg.GetClassMapping("EntityHasName"), Is.Not.Null);
			Assert.That(cfg.GetClassMapping("EntityCompany"), Is.Not.Null);
		}
 private static void Configure(Configuration config)
 {
     config.BuildMappings();
     new SchemaUpdate(config).Execute(false, true);
 }
Example #12
0
        private void ConfigureNHibernate()
        {
            _configuration = new Configuration();
            _configuration.DataBaseIntegration(x =>
                {
                    if (_inMemory)
                    {
                        x.Dialect<SQLiteDialect>();
                        x.Driver<SQLite20Driver>();
                        x.ConnectionProvider<DriverConnectionProvider>();
                    }
                    else
                        x.Dialect<MsSql2008Dialect>();
                    x.ConnectionString = _connectionString;
                    x.SchemaAction = SchemaAutoAction.Update;
                    x.IsolationLevel = IsolationLevel.ReadCommitted;

                    x.HqlToSqlSubstitutions = "True 1, False 0, true 1, false 0, yes 'Y', no 'N'";
                    x.BatchSize = 200;
                });

            var mappingAssemblies = _assemblies;
            foreach (var mappingAssembly in mappingAssemblies.Where(mappingAssembly => !String.IsNullOrWhiteSpace(mappingAssembly)))
            {
                _configuration.AddAssembly(mappingAssembly);
            }
            _configuration.BuildMappings();
            _configuration.SetProperty(NHEnvironment.CacheDefaultExpiration, 120.ToString());
            _configuration.SetProperty(NHEnvironment.ShowSql, "false");
            _configuration.Proxy(cfg => cfg.ProxyFactoryFactory<DefaultProxyFactoryFactory>());
            _configuration.SessionFactory()
                          .GenerateStatistics();
        }
Example #13
0
        /// <summary>
        /// Configure NHibernate
        /// </summary>
        private void ConfigureNHibernate()
        {
            _configuration = new NHConfiguration();
            _configuration.DataBaseIntegration(x =>
                    {
                        //x.AutoCommentSql = true;
                        //x.Dialect<MsSqlCustomDialect>();
                        x.Dialect<MsSqlCustomDialect>();
                        x.ConnectionString = _connectionString;
                        x.SchemaAction = SchemaAutoAction.Update;
                        x.IsolationLevel = IsolationLevel.ReadCommitted;

                        x.HqlToSqlSubstitutions = "True 1, False 0, true 1, false 0, yes 'Y', no 'N'";
                        x.BatchSize = 15;
                    });

            var mappingAssemblies = _assemblies;
            foreach (var mappingAssembly in mappingAssemblies)
            {
                if (!String.IsNullOrWhiteSpace(mappingAssembly))
                {
                    _configuration.AddAssembly(mappingAssembly);
                }
            }

            _configuration.BuildMappings();
            _configuration.Cache(cfg =>
                                     {
                                         cfg.DefaultExpiration = 120;
                                         cfg.Provider<SysCacheProvider>();
                                         cfg.UseMinimalPuts = true;
                                         cfg.RegionsPrefix = "xyz";
                                         cfg.UseQueryCache = true;
                                     });
            _configuration.SetProperty(NHibernate.Cfg.Environment.CacheDefaultExpiration, 120.ToString());
            _configuration.SetProperty(NHibernate.Cfg.Environment.ShowSql, "false");
            _configuration.Proxy(cfg => cfg.ProxyFactoryFactory<DefaultProxyFactoryFactory>());
            _configuration.SessionFactory()
                          .GenerateStatistics();

            new AuditingEventListener().Register(_configuration);
        }