public static void Initialize(TestContext context)
        {
            var cfg = new Configuration();
            cfg.DataBaseIntegration(x => {
                x.ConnectionString = "Server=localhost;Database=test;Uid=root;Pwd=kmn23po;";
                x.Driver<MySqlDataDriver>();
                x.Dialect<MySQLDialect>();
                x.LogSqlInConsole = true;
                x.BatchSize = 30;
            });

            var mapper = new ModelMapper();
            mapper.AddMapping<ParentMap>();
            mapper.AddMapping<ParentWithGuidMap>();
            mapper.AddMapping<ChildMap>();

            cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            sessionFactory = cfg.BuildSessionFactory();

            var schemaUpdate = new SchemaUpdate(cfg);
            schemaUpdate.Execute(false, true);

            InsertData();
        }
Example #2
0
        public void TestEvent()
        {
            var config = new NHibernate.Cfg.Configuration();

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

            config.EventListeners.SaveEventListeners = new ISaveOrUpdateEventListener[]
            {
                new TestSaveOrUpdateEventListener()
            };

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

            var factory = config.BuildSessionFactory();

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

            using (var session = factory.OpenSession())
            {
                var message = session.Get <Message>(1);
                Assert.IsNotNull(message.Creator);
                Assert.AreEqual(message.LastEditor, "Leoli_SaveOrUpdate_Event");
            }
        }
Example #3
0
        static void Main(string[] args)
        {
            var configuration = new Configuration();
            configuration.DataBaseIntegration(x =>
            {
                x.ConnectionString = "Server=localhost;Database=NHibernateSpike;Integerated Security=SSPI;";
                x.Driver<SqlClientDriver>();
                x.Dialect<MsSql2012Dialect>();
                x.LogSqlInConsole = true;
            });

            configuration.AddAssembly(Assembly.GetExecutingAssembly());

            var sessionFactory = configuration.BuildSessionFactory();

            using (var session = sessionFactory.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    var customers = session.QueryOver<Customer>().Where(x => x.FirstName == "Oleg");
                    transaction.Commit();

                }

            }
        }
Example #4
0
        public void TestEvent2()
        {
            var config = new NHibernate.Cfg.Configuration();

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

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

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

            var factory = config.BuildSessionFactory();

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

            using (var session = factory.OpenSession())
            {
                var message = session.Get <Message>(1);
                message.Content = "Message_Leoli2";
                session.Save(message);
                session.Flush();
                Assert.AreEqual(message.LastEditor, "Leoli_Update_Event");
            }
        }
        public static ISessionFactory CreateSessionFactory(string connectionString)
        {
            lock (ThreadLock)
            {
                if (sessionFactory == null)
                {
                    var config = new Configuration();

                    config.DataBaseIntegration(
                        db =>
                        {
                            db.Dialect<MsSql2008Dialect>();
                            db.Driver<Sql2008ClientDriver>();
                            db.ConnectionString = connectionString;
                            db.IsolationLevel = IsolationLevel.ReadCommitted;
                            db.LogSqlInConsole = true;
                            db.LogFormattedSql = true;
                            db.AutoCommentSql = true;
                        }
                        );

                    var mapper = new ModelMapper();
                    mapper.WithMappings(config);

                    sessionFactory = config.BuildSessionFactory();
                }

                return sessionFactory;
            }
        }
Example #6
0
        static SessionFactory()
        {
            var connectionString = @"Data Source=.\sqlexpress2014;Initial Catalog=BlogDatabase;Integrated Security=True";

            var configuration = new Configuration();
            configuration.DataBaseIntegration(
                x =>
                {
                    x.ConnectionString = connectionString;
                    x.Driver<SqlClientDriver>();
                    x.Dialect<MsSql2012Dialect>();
                });
            configuration.SetProperty(Environment.UseQueryCache, "true");
            configuration.SetProperty(Environment.UseSecondLevelCache, "true");
            configuration.SetProperty(Environment.CacheProvider, typeof(SysCacheProvider).AssemblyQualifiedName);
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            mapper.BeforeMapBag += (modelInspector, member1, propertyCustomizer) =>
            {
                propertyCustomizer.Inverse(true);
                propertyCustomizer.Cascade(Cascade.All | Cascade.DeleteOrphans);
            };
            mapper.BeforeMapManyToOne +=
                (modelInspector, member1, propertyCustomizer) => { propertyCustomizer.NotNullable(true); };
            mapper.BeforeMapProperty += (inspector, member, customizer) => customizer.NotNullable(true);
            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            configuration.AddMapping(mapping);
            sessionFactory = configuration.BuildSessionFactory();
        }
        private ISessionFactory BuildSessionFactory()
        {
            var mapper = new ModelMapper();
            var configuration = new Configuration();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            configuration.DataBaseIntegration(c =>
            {
                c.ConnectionString = _connectionString;
                c.IsolationLevel = IsolationLevel.ReadCommitted;
                c.Driver<Sql2008ClientDriver>();
                c.Dialect<MsSql2008Dialect>();
                c.BatchSize = 50;
                c.Timeout = 30;

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

            #if DEBUG
            configuration.SessionFactory().GenerateStatistics();
            #endif

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            var sessionFactory = configuration.BuildSessionFactory();

            return sessionFactory;
        }
Example #8
0
        public void TestEvent()
        {
            var config = new NHibernate.Cfg.Configuration();
            config.Configure();
            config.DataBaseIntegration(db =>
            {
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

            config.EventListeners.SaveEventListeners = new ISaveOrUpdateEventListener[] 
            { 
                new TestSaveOrUpdateEventListener()
            };

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

            var factory = config.BuildSessionFactory();

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

            using (var session = factory.OpenSession())
            {
                var message = session.Get<Message>(1);
                Assert.IsNotNull(message.Creator);
                Assert.AreEqual(message.LastEditor, "Leoli_SaveOrUpdate_Event");
            }
        }
Example #9
0
        public static ISession OpenSession()
        {
            if (sessionFactory == null)
            {
                System.Collections.Specialized.NameValueCollection sets = System.Configuration.ConfigurationManager.AppSettings;

                //获取连接字符串
                string server = Utilities.GetConfigValue("server");
                string pwd = VTMS.Common.Utilities.Base64Dencrypt(Utilities.GetConfigValue("DBPassword"));
                string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
                connectionString = string.Format(connectionString, server, pwd);

                try
                {
                    Configuration cfg = new Configuration().Configure();
                    cfg.Proxy(p => p.ProxyFactoryFactory<NHibernate.Bytecode.DefaultProxyFactoryFactory>());
                    cfg.DataBaseIntegration(db =>
                    {
                        db.ConnectionString = connectionString;
                    });

                    sessionFactory = cfg.BuildSessionFactory();
                }
                catch (Exception e)
                {
                    VTMS.Common.MessageUtil.ShowError("无法登陆服务器,请检查服务器IP设置是否正确,错误信息为:" + e.Message);
                }
            }
            return sessionFactory.OpenSession();
        }
		/// <summary>
		/// Configure NHibernate
		/// </summary>
		private static Configuration ConfigureNHibernate()
		{
			Configuration configure = new Configuration();
			configure.SessionFactoryName("SessionFactory");

			configure.DataBaseIntegration(db =>
				{
					db.Dialect<MsSql2008Dialect>();
					db.Driver<SqlClientDriver>();
					db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
					db.IsolationLevel = IsolationLevel.ReadCommitted;

					db.ConnectionStringName = RegtestingServerConfiguration.DefaultConnectionString;
					//db.Timeout = 10;

					//For testing
					//db.LogFormattedSql = true;
					//db.LogSqlInConsole = true;
					//db.AutoCommentSql = true;
				});

			HbmMapping hbmMapping = GetMappings();
			configure.AddDeserializedMapping(hbmMapping,"NHMapping");
			SchemaMetadataUpdater.QuoteTableAndColumns(configure);

			return configure;
		}
		protected override void Mapping(Configuration config)
		{
			var mapper = new ModelMapper();
			mapper.Class<Software>(map =>
			{
				map.Id(s => s.Id, o => o.Generator(Generators.GuidComb));
				map.Property(s => s.Name, o =>
				{
					o.NotNullable(true);
					o.Unique(true);
				});
			});

			mapper.Class<AssignedSoftware>(map =>
			{
				map.Id(s => s.Key, o => o.Generator(Generators.Assigned));
				map.Property(s => s.Name, o =>
				{
					o.NotNullable(true);
					o.Unique(true);
				});
			});

			var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
			config.AddMapping(mapping);
			config.DataBaseIntegration(db => db.LogSqlInConsole = true);
		}
        static Configuration ConfigureNHibernate()
        {
            var configure = new Configuration();
            configure.SessionFactoryName("HemArkivAccess");

            configure.DataBaseIntegration(db =>
            {
                db.Dialect<NHibernate.JetDriver.JetDialect>();
                db.Driver<NHibernate.JetDriver.JetDriver>();
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;

                db.ConnectionStringName = "HemArkivAccess";
                db.Timeout = 10;

                // enabled for testing
                db.LogFormattedSql = true;
                db.LogSqlInConsole = false;
                db.AutoCommentSql = false;
                db.Timeout = 10;
                //db.ConnectionProvider<NHibernate.Connection.DriverConnectionProvider>();
            });

            var mapping = GetMappings();
            configure.AddDeserializedMapping(mapping, "HemArkivAccess");

            return configure;
        }
Example #13
0
        static void Main(string[] args)
        {
            #region NHibernate
            var hibernateConfig = new Configuration();
            hibernateConfig.DataBaseIntegration(x =>
            {
                x.ConnectionStringName = "NServiceBus/Persistence";
                x.Dialect <MsSql2012Dialect>();
            });
            var mapper = new ModelMapper();
            mapper.AddMapping <OrderMap>();
            hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            SessionFactory = hibernateConfig.BuildSessionFactory();
            #endregion

            new SchemaExport(hibernateConfig).Execute(false, true, false);

            #region ReceiverConfiguration
            var busConfig = new BusConfiguration();
            busConfig.UseTransport <SqlServerTransport>().UseSpecificConnectionInformation(
                EndpointConnectionInfo.For("sender")
                .UseConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=sender;Integrated Security=True"));

            busConfig.UsePersistence <NHibernatePersistence>();
            busConfig.EnableOutbox();
            #endregion

            using (Bus.Create(busConfig).Start())
            {
                Console.WriteLine("Press <enter> to exit");
                Console.ReadLine();
            }
        }
        private static void InitNHibernate()
        {
            lock (LockObject)
            {
                if (_sessionFactory == null)
                {
                    // Создание NHibernate-конфигурации приложения на основании описаний из web.config.
                    // После этого вызова, в том числе, из сборки будут извлечены настройки маппинга, 
                    // заданные в xml-файлах.
                    var configure = new Configuration().Configure();

                    // Настройка маппинга, созданного при помощи mapping-by-code
                    var mapper = new ModelMapper();
                    mapper.AddMappings(new List<Type>
                    {
                        // Перечень классов, описывающих маппинг
                        typeof (DocumentTypeMap),
                        typeof (DocumentMap),
                        typeof (DocumentWithVersionMap),
                    });
                    // Добавление маппинга, созданного при помощи mapping-by-code, 
                    // в NHibernate-конфигурацию приложения
                    configure.AddDeserializedMapping(mapper.CompileMappingForAllExplicitlyAddedEntities(), null);
                    //configure.LinqToHqlGeneratorsRegistry<CompareValuesGeneratorsRegistry>();
                    //configure.LinqToHqlGeneratorsRegistry<InGeneratorRegistry>();
                    configure.DataBaseIntegration(x =>
                    {
                        x.LogSqlInConsole = true;
                        x.LogFormattedSql = true;
                    });

                    _sessionFactory = configure.BuildSessionFactory();
                }
            }
        }
        private Configuration InitConfiguration()
        {
            var configuration = new Configuration();

            configuration.SessionFactoryName(typeof(NHibernateConfigurer).Assembly.GetName().
                                             FullName);

            configuration.DataBaseIntegration(dicp => {
                dicp.ConnectionProvider <DriverConnectionProvider>();
                dicp.Dialect <MsSql2008Dialect>();
                dicp.Driver <Sql2008ClientDriver>();
                dicp.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                dicp.IsolationLevel     = IsolationLevel.ReadCommitted;
                dicp.ConnectionString   = ConfigurationManager.ConnectionStrings[ConnectionString].ConnectionString;
                dicp.Timeout            = 10;
                dicp.BatchSize          = 20;

                if (ShowLogs)
                {
                    dicp.LogFormattedSql = true;
                    dicp.LogSqlInConsole = true;
                    dicp.AutoCommentSql  = false;
                }
            });

            return(configuration);
        }
Example #16
0
        public Configuration BuildConfiguration(string connectionString, string sessionFactoryName)
        {
            Contract.Requires(!string.IsNullOrEmpty(connectionString), "ConnectionString is null or empty");
            Contract.Requires(!string.IsNullOrEmpty(sessionFactoryName), "SessionFactory name is null or empty");
            Contract.Requires(!string.IsNullOrEmpty(_databaseSchema), "Database Schema is null or empty");
            Contract.Requires(_configurator != null, "Configurator is null");

            return CatchExceptionHelper.TryCatchFunction(
                () =>
                {
                    DomainTypes = GetTypeOfEntities(_assemblies);

                    if (DomainTypes == null)
                        throw new Exception("Type of domains is null");

                    var configure = new Configuration();
                    configure.SessionFactoryName(sessionFactoryName);

                    configure.Proxy(p => p.ProxyFactoryFactory<ProxyFactoryFactory>());
                    configure.DataBaseIntegration(db => GetDatabaseIntegration(db, connectionString));

                    if (_configurator.GetAppSettingString("IsCreateNewDatabase").ConvertToBoolean())
                    {
                        configure.SetProperty("hbm2ddl.auto", "create-drop");
                    }

                    configure.Properties.Add("default_schema", _databaseSchema);
                    configure.AddDeserializedMapping(GetMapping(),
                                                     _configurator.GetAppSettingString("DocumentFileName"));

                    SchemaMetadataUpdater.QuoteTableAndColumns(configure);

                    return configure;
                }, Logger);
        }
Example #17
0
        private Configuration BuildSQLiteConfiguration()
        {
            var config = new Configuration();

            config.DataBaseIntegration(x =>
            {
                x.Driver <SQLite20Driver>();
                x.Dialect <CustomSQLiteDialect>();
                x.ConnectionProvider <DriverConnectionProvider>();
                x.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                x.ConnectionString   = BuildSqlitePath();
                x.Timeout            = 255;
                x.BatchSize          = 100;
                x.LogFormattedSql    = true;
                x.LogSqlInConsole    = true;
                x.AutoCommentSql     = false;
            });

            var mapper = new ModelMapper();

            mapper.AddMappings(typeof(DevContainer).Assembly.GetExportedTypes());

            var domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            if (domainMapping.Items != null)
            {
                config.AddMapping(domainMapping);
            }

            return(config);
        }
        public static Configuration ConfigureNHibernate()
        {
            var cfg = new Configuration();

            cfg.DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2012Dialect>();
                db.Driver <SqlClientDriver>();
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                db.IsolationLevel     = IsolationLevel.ReadCommitted;

                db.ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString;
                db.Timeout          = 10;

                db.LogFormattedSql = true;
                db.LogSqlInConsole = true;
                //db.AutoCommentSql = true;
            });

            var mapping = GetAllMappingsFromAssembly();

            cfg.AddDeserializedMapping(mapping, null);
            SchemaMetadataUpdater.QuoteTableAndColumns(cfg);

            return(cfg);
        }
        public static Configuration BuildConfiguration(string connStr)
        {
            var cfg = new Configuration();

            // See http://fabiomaulo.blogspot.com/2009/07/nhibernate-configuration-through.html
            cfg.DataBaseIntegration(db => {
                db.Driver<SqlClientDriver>();
                db.Dialect<MsSql2012Dialect>();
                db.ConnectionString = connStr; // db.ConnectionStringName = "ConnStr";
                db.HqlToSqlSubstitutions = "true 1, false 0, yes 'Y', no 'N'";

                // See http://geekswithblogs.net/lszk/archive/2011/07/12/showing-a-sql-generated-by-nhibernate-on-the-vs-build-in.aspx
                //db.LogSqlInConsole = true; // Remove if using Log4Net
                //db.LogFormattedSql = true;
                //db.AutoCommentSql = true;

                db.SchemaAction = SchemaAutoAction.Validate; // This correspond to "hbm2ddl.validate", see http://nhforge.org/blogs/nhibernate/archive/2008/11/23/nhibernate-hbm2ddl.aspx
            });

            var mapper = new ModelMapper();
            mapper.Class<Parent>(map => {
                map.Id(x => x.Id, m => {
                    m.Generator(Generators.GuidComb);
                    m.UnsavedValue(Guid.Empty);
                });
                map.Version(x => x.RowVersion, m => m.UnsavedValue(0));
                map.Property(x => x.Description);
            });
            cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            return cfg;
        }
        static public ISessionFactory GetSF()
        {
            try
            {
                if (_SF == null)
                {
                    var nhCnfig = new NHibernate.Cfg.Configuration();

                    nhCnfig.DataBaseIntegration(delegate(NHibernate.Cfg.Loquacious.IDbIntegrationConfigurationProperties abc)
                    {
                        abc.ConnectionString = "Database=rides;Data Source=localhost;Port=3306;User Id=root;Password=<K%F!1?qsYt0";
                        abc.Dialect <NHibernate.Dialect.MySQL55Dialect>();
                        abc.Driver <NHibernate.Driver.MySqlDataDriver>();
                        abc.LogSqlInConsole = true;
                        abc.Timeout         = 60;
                    });

                    nhCnfig.AddAssembly(typeof(Templar).Assembly);
                    nhCnfig.CurrentSessionContext <WebSessionContext>();

                    _SF = nhCnfig.BuildSessionFactory();
                }
            }

            catch (Exception ex)
            { }

            return(_SF);
        }
        /// <summary>
        /// Creates session factory
        /// </summary>
        /// <param name="configurationReader">configuration reader</param>
        /// <returns></returns>
        private static ISessionFactory CreateSessionFactory(IConfigurationReader configurationReader)
        {
            var configuration = new NHibernate.Cfg.Configuration();
            configuration.SessionFactoryName("Jumblocks Blog");

            configuration.DataBaseIntegration(db =>
            {
                db.Dialect<MsSql2008FixedDialect>();
                db.IsolationLevel = IsolationLevel.ReadCommitted;
                db.ConnectionString = configurationReader.ConnectionStrings["BlogDb"].ConnectionString;
                db.BatchSize = 100;

                //for testing
                db.LogFormattedSql = true;
                db.LogSqlInConsole = true;
                db.AutoCommentSql = true;
            });

            var mapper = new ModelMapper();
            mapper.AddMapping<BlogPostMap>();
            mapper.AddMapping<BlogUserMap>();
            mapper.AddMapping<ImageReferenceMap>();
            mapper.AddMapping<TagMap>();
            mapper.AddMapping<SeriesMap>();

            mapper.AddMapping<UserMap>();
            mapper.AddMapping<RoleMap>();
            mapper.AddMapping<OperationMap>();

            configuration.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
            configuration.CurrentSessionContext<WebSessionContext>();

            return configuration.BuildSessionFactory();
        }
        private void InitSessionFactory()
        {
            var mapper = new ModelMapper();

            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());

            var mapeamentoDominio = mapper.CompileMappingForAllExplicitlyAddedEntities();


            //var testStrinConecao = "Data Source=189.36.10.90,49433;Initial Catalog=ProIntegracao;Persist Security Info=True;User ID=mfranco;Password=M@rcelo1988"; //System.Configuration.ConfigurationSettings.AppSettings["ConexaoSQL.0"];


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

            configuration.DataBaseIntegration(c =>
            {
                c.Dialect <MsSql2008Dialect>();
                c.ConnectionString   = ObterStringConexao();//System.Configuration.ConfigurationSettings.AppSettings["ConexaoSQL.0"];
                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            }).AddMapping(mapeamentoDominio);

            configuration.AddAssembly("ProIntegracao.Data");

            _sessionFactory = configuration.BuildSessionFactory();
        }
 private static void InitializeSessionFactory()
 {
     if (sessionFactory == null)
     {
         lock (mutex)
         {
             if (sessionFactory == null)
             {
                 configuration = new Configuration();
                 configuration.DataBaseIntegration(db =>
                 {
                     db.ConnectionString = connectionString;
                     db.Dialect<MsSql2008Dialect>();
                     db.Driver<SqlClientDriver>();
                     db.Timeout = 20;
                     db.LogFormattedSql = Config.LogSql;
                     db.LogSqlInConsole = Config.LogSql;
                 });
                 var modelMapper = new ModelMapper();
                 modelMapper.AddMappings(ExportedTypes);
                 var mappingDocument = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
                 configuration.AddMapping(mappingDocument);
                 sessionFactory = configuration.BuildSessionFactory();
             }
         }
     }
 }
Example #24
0
        static void Main(string[] args)
        {
            var container = new WindsorContainer();
            container.Register(
                Component.For<ICustomerRepository>().ImplementedBy<CustomerRepository>(),
                Component.For<ICustomerValidator>().ImplementedBy<CustomerValidator>(),
                Component.For<ICreditCheck>().ImplementedBy<CreditCheck>()
                );

            var cfg = new Configuration();
            cfg.DataBaseIntegration(x => {
                x.ConnectionStringName="Default";
                x.Driver<SqlClientDriver>();
                x.Dialect<MsSqlCe40Dialect>();
                x.BatchSize = 50;
            });
            cfg.AddAssembly(Assembly.GetExecutingAssembly());
            var sessionfactory = cfg.BuildSessionFactory();
            using (var session = sessionfactory.OpenSession())
            {
                using (var trx = session.BeginTransaction())
                {
                    //blah
                    trx.Commit();
                }
            }
        }
Example #25
0
        private static Configuration ConfigureNHibernate()
        {
            var configure = new Configuration();

            configure.SessionFactoryName("BuildIt");

            configure.DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2008Dialect>();
                db.Driver <Sql2008ClientDriver>();
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                db.IsolationLevel     = IsolationLevel.ReadCommitted;

                db.ConnectionStringName = "TestDB";
                db.Timeout = 10;

                // enabled for testing
                db.LogFormattedSql = true;
                db.LogSqlInConsole = true;
                db.AutoCommentSql  = true;
            });

            var mapping = GetMappings();

            configure.AddDeserializedMapping(mapping, "NHSchemaTest");
            SchemaMetadataUpdater.QuoteTableAndColumns(configure);

            return(configure);
        }
		protected override void Configure(Configuration configuration)
		{
			configuration.DataBaseIntegration(x =>
			{
				x.BatchSize = 10;
			});
		}
Example #27
0
        public void TestEvent2()
        {
            var config = new NHibernate.Cfg.Configuration();
            config.Configure();
            config.DataBaseIntegration(db =>
            {
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

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

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

            var factory = config.BuildSessionFactory();

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

            using (var session = factory.OpenSession())
            {
                var message = session.Get<Message>(1);
                message.Content = "Message_Leoli2";
                session.Save(message);
                session.Flush();
                Assert.AreEqual(message.LastEditor, "Leoli_Update_Event");
            }
        }
        static public ISessionFactory GetSF()
        {
            try
            {
                if (_SF == null)
                {
                    var nhCnfig = new NHibernate.Cfg.Configuration();

                    nhCnfig.DataBaseIntegration(delegate(NHibernate.Cfg.Loquacious.IDbIntegrationConfigurationProperties abc)
                    {
                        abc.ConnectionString = "Database=test_db;Data Source=localhost;Port=3306;User Id=root;Password=1234";
                        abc.Dialect <NHibernate.Dialect.MySQL55Dialect>();
                        abc.Driver <NHibernate.Driver.MySqlDataDriver>();
                        abc.Timeout = 60;
                    }
                                                );
                    //one of your model in our case we just have one model
                    nhCnfig.AddAssembly(typeof(TestTable).Assembly);
                    nhCnfig.CurrentSessionContext <WebSessionContext>();
                    _SF = nhCnfig.BuildSessionFactory();
                }
            }

            catch (Exception ex)
            { }


            return(_SF);
        }
        public InMemoryNHibernateSessionSource(IEnumerable<Assembly> mappingAssemblies)
        {
            var configuration = new Configuration();
            configuration.DataBaseIntegration(cfg =>
                                              {
                                                  cfg.ConnectionString = "FullUri=file:memorydb.db?mode=memory&cache=shared";
                                                  cfg.Driver<SQLite20Driver>();
                                                  cfg.Dialect<SQLiteDialect>();
                                                  cfg.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                                                  cfg.SchemaAction = SchemaAutoAction.Update;
                                              });

            configuration.AddCodeMappingsFromAssemblies(mappingAssemblies);

            SchemaMetadataUpdater.QuoteTableAndColumns(configuration);

            _factory = configuration.BuildSessionFactory();

            _connectionCreatingSessionThatShouldNotBeDisposedUntilTestHasRunToEnd = _factory.OpenSession();
            _connection = _connectionCreatingSessionThatShouldNotBeDisposedUntilTestHasRunToEnd.Connection;

            new SchemaExport(configuration).Execute(
                              script: false,
                              export: true,
                              justDrop: false,
                              connection: _connection,
                              exportOutput: null);
        }
Example #30
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SQLNHibernateOutbox.Receiver";
        #region NHibernate

        var hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionString = @"Data Source=.\SqlExpress;Database=nservicebus;Integrated Security=True";
            x.Dialect <MsSql2012Dialect>();
        });
        var mapper = new ModelMapper();
        mapper.AddMapping <OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        #endregion

        new SchemaExport(hibernateConfig).Execute(false, true, false);

        var endpointConfiguration = new EndpointConfiguration("Samples.SQLNHibernateOutbox.Receiver");
        endpointConfiguration.UseSerialization <JsonSerializer>();
        #region ReceiverConfiguration

        var transport = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.ConnectionString(@"Data Source=.\SqlExpress;Database=nservicebus;Integrated Security=True");

        var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>();
        persistence.UseConfiguration(hibernateConfig);

        endpointConfiguration.EnableOutbox();

        #endregion

        #region RetriesConfiguration

        endpointConfiguration.Recoverability()
        .Immediate(immediate => immediate.NumberOfRetries(0))
        .Delayed(delayed => delayed.NumberOfRetries(0));

        #endregion

        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
		protected override void Configure(Configuration configuration)
		{
			configuration.DataBaseIntegration(x =>
			{
				x.BatchSize = 0;
				x.Batcher<NonBatchingBatcherFactory>();
			});
		}
		protected override void Configure(Configuration configuration)
		{
			configuration.DataBaseIntegration(x =>
			                                  {
																					x.BatchSize = batchSize;
																					x.OrderInserts = true;
																					x.Batcher<StatsBatcherFactory>();
			                                  });
		}
Example #33
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SQLNHibernateOutbox.Receiver";
        #region NHibernate

        Configuration hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=nservicebus;Integrated Security=True";
            x.Dialect <MsSql2012Dialect>();
        });
        ModelMapper mapper = new ModelMapper();
        mapper.AddMapping <OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        #endregion

        new SchemaExport(hibernateConfig).Execute(false, true, false);

        EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.SQLNHibernateOutbox.Receiver");
        endpointConfiguration.UseSerialization <JsonSerializer>();
        #region ReceiverConfiguration

        endpointConfiguration
        .UseTransport <SqlServerTransport>()
        .ConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=nservicebus;Integrated Security=True");

        endpointConfiguration.UsePersistence <NHibernatePersistence>()
        .UseConfiguration(hibernateConfig);

        endpointConfiguration.EnableOutbox();

        #endregion

        #region RetriesConfiguration

        endpointConfiguration.DisableFeature <FirstLevelRetries>();
        endpointConfiguration.DisableFeature <SecondLevelRetries>();

        #endregion

        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration);

        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpoint.Stop();
        }
    }
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SQLNHibernateOutbox.Receiver";
        #region NHibernate

        var hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=nservicebus;Integrated Security=True";
            x.Dialect<MsSql2012Dialect>();
        });
        var mapper = new ModelMapper();
        mapper.AddMapping<OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        #endregion

        new SchemaExport(hibernateConfig).Execute(false, true, false);

        var endpointConfiguration = new EndpointConfiguration("Samples.SQLNHibernateOutbox.Receiver");
        endpointConfiguration.UseSerialization<JsonSerializer>();
        #region ReceiverConfiguration

        var transport = endpointConfiguration.UseTransport<SqlServerTransport>();
        transport.ConnectionString(@"Data Source=.\SQLEXPRESS;Initial Catalog=nservicebus;Integrated Security=True");

        var persistence = endpointConfiguration.UsePersistence<NHibernatePersistence>();
        persistence.UseConfiguration(hibernateConfig);

        endpointConfiguration.EnableOutbox();

        #endregion

        #region RetriesConfiguration

        endpointConfiguration.DisableFeature<FirstLevelRetries>();
        endpointConfiguration.DisableFeature<SecondLevelRetries>();

        #endregion

        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.AuditProcessedMessagesTo("audit");

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpointInstance.Stop()
                .ConfigureAwait(false);
        }
    }
		public virtual void Apply(Configuration configuration, IDatabaseProvider databaseProvider)
		{
			configuration.CurrentSessionContext<CallSessionContext>();

			configuration.DataBaseIntegration(db => SetDatabase(db, databaseProvider, configuration));

			configuration.Cache(SetCache);

			configuration.Proxy(SetProxy);
		}
Example #36
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SQLNHibernateOutboxEF.Receiver";

        var connectionString = @"Data Source=.\SqlExpress;Database=nservicebus;Integrated Security=True";
        var startupSql       = File.ReadAllText("Startup.sql");

        await SqlHelper.ExecuteSql(connectionString, startupSql)
        .ConfigureAwait(false);

        var hibernateConfig = new Configuration();

        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect <MsSql2012Dialect>();
        });

        hibernateConfig.SetProperty("default_schema", "receiver");

        var endpointConfiguration = new EndpointConfiguration("Samples.SQLNHibernateOutboxEF.Receiver");

        endpointConfiguration.UseSerialization <JsonSerializer>();
        endpointConfiguration.EnableInstallers();
        endpointConfiguration.SendFailedMessagesTo("error");

        #region ReceiverConfiguration

        var transport = endpointConfiguration.UseTransport <SqlServerTransport>();

        var routing = transport.Routing();
        routing.RouteToEndpoint(typeof(OrderAccepted).Assembly, "Samples.SQLNHibernateOutboxEF.Sender");
        routing.RegisterPublisher(typeof(OrderAccepted).Assembly, "Samples.SQLNHibernateOutboxEF.Sender");

        transport.DefaultSchema("receiver");

        transport.UseSchemaForEndpoint("Samples.SQLNHibernateOutboxEF.Sender", "sender");
        transport.UseSchemaForQueue("error", "dbo");
        transport.UseSchemaForQueue("audit", "dbo");

        endpointConfiguration
        .UsePersistence <NHibernatePersistence>();

        endpointConfiguration.EnableOutbox();

        #endregion

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
		static void Main(String[] args)
		{
			var cfg = new Configuration();
			cfg.DataBaseIntegration(x =>
				{
					x.Dialect<MsSql2008Dialect>();
					x.Driver<Sql2008ClientDriver>();
					x.ConnectionString = @"Data Source=(local)\SQLEXPRESS; Initial Catalog=NHibernate; Integrated Security=SSPI";
					x.SchemaAction = SchemaAutoAction.Update;
				})
				.SetProperty(NHibernate.Cfg.Environment.UseProxyValidator, Boolean.FalseString);

			var model = new ConventionModelMapper();
			model.BeforeMapClass += (a, b, c) => { c.Lazy(false); c.Id(x => x.Generator(Generators.Identity)); };

			var mappings = model.CompileMappingFor(new Type[] { typeof(Xpto) });

			cfg.AddMapping(mappings);

			using (var sessionFactory = cfg.BuildSessionFactory())
			{
				var validation = sessionFactory
					.FluentlyValidate()
					.Entity<Xpto>(x => x.Name != "aa", "Name is empty");

				using (var session = sessionFactory.OpenSession())
				using (var tx = session.BeginTransaction())
				{
					var x = new Xpto();

					try
					{
						session.Save(x);
						session.Flush();
					}
					catch
					{
						//expected
					}

					x.Name = "aa";

					//disable all validations
					//sessionFactory.DisableFluentValidation();
					
					//disable validations over the Xpto class
					//validation.Clear<Xpto>();

					//session.Save(new Xpto());
					session.Flush();
					//should work
				}
			}
		}
Example #38
0
        private static Configuration GetConfiguration()
        {
            Configuration configuration = new Configuration();

            configuration.DataBaseIntegration(db =>
            {
                db.ConnectionString = "";
                db.Dialect <MsSql2012Dialect>();
            });
            return(configuration);
        }
        private static ISessionFactory ConfigureSessionFactory()
        {
            var config = new Configuration();

            config.DataBaseIntegration(db =>
            {
                db.Dialect<SQLiteDialect>();
                db.ConnectionStringName = "Sqlite_InMemory";
            });

            return config.BuildSessionFactory();
        }
 private void ConfigureByCode(NHibernate.Cfg.Configuration cfg)
 {
     cfg.DataBaseIntegration(db =>
     {
         db.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
         db.Dialect <NHibernate.Dialect.SQLiteDialect>();
         db.Driver <NHibernate.Driver.SQLite20Driver>();
         db.ConnectionString = CONNECTION_STRING;
         db.LogSqlInConsole  = true;
         db.LogFormattedSql  = true;
     });
 }
 protected virtual void CreateInMemoryDatabase()
 {
     configuration = new Configuration();
     configuration.DataBaseIntegration(
         db=>{
             db.Dialect<SQLiteDialect>();
             db.ConnectionProvider<InMemoryConnectionProvider>();
             db.ConnectionString = "Data Source=:memory:;Version=3;New=True;";
         });
     Mapping(configuration);
     sessionFactory = configuration.BuildSessionFactory();
 }
 static Store()
 {
     _cfg = new Configuration();
        // _cfg.Configure();
     _cfg.DataBaseIntegration(x =>
     {
         x.ConnectionString = "Server=.;Initial Catalog=UtbildningDatabas;Integrated Security=true;";
         x.Driver<SqlClientDriver>();
         x.Dialect<MsSql2012Dialect>();
     });
     _cfg.AddDeserializedMapping(CreateMapping(), null);
     //_cfg.AddAssembly(System.Reflection.Assembly.GetExecutingAssembly());
 }
Example #43
0
        public void SetUp()
        {
            Configuration config = new Configuration();
            config.DataBaseIntegration(db =>
            {
                db.Dialect<MsSql2012Dialect>();
                db.Driver<SqlClientDriver>();
                db.ConnectionString = "Data Source=DESKTOP-0II3UCP\\MAINSERVER;Initial Catalog=travelme;Integrated Security=True";
            });

            this.MockConfig = new Mock<IDatabaseConfig>();
            this.MockConfig.SetupSequence(o => o.GetConfig()).Returns(config);
        }
        protected override void Customize(Configuration config)
        {
            config.DataBaseIntegration(x =>
            {
                x.ConnectionString = ConnectionString;
                x.Dialect<SQLiteDialect>();
                x.Driver<SQLite20Driver>();
            });

            config.SetProperty("cache.use_second_level_cache", "false");
            config.SetProperty("generate_statistics", "true");
            config.SetProperty("auto-import", "false");
        }
Example #45
0
        public void TestConfigMappingByCode()
        {
            var config = new NHibernate.Cfg.Configuration();

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

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

            var factory = config.BuildSessionFactory();
        }
Example #46
0
        public void Start()
        {
            _host = WebApp.Start <Startup>(Endpoint);

            Console.WriteLine();
            Console.WriteLine("Hangfire Server started.");
            Console.WriteLine("Dashboard is available at {0}/hangfire", Endpoint);
            Console.WriteLine();

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

            config.DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2008Dialect>();
                db.ConnectionStringName = "DataContext";
            });

            var mapper = new ModelMapper();

            mapper.AddMapping <ApplicationMap>();
            mapper.AddMapping <EnviromentMap>();
            mapper.AddMapping <DeployTaskMap>();
            mapper.AddMapping <ParameterMap>();
            mapper.AddMapping <DeploymentMap>();
            mapper.AddMapping <ApplicationAdministratorsMap>();
            mapper.AddMapping <AllowedGroupMap>();
            mapper.AddMapping <AllowedUserMap>();
            mapper.AddMapping <LogEntryMap>();
            mapper.AddMapping <MailTaskMap>();
            mapper.AddMapping <LocalScriptTaskMap>();
            mapper.AddMapping <RemoteScriptTaskMap>();
            mapper.AddMapping <DatabaseTaskMap>();
            mapper.AddMapping <AgentMap>();
            mapper.AddMapping <ApplicationGroupMap>();
            mapper.AddMapping <DeploymentTaskMap>();
            mapper.AddMapping <TaskTemplateMap>();
            mapper.AddMapping <TaskTemplateVersionMap>();
            mapper.AddMapping <TaskTemplateParameterMap>();
            mapper.AddMapping <TemplatedTaskMap>();
            mapper.AddMapping <TemplatedTaskParameterMap>();
            mapper.AddMapping <MaintenanceTaskMap>();
            mapper.AddMapping <MaintenanceLogEntryMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

            DeployJob.Store         = config.BuildSessionFactory();
            LogsCompactionJob.Store = DeployJob.Store;
            MaintenanceJob.Store    = DeployJob.Store;
            HealthCheckJob.Store    = DeployJob.Store;
        }
        public void Execute(NHibernate.Cfg.Configuration configuration)
        {
            configuration.DataBaseIntegration(
                c =>
            {
                // these fields need to have a value or nhibernate throws an exception. we default them to empty because
                // we have a connection string provider
                c.ConnectionString     = string.Empty;
                c.ConnectionStringName = string.Empty;

                // this enables the connection to be dynamic based on routes
                c.ConnectionProvider <NHibernateOdsConnectionProvider>();
            });
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();



            services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority            = "http://localhost:5000";
                options.RequireHttpsMetadata = false;

                options.Audience = "api1";
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    NameClaimType = JwtClaimTypes.Name,
                    RoleClaimType = JwtClaimTypes.Role,
                };
            });

            services.AddCors(options =>
            {
                // this defines a CORS policy called "default"
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins("http://localhost:8080")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.DataBaseIntegration(options =>
            {
                options.ConnectionString = Configuration.GetConnectionString("DefaultConnection");
                options.Driver <NHibernate.Driver.SqlClientDriver>();
                options.Dialect <NHibernate.Dialect.MsSql2005Dialect>();
                options.LogSqlInConsole       = true;
                options.LogFormattedSql       = true;
                options.ConnectionReleaseMode = ConnectionReleaseMode.OnClose;
                options.SchemaAction          = SchemaAutoAction.Update;
                options.KeywordsAutoImport    = Hbm2DDLKeyWords.AutoQuote;
            });
            services.AddAdminApi(config);
        }
Example #49
0
    static void Main()
    {
        Console.Title = "Samples.SQLNHibernateOutboxEF.Receiver";

        var connectionString = @"Data Source=.\SqlExpress;Database=nservicebus;Integrated Security=True";
        var startupSql       = File.ReadAllText("Startup.sql");

        SqlHelper.ExecuteSql(connectionString, startupSql);

        var hibernateConfig = new Configuration();

        hibernateConfig.DataBaseIntegration(
            dataBaseIntegration: configurationProperties =>
        {
            configurationProperties.ConnectionStringName = "NServiceBus/Persistence";
            configurationProperties.Dialect <MsSql2012Dialect>();
        });

        hibernateConfig.SetProperty("default_schema", "receiver");

        var busConfiguration = new BusConfiguration();

        busConfiguration.UseSerialization <JsonSerializer>();
        busConfiguration.EndpointName("Samples.SQLNHibernateOutboxEF.Receiver");

        #region ReceiverConfiguration

        var transport      = busConfiguration.UseTransport <SqlServerTransport>();
        var connectionInfo = EndpointConnectionInfo.For("Samples.SQLNHibernateOutboxEF.Sender")
                             .UseSchema("sender");
        transport.UseSpecificConnectionInformation(connectionInfo);
        transport.DefaultSchema("receiver");

        var persistence = busConfiguration.UsePersistence <NHibernatePersistence>();
        persistence.RegisterManagedSessionInTheContainer();

        busConfiguration.EnableOutbox();

        #endregion

        using (Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
Example #50
0
        private bool Conexao()
        {
            //Cria a configuração com o NH

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

            try
            {
                //Integração com o banco de dados
                config.DataBaseIntegration(c => {
                    //Dialeto do banco
                    c.Dialect <NHibernate.Dialect.MySQLDialect>();
                    //String de conexão
                    c.ConnectionString = StringConexao;
                    //Driver de conexão com o banco
                    c.Driver <NHibernate.Driver.MySqlDataDriver>();
                    //Provedor de conexão do MySQL
                    c.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
                    //Gera Log dos  comenados exercutados no console
                    c.LogSqlInConsole = true;
                    //Cria o schema do banco de dados sempre que a configuration for utilizada
                    c.SchemaAction = SchemaAutoAction.Update;
                });

                //Realiza o mapeamento das classes
                var maps = this.Mapeamento();
                config.AddMapping(maps);

                if (HttpContext.Current == null)
                {
                    config.CurrentSessionContext <ThreadStaticSessionContext>();
                }
                else
                {
                    config.CurrentSessionContext <WebSessionContext>();
                }

                this.SessionFactory = config.BuildSessionFactory();

                return(true);
            }
            catch
            {
                throw;
            }
        }
Example #51
0
        public static ISessionFactory GetNhibernateSessionFactory()
        {
            var configure = new NHibernate.Cfg.Configuration();

            configure.DataBaseIntegration(delegate(NHibernate.Cfg.Loquacious.IDbIntegrationConfigurationProperties dbi) {
                dbi.ConnectionString = "mvcWithNHibernate";
                dbi.Dialect <NHibernate.Dialect.MsSql2012Dialect>();
                dbi.Driver <NHibernate.Driver.SqlClientDriver>();
                dbi.Timeout = 255;
            });

            configure.AddAssembly(typeof(Address).Assembly);

            configure.CurrentSessionContext <WebSessionContext>();

            return(configure.BuildSessionFactory());
        }
Example #52
0
    static Configuration CreateBasicNHibernateConfig()
    {
        var hibernateConfig = new Configuration();

        hibernateConfig.DataBaseIntegration(x =>
        {
            #region ConnectionProvider

            x.ConnectionProvider <MultiTenantConnectionProvider>();

            #endregion

            x.Dialect <MsSql2012Dialect>();
            x.ConnectionStringName = "NServiceBus/Persistence";
        });
        return(hibernateConfig);
    }
Example #53
0
    static Configuration CreateBasicNHibernateConfig()
    {
        var hibernateConfig = new Configuration();

        hibernateConfig.DataBaseIntegration(x =>
        {
            #region ConnectionProvider

            x.ConnectionProvider <MultiTenantConnectionProvider>();

            #endregion

            x.Dialect <MsSql2012Dialect>();
            x.ConnectionString = Connections.Default;
        });
        return(hibernateConfig);
    }
Example #54
0
        private static NHibernate.Cfg.Configuration NHibernateConfiguration()
        {
            var cfg = new NHibernate.Cfg.Configuration();

            cfg.DataBaseIntegration(x =>
            {
                x.ConnectionString = @"Server=(localdb)\MSSQLLocalDB;Integrated Security=true;AttachDbFileName=C:\Data\FinanceDB.mdf";
                x.Driver <SqlClientDriver>();
                x.Dialect <MsSql2012Dialect>();
                x.Timeout         = 10;
                x.LogSqlInConsole = true;
                x.LogFormattedSql = true;
            });

            cfg.AddAssembly(Assembly.GetExecutingAssembly());

            return(cfg);
        }
        /// <summary>
        /// Configure the defaults for PostgreSQL support, but only if not already set, such as from another
        /// configuration activity or from the xml config
        /// </summary>
        /// <param name="configuration">The NHibernate <see cref="Configuration"/> instance to be manipulated.</param>
        public void Execute(NHibernate.Cfg.Configuration configuration)
        {
            var configuredDialect = configuration.GetProperty(Environment.Dialect);
            var configuredDriver  = configuration.GetProperty(Environment.ConnectionDriver);

            configuration.DataBaseIntegration(c =>
            {
                if (string.IsNullOrWhiteSpace(configuredDialect))
                {
                    c.Dialect <MsSql2012Dialect>();
                }

                if (string.IsNullOrWhiteSpace(configuredDriver))
                {
                    c.Driver <EdFiSql2008ClientDriver>();
                }
            });
        }
Example #56
0
        private static NHibernate.Cfg.Configuration ConfigureNHibernate()
        {
            var configuration = new NHibernate.Cfg.Configuration();

            //configuration.SessionFactoryName("BuildIt");

            configuration.DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2008Dialect>();
                db.Driver <SqlClientDriver>();
                db.Timeout = 10;

                db.ConnectionString = ConfigurationManager.AppSettings.Get("ConnectionString");
                db.LogFormattedSql  = true;
                db.LogSqlInConsole  = true;
                db.AutoCommentSql   = true;
            });
            return(configuration);
        }
Example #57
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var configuration = new NHibernate.Cfg.Configuration();

            configuration.DataBaseIntegration(c =>
            {
                c.Driver <NHibernate.Driver.NpgsqlDriver>();
                c.Dialect <NHibernate.Dialect.PostgreSQL83Dialect>();

                var connectionString = System.Environment.GetEnvironmentVariable("CONNECTION_STRING");
                Console.WriteLine("Given ConnectionString:" + connectionString);
                c.ConnectionString = connectionString;
                c.LogFormattedSql  = true;
                c.LogSqlInConsole  = true;
            });

            var mapper = new NHibernate.Mapping.ByCode.ModelMapper();

            mapper.AddMapping <PatientMapping>();
            mapper.AddMapping <ObservationMapping>();

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            configuration.AddMapping(mapping);

            services.AddSingleton <ICentralConfiguration>(new CentralConfiguration());
            services.AddSingleton <IObservationTransformer>(new ObservationTransformer());

            // add NHibernate services;
            services.AddHibernate(configuration);

            services.AddControllers();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder
                                  .AllowAnyMethod()
                                  .AllowCredentials()
                                  .SetIsOriginAllowed((host) => true)
                                  .AllowAnyHeader());
            });
        }
Example #58
0
        protected virtual void RegisterProperties(NHibernate.Cfg.Configuration configuration)
        {
            configuration.Proxy(p => p.ProxyFactoryFactory <ComponentProxyFactoryFactory>());
            configuration.DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2005Dialect>();
                db.Driver <SqlClientDriver>();
                //db.ConnectionStringName = "ConnectionString";
                db.ConnectionString = Common.Constants.AppConfig.ConnectionString;
                db.BatchSize        = 10;
            });
            configuration.CurrentSessionContext <ThreadLocalConversationalSessionContext>();

            configuration.Cache(cp =>
            {
                cp.UseQueryCache = true;
                cp.Provider <SysCacheProvider>();
            });
        }
Example #59
0
    static void Main()
    {
        Console.Title = "Samples.SQLNHibernateOutbox.Receiver";
        #region NHibernate

        Configuration hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect <MsSql2012Dialect>();
        });
        ModelMapper mapper = new ModelMapper();
        mapper.AddMapping <OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        #endregion

        new SchemaExport(hibernateConfig).Execute(false, true, false);

        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.UseSerialization <JsonSerializer>();
        busConfiguration.EndpointName("Samples.SQLNHibernateOutbox.Receiver");
        #region ReceiverConfiguration

        busConfiguration.UseTransport <SqlServerTransport>();

        busConfiguration.UsePersistence <NHibernatePersistence>()
        .RegisterManagedSessionInTheContainer()
        .UseConfiguration(hibernateConfig);

        busConfiguration.EnableOutbox();

        #endregion

        busConfiguration.DisableFeature <SecondLevelRetries>();

        using (Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
Example #60
-1
        public void TestInitizlize()
        {
            var config = new Configuration();

            config.DataBaseIntegration(
                db =>
                {
                    db.Dialect<SQLiteDialect>();
                    db.Driver<SQLite20Driver>();
                    db.ConnectionString = ConnectionString;
                    db.LogSqlInConsole = false;
                    db.LogFormattedSql = true;
                    db.AutoCommentSql = true;
                }
                );
            config.SetProperty(Environment.CurrentSessionContextClass, "thread_static");

            var mapper = new ModelMapper();
            mapper.WithMappings(config);

            ContextSessionFactory = config.BuildSessionFactory();

            ContextSession = ContextSessionFactory.OpenSession();

            var schemaExport = new SchemaExport(config);
            schemaExport.Execute(false, true, false, ContextSession.Connection, TextWriter.Null);

            Context();
            BecauseOf();
        }