Пример #1
0
        private void BuildSessionFactoryFor(string configurationFilePath)
        {
            var             nHibernateMappingAssembly = GetAssemblyName(configurationFilePath);
            ISessionFactory sessionFactory;

            if (nHibernateMappingAssembly != null)
            {
                var assembly = Assembly.Load(nHibernateMappingAssembly);
                var cfg      = new global::NHibernate.Cfg.Configuration();
                cfg.Configure(configurationFilePath);
                sessionFactory =
                    Fluently.Configure(cfg).Mappings(m =>
                {
                    m.FluentMappings.AddFromAssembly(assembly).Conventions.AddAssembly(assembly);
                }).BuildSessionFactory();
            }
            else
            {
                var cfg = new global::NHibernate.Cfg.Configuration();
                cfg.Configure(configurationFilePath);
                sessionFactory = Fluently.Configure(cfg).BuildSessionFactory();

                Fluently.Configure(cfg);
            }
            _sessionFactory = sessionFactory;

            Console.WriteLine("NHibernate Initiated");
        }
Пример #2
0
        /// <summary>
        /// Builds the session factory with the given properties. Database is updated if updateSchema is set
        /// </summary>
        public ISessionFactory Build(Configuration nhibernateConfiguration)
        {
            var scannedAssemblies = typesToScan.Select(t => t.Assembly).Distinct();

            foreach (var assembly in scannedAssemblies)
            {
                nhibernateConfiguration.AddAssembly(assembly);
            }

            var modelMapper =
                new SagaModelMapper(typesToScan.Except(nhibernateConfiguration.ClassMappings.Select(x => x.MappedClass)));

            nhibernateConfiguration.AddMapping(modelMapper.Compile());

            try
            {
                return(nhibernateConfiguration.BuildSessionFactory());
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    throw new ConfigurationErrorsException(e.InnerException.Message, e);
                }

                throw;
            }
        }
Пример #3
0
        private static void BuildSchema(global::NHibernate.Cfg.Configuration config)
        {
            var schemaExport = new SchemaExport(config);

            schemaExport.Drop(false, true);
            schemaExport.Create(false, true);
        }
#pragma warning disable 1591
        public void AddMappings(ref global::NHibernate.Cfg.Configuration config)
        {
            LoadAssemblies();
            foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                // при любом обращении к динамической сборке появляется Exception
                try {
                    var tmp = asm.Location;
                } catch (Exception) {
                    continue;
                }
                if (IsSearchMappingsInAssembly(asm))
                {
                    config.AddAssembly(asm);
                    if (this.logger?.IsEnabled(LogLevel.Information) == true)
                    {
                        this.logger.LogInformation("Mappings added from assembly: " + asm.FullName);
                    }
                }
                else
                {
                    if (this.logger?.IsEnabled(LogLevel.Debug) == true)
                    {
                        this.logger.LogDebug("Skip finding mappings from assembly: " + asm.FullName);
                    }
                }
            }
        }
Пример #5
0
        private static ISessionFactory CreateSessionFactory()
        {
            /*
            Configuration _cfg  = null;

             var factory = Fluently.Configure()
                .Database(
                    SQLiteConfiguration.Standard.InMemory()
                    // .UsingFile(@"C:\Users\thiago.alves\Desktop\firstProject.db")
                )
                .ProxyFactoryFactory(typeof(ProxyFactoryFactory))
                .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Cliente>()))
                .ExposeConfiguration(Cfg => _cfg = Cfg)
                .BuildSessionFactory();*/
                        var cfg = new global::NHibernate.Cfg.Configuration();
            cfg.Configure();

            return Fluently.Configure(cfg)
                .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Cliente>())

                )
                .ProxyFactoryFactory(typeof(ProxyFactoryFactory).AssemblyQualifiedName)
                .BuildSessionFactory();

            //return cfg.BuildSessionFactory();
        }
        /// <summary>
        /// Builds the session factory with the given properties. Database is updated if updateSchema is set
        /// </summary>
        public ISessionFactory Build(Configuration nhibernateConfiguration)
        {
            var scannedAssemblies = typesToScan.Select(t => t.Assembly).Distinct();

            foreach (var assembly in scannedAssemblies)
            {
                nhibernateConfiguration.AddAssembly(assembly);
            }

            var modelMapper =
                new SagaModelMapper(typesToScan.Except(nhibernateConfiguration.ClassMappings.Select(x => x.MappedClass)));

            nhibernateConfiguration.AddMapping(modelMapper.Compile());

            try
            {
                return nhibernateConfiguration.BuildSessionFactory();
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                    throw new ConfigurationErrorsException(e.InnerException.Message, e);

                throw;
            }
        }
Пример #7
0
 public void Process(string sessionAlias, global::NHibernate.Cfg.Configuration configuration)
 {
     foreach (IConfigurationProcessor item in items)
     {
         item.Process(sessionAlias, configuration);
     }
 }
Пример #8
0
        public void FixtureSetup()
        {
            var provider = new NHibernateProvider();

            _config = provider.CreateConfiguration();

            _sessionFactory = provider.CreateSessionFactory(_config);

            _session = _sessionFactory.OpenSession();

            provider.ExportSchema(_config, _session.Connection);

            using (var trans = _session.BeginTransaction())
            {
                var modelCreator = new NHibernateQueryingModel();
                modelCreator.CreateModel(_session);
                trans.Commit();
            }

            _query = new QueryAdapter(_session);

            QueryableExtensions.EagerFetchingProvider = new EagerFetchingProvider();
            QueryableExtensions.LazyQueryingProvider  = new LazyResultProvider();
            QueryableExtensions.AsyncQueryingProvider = new AsyncQueryProvider();
        }
        public void Setup()
        {
            var mapper = new ModelMapper();
            mapper.AddMapping<OutboxEntityMap>();

            var configuration = new global::NHibernate.Cfg.Configuration()
                .AddProperties(new Dictionary<string, string>
                {
                    { "dialect", dialect },
                    { global::NHibernate.Cfg.Environment.ConnectionString,connectionString }
                });

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            new SchemaUpdate(configuration).Execute(false, true);

            SessionFactory = configuration.BuildSessionFactory();

            Session = SessionFactory.OpenSession();

            persister = new OutboxPersister
            {
                StorageSessionProvider = new FakeSessionProvider(SessionFactory, Session),
                EndpointName = "TestEndpoint"
            };

        }
Пример #10
0
        private void InsertInitialData(global::NHibernate.Cfg.Configuration configuration)
        {
            ISession session = configuration.BuildSessionFactory().OpenSession();

            session.Save(LogBuilder.Default.Build());
            session.Flush();
        }
        private static NhibConfigData GetOrCreateConfigData(String configFileName)
        {
            NhibConfigData retvalue = factories.SafeGet(configFileName);

            if (null == retvalue)
            {
                //This is the first time we ask for this configuration
                global::NHibernate.Cfg.Configuration config = new global::NHibernate.Cfg.Configuration();
                XDocument doc = XDocument.Load(configFileName);
                XElement  connStringElement = (from e in doc.Descendants()
                                               where e.Attribute("name") != null && e.Attribute("name").Value == "connection.connection_string"
                                               select e).Single();
                String cnName = connStringElement.Value;
                connStringElement.Value = ConfigurationRegistry.ConnectionString(connStringElement.Value).ConnectionString;
                using (XmlReader reader = doc.CreateReader())
                {
                    config.Configure(reader);
                }
                ISessionFactory factory = config.BuildSessionFactory();
                retvalue = new NhibConfigData()
                {
                    Configuration = config, SessionFactory = factory, ConnectionName = cnName
                };
                factories.Add(configFileName, retvalue);
            }
            return(retvalue);
        }
Пример #12
0
        public void SetUp()
        {
            connectionString = String.Format(@"Data Source={0};New=True;", Path.GetTempFileName());


            var configuration = new global::NHibernate.Cfg.Configuration()
                                .AddProperties(new Dictionary <string, string>
            {
                { "dialect", dialect },
                { global::NHibernate.Cfg.Environment.ConnectionString, connectionString }
            });

            var modelMapper = new SagaModelMapper(new[] { typeof(T) });

            configuration.AddMapping(modelMapper.Compile());

            SessionFactory = configuration.BuildSessionFactory();

            new SchemaUpdate(configuration).Execute(false, true);

            session = SessionFactory.OpenSession();

            SagaPersister = new SagaPersister(new FakeSessionProvider(SessionFactory, session));

            new Installer().Install(WindowsIdentity.GetCurrent().Name, null);
        }
        public Configuration GetConfiguration()
        {
            if (this.configuration != null)
            {
                return(this.configuration);
            }

            var mappingAssemblies    = GetMappingAssemblies();
            var autoPersistenceModel = GenerateAutoPersistenceModel(mappingAssemblies);

            var builder = new NHibernateSessionFactoryBuilder()
                          .AddMappingAssemblies(mappingAssemblies)
                          .UseAutoPersistenceModel(autoPersistenceModel);

            var defaultConfigFilePath = Path.Combine(basePath, NHibernateSessionFactoryBuilder.DefaultNHibernateConfigFileName);

            if (File.Exists(defaultConfigFilePath))
            {
                Debug.WriteLine(
                    $"Found default configuration file {NHibernateSessionFactoryBuilder.DefaultNHibernateConfigFileName} in output folder. Loading configuration from '{defaultConfigFilePath}'.");
                builder.UseConfigFile(defaultConfigFilePath);
            }

            configuration = builder.BuildConfiguration();
            return(configuration);
        }
Пример #14
0
 public void Initialize(IContainer container)
 {
     var typeDiscoverer = container.Get<ITypeDiscoverer>();
     FluentConfiguration.Mappings(m => DiscoverClassMapsAndAddAssemblies(typeDiscoverer, m));
     Configuration = FluentConfiguration.BuildConfiguration();
     SessionFactory = Configuration.BuildSessionFactory();
 }
        public void Setup()
        {
            var configuration = new global::NHibernate.Cfg.Configuration()
                                .AddProperties(new Dictionary <string, string>
            {
                { "dialect", dialect },
                { global::NHibernate.Cfg.Environment.ConnectionString, connectionString }
            });
            var mapper = new ModelMapper();

            mapper.AddMapping <TimeoutEntityMap>();

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            new SchemaExport(configuration).Create(false, true);

            sessionFactory = configuration.BuildSessionFactory();

            persister = new TimeoutPersister
            {
                SessionFactory       = sessionFactory,
                DbConnectionProvider = new FakeDbConnectionProvider(sessionFactory.GetConnection()),
                EndpointName         = "MyTestEndpoint"
            };
        }
Пример #16
0
        public void Setup()
        {
            var mapper = new ModelMapper();

            mapper.AddMapping <OutboxEntityMap>();

            var configuration = new global::NHibernate.Cfg.Configuration()
                                .AddProperties(new Dictionary <string, string>
            {
                { "dialect", dialect },
                { global::NHibernate.Cfg.Environment.ConnectionString, connectionString }
            });

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            new SchemaUpdate(configuration).Execute(false, true);

            SessionFactory = configuration.BuildSessionFactory();

            Session = SessionFactory.OpenSession();

            persister = new OutboxPersister
            {
                StorageSessionProvider = new FakeSessionProvider(SessionFactory, Session),
                EndpointName           = "TestEndpoint"
            };
        }
Пример #17
0
        public void SetUp()
        {
            ConnectionString = $@"Data Source={Path.GetTempFileName()};New=True;";

            var configuration = new global::NHibernate.Cfg.Configuration()
                                .AddProperties(new Dictionary <string, string>
            {
                { "dialect", dialect },
                { global::NHibernate.Cfg.Environment.ConnectionString, ConnectionString }
            });

            var metaModel = new SagaMetadataCollection();

            metaModel.Initialize(new[] { typeof(T) });
            var metadata = metaModel.Find(typeof(T));

            var modelMapper = new SagaModelMapper(metaModel, new[] { metadata.SagaEntityType });

            configuration.AddMapping(modelMapper.Compile());

            SessionFactory = configuration.BuildSessionFactory();

            new SchemaUpdate(configuration).Execute(false, true);

            SagaPersister = new SagaPersister();
        }
Пример #18
0
        /// <summary>
        /// Only development phase usage do not use production code
        /// </summary>
        /// <param name="factoryKey"></param>
        private void BuildSchemaByDroping(string factoryKey)
        {
            var filePath = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, factoryKey + ".NHibernate.config")?.FirstOrDefault();

            if (string.IsNullOrEmpty(filePath))
            {
                Console.WriteLine(factoryKey + ".NHibernate.config file not found for BuildSchemaDroping!");
                return;
            }
            var nHibernateMappingAssembly = GetAssemblyName(filePath);

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

            cfg.Configure(filePath);
            FluentConfiguration a = Fluently.Configure(cfg).Mappings(m =>
            {
                var assembly = Assembly.Load(nHibernateMappingAssembly);
                m.HbmMappings.AddFromAssembly(assembly);
                m.FluentMappings.AddFromAssembly(assembly).Conventions.AddAssembly(assembly);
            });

            SchemaExport schema = new SchemaExport(a.BuildConfiguration());

            if (schema != null)
            {
                schema.Execute(true, true, false);
            }
        }
Пример #19
0
        public ISessionFactory GetSessionFactory()
        {
            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
            var path = "";

            if (HttpContext.Current != null)
            {
                path = HttpContext.Current.Server.MapPath("/Config/hibernate.cfg.xml");
            }
            else
            {
                path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"\Config\",
                                    "hibernate.cfg.xml");
            }

            var config = new global::NHibernate.Cfg.Configuration().Configure(path);
            var t      = Fluently.Configure(config);

            try
            {
                var mapAssembly    = Assembly.Load("Project.Domain.Core.Nhibernate");
                var sessionFactory = Fluently.Configure(config)
                                     .Mappings(m => m.FluentMappings.AddFromAssembly(mapAssembly)
                                               //.ExportTo(@"E:\XmlMappings2")
                                               ).BuildSessionFactory();

                return(sessionFactory);
            }
            catch (System.Exception e)
            {
                throw e;
            }
        }
Пример #20
0
        private static void BuildSchema(global::NHibernate.Cfg.Configuration config)
        {
            config.SetProperty(global::NHibernate.Cfg.Environment.CurrentSessionContextClass, "web");

            // this NHibernate tool takes a configuration (with mapping info in)
            // and exports a database schema from it
            new SchemaExport(config).Create(false, true);
        }
Пример #21
0
        public ConfigurationResult(ISessionFactory sessionFactory, global::NHibernate.Cfg.Configuration configuration)
        {
            Requires.NotNull(sessionFactory, "sessionFactory");
            Requires.NotNull(configuration, "configuration");

            SessionFactory = sessionFactory;
            Configuration  = configuration;
        }
Пример #22
0
 public static void UpdateSchema(global::NHibernate.Cfg.Configuration configuration)
 {
     using (new WriteLockDisposable(SchemaValidationLocker))
     {
         var schema = new SchemaUpdate(configuration);
         schema.Execute(false, true);
     }
 }
Пример #23
0
 public void Configure(Configuration configuration)
 {
     configuration.SetProperty(DriverKey, this.driverType.AssemblyQualifiedName);
     configuration.SetProperty(DialectKey, this.dialectType.AssemblyQualifiedName);
     configuration.SetProperty(ConnectionStringKey, this.connectionString);
     configuration.SetProperty(DefaultSchemaKey, "dbo");
     configuration.SetProperty(UseReflectionOptimizerKey, "true");
 }
Пример #24
0
        public void Initialize(IContainer container)
        {
            var typeDiscoverer = container.Get <ITypeDiscoverer>();

            FluentConfiguration.Mappings(m => DiscoverClassMapsAndAddAssemblies(typeDiscoverer, m));
            Configuration  = FluentConfiguration.BuildConfiguration();
            SessionFactory = Configuration.BuildSessionFactory();
        }
Пример #25
0
        public void Process(string sessionAlias, global::NHibernate.Cfg.Configuration configuration)
        {
            if (sessionAlias != this.sessionAlias)
            {
                return;
            }

            Process(configuration);
        }
Пример #26
0
        /// <summary>
        /// Configures NHibernate
        /// </summary>
        public void Configure()
        {
            // Arashi.Core.NHibernate

             configuration = new Configuration();
             configuration.Configure();
             configuration = configuration.AddAssembly("Arashi.Core.NHibernate");

             SessionFactory = configuration.BuildSessionFactory();
        }
Пример #27
0
 public CustomAutoPersistenceModel(
     Container container,
     IAutomappingConfiguration cfg,
     IEventPublisher eventPublisher,
     global::NHibernate.Cfg.Configuration configuration) : base(cfg)
 {
     _container      = container;
     _eventPublisher = eventPublisher;
     _configuration  = configuration;
 }
#pragma warning disable 1591
        public global::NHibernate.Cfg.Configuration GetConfiguration()
        {
            if (null == _config)
            {
                _config = new global::NHibernate.Cfg.Configuration();
                Reconfigure(ref _config);
            }

            return(_config);
        }
Пример #29
0
 public static void UpdateSchema(global::NHibernate.Cfg.Configuration configuration)
 {
     using (new WriteLockDisposable(SchemaValidationLocker))
     {
         using (DisposableTimer.TraceDuration <ProviderBootstrapper>("Begin db schema update", "End db schema update"))
         {
             var schema = new SchemaUpdate(configuration);
             schema.Execute(x => LogHelper.TraceIfEnabled <ProviderBootstrapper>("NHibernate generated the following update Sql: \n" + x), true);
         }
     }
 }
Пример #30
0
        public bool ValidateSchema(global::NHibernate.Cfg.Configuration configuration)
        {
            using (new WriteLockDisposable(SchemaValidationLocker))
            {
                var myvalidator = new SchemaValidator(configuration);
                try
                {
                    myvalidator.Validate();
                    return(true);
                }
                catch (HibernateException ex)
                {
                    /* SchemaValidator.Validate() returns void - FFS */
                    LogHelper.Error <ProviderBootstrapper>("While running SchemaValidator: " + ex.Message, ex);

                    // New in 5.2 (limited support for schema upgrades - pending full migration support)
                    // Use our own validator to actually get back metadata about the missing tables rather than
                    // just an exception of the first failure
                    // Then if it's something we're OK to try to handle, try to handle it...
                    if (_localConfig.AutoUpdateDbSchema)
                    {
                        var customValidator = new SchemaChangeValidator(configuration);
                        var result          = customValidator.Validate();
                        if (!result.IsValid)
                        {
                            // 5.2: Just check for whether AggregateNodeStatus is the only missing one
                            if (result.MissingTables.Any())
                            {
                                var missingTables = string.Join(", ", result.MissingTables.Select(x => x.Name));
                                LogHelper.Warn <ProviderBootstrapper>("The following tables are missing from the database: {0}", missingTables);

                                var agg = result.MissingTables.FirstOrDefault(x => x.Name == typeof(AggregateNodeStatus).Name);
                                if (agg != null && result.MissingTables.Count == 1)
                                {
                                    // It's the only missing table, so we've already done one install
                                    LogHelper.Warn <ProviderBootstrapper>("Automatically attempting to update the database schema to add the following missing tables: {0}. You can prevent this behaviour by setting '{1}' to false in the configuration for this provider", missingTables, ProviderConfigurationSection.XAutoUpdateSchema);
                                    try
                                    {
                                        UpdateSchema(configuration);
                                        // Everything went OK, so can return true since we're now "valid"
                                        return(true);
                                    }
                                    catch (Exception updateEx)
                                    {
                                        LogHelper.Error <ProviderBootstrapper>("Auto-update of db schema failed. Does the db user have the correct permissions? If you need to manually run the update script, the script should be in the logfile preceding this entry", updateEx);
                                    }
                                }
                            }
                        }
                    }
                    return(false);
                }
            }
        }
Пример #31
0
#pragma warning disable 1591

        public void AddMappings(ref global::NHibernate.Cfg.Configuration config)
        {
            foreach (var dir in _searchPath)
            {
                config.AddDirectory(dir);
                if (this.logger?.IsEnabled(LogLevel.Information) == true)
                {
                    this.logger.LogInformation("Mappings added from directory: " + dir.FullName);
                }
            }
        }
            public MyEndpoint()
            {
                EndpointSetup <DefaultServer>(c =>
                {
                    var cfg = new NHibernate.Cfg.Configuration();
                    cfg.SetProperty(NHibernate.Cfg.Environment.Dialect, typeof(NHibernate.Dialect.MsSql2012Dialect).FullName);
                    cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, typeof(NHibernate.Driver.Sql2008ClientDriver).FullName);
                    cfg.SetProperty(NHibernate.Cfg.Environment.ConnectionString, @"Server=localhost\sqlexpress;Database=nservicebus;Trusted_Connection=True;");

                    c.UsePersistence <NHibernatePersistence>().UseConfiguration(cfg);
                });
            }
        public void ApplyBeforeExecutingQuery(global::NHibernate.Cfg.Configuration config, IDbConnection connection, IDbCommand dbCommand)
        {
            var tableMatch = Regex.Match(dbCommand.CommandText, @"create\s+table\s+([\[\]\w_]+)");

            if (!tableMatch.Success)
            {
                return;
            }
            var tableName = tableMatch.Groups[1].Value.TrimStart('[').TrimEnd(']');
            var matches   = Regex.Matches(dbCommand.CommandText,
                                          @"(([\[\]\w_]+)\s+([\w\(\)]+)\s+(not null|null) unique)|(unique\s+\(([^\)]+))\)");

            if (matches.Count == 0)
            {
                return;
            }
            var script = new StringBuilder();

            script.AppendLine();
            foreach (var match in matches.Cast <Match>().Where(match => match.Success))
            {
                string uniqueKeySql;
                if (string.IsNullOrEmpty(match.Groups[2].Value)) //named unique key
                {
                    var columns = match.Groups[6].Value.Split(',').Select(o => o.Trim()).ToList();
                    uniqueKeySql =
                        $"CONSTRAINT {GetUniqueKeyName(tableName, columns)} UNIQUE ({string.Join(", ", columns)})";
                    dbCommand.CommandText = dbCommand.CommandText.Replace(match.Groups[0].Value, uniqueKeySql);
                }
                else
                {
                    var column = match.Groups[2].Value;
                    uniqueKeySql          = match.Groups[0].Value.Replace("unique", "");
                    dbCommand.CommandText = dbCommand.CommandText.Replace(match.Groups[0].Value, uniqueKeySql);

                    if (match.Groups[4].Value == "null") //create filtered unique index
                    {
                        script.AppendFormat("CREATE UNIQUE NONCLUSTERED INDEX {0} ON {1}({2}) WHERE {2} IS NOT NULL",
                                            GetUniqueKeyName(tableName, column), tableName, column);
                        script.AppendLine();
                    }
                    else
                    {
                        dbCommand.CommandText  = dbCommand.CommandText.Remove(dbCommand.CommandText.LastIndexOf(')'), 1);
                        dbCommand.CommandText +=
                            $",CONSTRAINT {GetUniqueKeyName(tableName, column)} UNIQUE ({column}))";
                    }
                }
            }
            dbCommand.CommandText += script.ToString();
        }
Пример #34
0
        protected override void Process(global::NHibernate.Cfg.Configuration configuration)
        {
            SchemaUpdate schemaUpdate = new SchemaUpdate(configuration);
            bool         isUpdated    = false;

            schemaUpdate.Execute(script => { Console.WriteLine(script); isUpdated = true; }, true);

            if (!isUpdated)
            {
                return;
            }

            InsertInitialData(configuration);
        }
Пример #35
0
 public void AddDataBaseIntegrationInfo(global::NHibernate.Cfg.Configuration config)
 {
     config.DataBaseIntegration(db =>
     {
         db.ConnectionString = string.Format("Data Source={0};Version=3;New=True;", _dbPath);
         db.Driver <SQLite20Driver>();
         db.Dialect <SQLiteDialect>();
         db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
         // enabled for testing
         db.LogFormattedSql = true;
         db.LogSqlInConsole = true;
         db.AutoCommentSql  = true;
     });
 }
		/// <summary>
		/// Configures NHibernate.
		/// </summary>
		/// <returns>
		/// The NHibernate configuration.
		/// </returns>
		private global::NHibernate.Cfg.Configuration Configure()
		{
			var configuration = new global::NHibernate.Cfg.Configuration();

			configuration.DataBaseIntegration(
				db =>
					{
						db.Driver<SQLite20Driver>();
						db.ConnectionString = "Data Source=:memory:;Version=3;New=True;Pooling=True;Max Pool Size=1";
						db.Dialect<SQLiteDialect>();
						db.ConnectionReleaseMode = ConnectionReleaseMode.OnClose;
					});

			return configuration;
		}
		/// <summary>
		/// Builds a configured session factory.
		/// </summary>
		/// <returns>
		/// The configured session factory.
		/// </returns>
		public ISessionFactory Build()
		{
			if (this.sessionFactory != null)
			{
				return this.sessionFactory;
			}

			this.Configuration = this.Configure();
			var mapping = this.Map();
			this.Configuration.AddDeserializedMapping(mapping, MapDocumentName);
			
			this.sessionFactory = this.Configuration.BuildSessionFactory();

			new SchemaExport(this.Configuration).Create(false, true);

			return this.sessionFactory;
		}
Пример #38
0
        public static void Init(Action<global::NHibernate.Cfg.Configuration> exposedConfiguration = null)
        {
            lock (_syncRoot)
            {
                var automappingConfiguration = new XangoAutomapping();

                XangoConfiguration xangoConfig = XangoConfigurationHelper.Get();

                _configuration = Fluently.Configure()
                    .Database(xangoConfig.Database)
                    .ProxyFactoryFactory<ProxyFactoryFactory>()
                    .CurrentSessionContext(xangoConfig.IsWeb ? "web" : "thread_static")
                    .Mappings(mappings => mappings.AutoMappings.Add(AutoMap.Assembly(xangoConfig.DomainAssembly, automappingConfiguration)
                                                                        .UseOverridesFromAssembly(xangoConfig.OverrideMapAssembly ?? xangoConfig.DomainAssembly)
                                                                        .Conventions.Setup(conv =>
                                                                                               {
                                                                                                   conv.Add
                                                                                                       <
                                                                                                           CustomCollectionConvetion
                                                                                                           >();
                                                                                                   conv.Add<CascadeAll>();
                                                                                                   conv.Add
                                                                                                       <
                                                                                                           HiLoIndetityStrategy
                                                                                                           >();
                                                                                                   conv.Add
                                                                                                       <
                                                                                                           TableNamePluralizeConvention
                                                                                                           >();
                                                                                                   conv.Add
                                                                                                       <
                                                                                                           CustomForeignKeyConvention
                                                                                                           >();
                                                                                               })))
                    .ExposeConfiguration(Validation.NHFluentConfiguration.Initialize)
                    .ExposeConfiguration(exposedConfiguration)
                    .BuildConfiguration();

            #if DEBUG
                var schema = new SchemaUpdate(_configuration);
                schema.Execute(true, true);
            #endif

                _sessionFactory = _configuration.BuildSessionFactory();
            }
        }
Пример #39
0
    private static ISessionFactory CreateSessionFactory()
    {
      Logger.DebugFormat("DataDirectory: {0}", AppDomain.CurrentDomain.GetData("DataDirectory"));

      // delete the existing db on each run
      string dbname = ConfigurationManager.AppSettings["Database.Filename"];
      Logger.DebugFormat("Try delete: {0}", dbname);
      if (dbname != null && File.Exists(dbname))
        File.Delete(dbname);

      var cfg = new global::NHibernate.Cfg.Configuration();
      cfg.Configure();

      return Fluently.Configure(cfg)
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<ProjectMapping>())
        .ExposeConfiguration(BuildSchema)
        .BuildSessionFactory();
    }
Пример #40
0
 internal static ISessionFactory CreateConfigurationForConfigFileName(string configurationFile)
 {
     try
     {
         global::NHibernate.Cfg.Configuration cfg = new global::NHibernate.Cfg.Configuration();
         cfg.Configure(configurationFile);
         return cfg.BuildSessionFactory();
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine("NHibernate exception stack");
         String formatter = "--";
         do
         {
             System.Diagnostics.Debug.WriteLine(formatter + ex.Message);
             ex = ex.InnerException;
             formatter += "--";
         } while (ex != null);
         throw;
     }
 }
Пример #41
0
        public void GenerateSchemaAndData()
        {
            var cfg = new global::NHibernate.Cfg.Configuration().Configure();
            new SchemaExport(cfg)
                .SetDelimiter(";")
                .Execute(false, true, false);

            var random = new Random();
            Func<DateTime> before2000 = () => new DateTime(random.Next(1950, 2000), random.Next(1, 13), random.Next(1, 29));
            Func<DateTime> before2005 = () => new DateTime(random.Next(2000, 2005), random.Next(1, 13), random.Next(1, 29));

            //some user data
            var users = new[] {
                new User {Created = before2000(), Email = "*****@*****.**", Username = "******" },
                new User {Created = before2000(), Email = "*****@*****.**", Username = "******" },
                new User {Created = before2000(), Email = "*****@*****.**", Username = "******" },
                new User {Created = DateTime.Now, Email = "*****@*****.**", Username = "******" },
                new User {Created = before2000(), Email = "*****@*****.**", Username = "******" },
                new User {Created = before2000(), Email = "*****@*****.**", Username = "******" },
                new User {Created = before2000(), Email = "*****@*****.**", Username = "******" },
                new User { Email = "*****@*****.**", Username = "******" },
                new User { Email = "*****@*****.**", Username = "******" },
                new User { Email = "*****@*****.**", Username = "******" },
                new User { Email = "*****@*****.**", Username = "******" },
                new User {Created = before2005(), Email = "*****@*****.**", Username = "******" },
                new User {Created = before2005(), Email = "*****@*****.**", Username = "******" },
                new User {Created = before2005(), Email = "*****@*****.**", Username = "******" },
                new User { Email = "*****@*****.**", Username = "******" },
            };

            using (var sessionFactory = cfg.BuildSessionFactory()) {
                using (var session = sessionFactory.OpenSession()) {
                    using (var tx = session.BeginTransaction()) {
                        var repo = new NHibernateRepository<User>(session);
                        users.Walk(user => repo.Save(user));
                        tx.Commit();
                    }
                }
            }
        }
Пример #42
0
        private global::NHibernate.Cfg.Configuration CreateConfiguration()
        {
            var configuration = new global::NHibernate.Cfg.Configuration()
                .CurrentSessionContext<LazySessionContext>();

            configuration.DataBaseIntegration(db =>
            {
                db.ConnectionProvider<DriverConnectionProvider>();
                db.Dialect<MsSql2005Dialect>();
                db.Driver<SqlClientDriver>();
                db.ConnectionStringName = "default";
                db.BatchSize = 30;
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                db.Timeout = 10;
                db.LogFormattedSql = true;
                db.LogSqlInConsole = false;
                db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'";
            });

            configuration.AddDeserializedMapping(EntitiesMapper.CreateMappingConfiguration(), "Cronos"); ;

            return configuration;
        }
        public void Setup()
        {
            var configuration = new global::NHibernate.Cfg.Configuration()
              .AddProperties(new Dictionary<string, string>
                {
                    { "dialect", dialect },
                    { global::NHibernate.Cfg.Environment.ConnectionString, connectionString }
                });
            var mapper = new ModelMapper();
            mapper.AddMapping<TimeoutEntityMap>();

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            new SchemaExport(configuration).Create(false, true);

            sessionFactory = configuration.BuildSessionFactory();

            persister = new TimeoutPersister
            {
                SessionFactory = sessionFactory,
                DbConnectionProvider = new FakeDbConnectionProvider(sessionFactory.GetConnection()),
                EndpointName = "MyTestEndpoint"
            };
        }
Пример #44
0
        private ISessionFactory BuildSessionFactory(IDomainModuleGroup group)
        {
            #if DEBUG
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            #endif

            global::NHibernate.Cfg.Configuration config;
            ISessionFactory sessionFactory;

            if (WarmStartCacheManager.IsUse)
            {
                WarmStartCacheManager.Reset();
                WarmStartCacheManager.SetIdentifier(group.Name);

                var dependentAssemblies = group.Modules
                    .SelectMany(g => g.AssemblyDependencies)
                    .Union(new [] { GetType().Assembly, typeof(IDomainModule).Assembly } )
                    .Distinct();

                WarmStartCacheManager.SetDependentAssemblies(dependentAssemblies);
            }

            if (WarmStartCacheManager.IsUse && WarmStartCacheManager.IsAbleToWarmStart)
            {
                Log.Debug(this, "Warm start method used.");

                config = WarmStartCacheManager.GetConfigFromCache();
                sessionFactory = config.BuildSessionFactory();
            }
            else
            {
                config = new global::NHibernate.Cfg.Configuration();
                sessionFactory = BuildSessionFactory(config, group);
            }

            Configurations.Add(sessionFactory, config);

            if (WarmStartCacheManager.IsUse && !WarmStartCacheManager.IsAbleToWarmStart)
            {
                Log.Debug(this, "Config cached for warm start use.");

                WarmStartCacheManager.CacheConfig(config);
            }

            #if DEBUG
            stopwatch.Stop();
            Log.Debug(this, string.Format("`{0}` session took {1:c}` seconds to build.", group.Name, stopwatch.Elapsed));
            #endif

            return sessionFactory;
        }
Пример #45
0
 public BasicSharedEngineProvider(ValidatorEngine ve, global::NHibernate.Cfg.Configuration configuration)
 {
     _ve = ve;
     _configuration = configuration;
 }
 private static NhibConfigData GetOrCreateConfigData(String configFileName)
 {
     NhibConfigData retvalue = factories.SafeGet(configFileName);
     if (null == retvalue)
     {
         //This is the first time we ask for this configuration
         global::NHibernate.Cfg.Configuration config = new global::NHibernate.Cfg.Configuration();
         XDocument doc = XDocument.Load(configFileName);
         XElement connStringElement = (from e in doc.Descendants()
                                                 where e.Attribute("name") != null && e.Attribute("name").Value == "connection.connection_string"
                                                 select e).Single();
         String cnName = connStringElement.Value;
         connStringElement.Value = ConfigurationRegistry.ConnectionString(connStringElement.Value).ConnectionString;
         using (XmlReader reader = doc.CreateReader())
         {
             config.Configure(reader);
         }
         ISessionFactory factory = config.BuildSessionFactory();
         retvalue = new NhibConfigData() { Configuration = config, SessionFactory = factory, ConnectionName = cnName };
         factories.Add(configFileName, retvalue);
     }
     return retvalue;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ProviderBootstrapper"/> class if sufficient configuration information has been supplied by the user.
 /// </summary>        
 /// <param name="configuration">The configuration.</param>
 /// <param name="localConfig">The existing config.</param>
 /// <remarks></remarks>
 public ProviderBootstrapper(global::NHibernate.Cfg.Configuration configuration, ProviderConfigurationSection localConfig)
 {
     _localConfig = localConfig;
     _configuration = configuration;
 }
		public void Configure()
		{
			Configuration = FluentConfiguration.BuildConfiguration();
			SessionFactory = Configuration.BuildSessionFactory();
		}
Пример #49
0
        private ISessionFactory GenerateNHibernateSessionFactory()
        {
            var sw = Stopwatch.StartNew();

            ForceLoadObjectModel(); // This is needed for "new Configuration()".
            var configuration = new global::NHibernate.Cfg.Configuration();
            configuration.SetProperty("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
            configuration.SetProperty("connection.connection_string", _connectionString);

            // Set factory-level property:
            configuration.SetProperty("command_timeout", SqlUtility.SqlCommandTimeout.ToString());
            // Set system-level property:
            // Note: Using NHibernate.Cfg.Environment.Properties does not allow setting properties becase the public property returns a copy of the dictionary.
            var globalPropertiesField = typeof(global::NHibernate.Cfg.Environment).GetField("GlobalProperties", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
            var globalProperties = (Dictionary<string, string>)globalPropertiesField.GetValue(null);
            globalProperties.Add("command_timeout", SqlUtility.SqlCommandTimeout.ToString());

            if (SqlUtility.DatabaseLanguage == "MsSql")
            {
                configuration.SetProperty("dialect", "NHibernate.Dialect.MsSql2005Dialect");
                configuration.SetProperty("connection.driver_class", "NHibernate.Driver.SqlClientDriver");
            }
            else if (SqlUtility.DatabaseLanguage == "Oracle")
            {
                configuration.SetProperty("dialect", "NHibernate.Dialect.Oracle10gDialect");
                configuration.SetProperty("connection.driver_class", "NHibernate.Driver.OracleDataClientDriver");
            }
            else
                throw new FrameworkException(DatabaseLanguageError);

            ResolveEventHandler resolveAssembly = (s, args) => _domainObjectModel.Assembly;
            try
            {
                AppDomain.CurrentDomain.AssemblyResolve += resolveAssembly;
                configuration.AddXmlString(_nHibernateMapping.GetMapping());
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= resolveAssembly;
            }

            foreach (var configurationExtension in _nHibernateConfigurationExtensions)
                configurationExtension.ExtendConfiguration(configuration);

            SchemaMetadataUpdater.QuoteTableAndColumns(configuration);
            var sessionFactory = configuration.BuildSessionFactory();

            _performanceLogger.Write(sw, "NHibernatePersistenceEngine.PrepareNHSessionFactory");
            return sessionFactory;
        }