예제 #1
1
파일: ExamUserOP.cs 프로젝트: wgang10/ZYWeb
        /// <summary>
        /// 保存考试人信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static int SaveExamUser(ExamUser model)
        {
            int id = -1;
            if (model != null)
            {
                var conf = new Configuration().Configure();
                ISession session = NHibernateHelper.GetSession();
                //配置NHibernate
                //在Configuration中添加HbmMapping
                conf.AddDeserializedMapping(NHibernateHelper.GetEntityMapping<ExamUser>(), "ExamUserXML");
                //配置数据库架构元数据
                SchemaMetadataUpdater.QuoteTableAndColumns(conf);

                //建立SessionFactory
                var factory = conf.BuildSessionFactory();
                //打开Session做持久化数据
                using (session = factory.OpenSession())
                {
                    using (var tx = session.BeginTransaction())
                    {
                        id = (int)session.Save(model);
                        tx.Commit();
                    }
                }
            }
            return id;
        }
        public static void AddNHibernateSessionFactory(this IServiceCollection services)
        {
            // By default NHibernate looks for hibernate.cfg.xml
            // otherwise for Web it will fallback to web.config
            // we got one under wwwroot/web.config
            Configuration config = new Configuration();
            config.Configure();

            // Auto load entity mapping class
            ModelMapper mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetAssembly(typeof(Employee)).GetExportedTypes());

            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            config.AddDeserializedMapping(mapping, "NHibernate.Mapping");

            SchemaMetadataUpdater.QuoteTableAndColumns(config);

            // Drop & Recreate database schema
            new SchemaExport(config).Drop(false, true);
            new SchemaExport(config).Create(false, true);

            // Register services
            services.AddSingleton<ISessionFactory>(provider => config.BuildSessionFactory());
            services.AddTransient<ISession>(provider => services.BuildServiceProvider().GetService<ISessionFactory>().OpenSession());
        }
예제 #3
0
		public void SetUp() {
			if (this._sessionFactory == null) {
				var cfg = new Configuration();
				cfg.Configure();
				this._sessionFactory = cfg.BuildSessionFactory();
			}
		}
예제 #4
0
		public override void Process(Configuration config)
		{
			var tables = GetTables(config);

			// create a resource resolver that will scan all plugins
			// TODO: we should only scan plugins that are tied to the specified PersistentStore, but there is currently no way to know this
			IResourceResolver resolver = new ResourceResolver(
				CollectionUtils.Map(Platform.PluginManager.Plugins, (PluginInfo pi) => pi.Assembly).ToArray());

			// find all dbi resources
			var rx = new Regex("dbi.xml$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
			var dbiFiles = resolver.FindResources(rx);

			foreach (var dbiFile in dbiFiles)
			{
				using (var stream = resolver.OpenResource(dbiFile))
				{
					var xmlDoc = new XmlDocument();
					xmlDoc.Load(stream);
					var indexElements = xmlDoc.SelectNodes("indexes/index");
					if (indexElements == null)
						continue;

					foreach (XmlElement indexElement in indexElements)
					{
						ProcessIndex(indexElement, tables);
					}
				}
			}

		}
 static OracleSessionFactoryHelper()
 {
     var cfg = new Configuration();
     cfg.SessionFactory()
            .Proxy
                .DisableValidation()
                .Through<NHibernate.Bytecode.DefaultProxyFactoryFactory>()
                .Named("Fluent.SessionFactory")
                .GenerateStatistics()
                .Using(EntityMode.Poco)
                .ParsingHqlThrough<NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory>()
            .Integrate
                .Using<Oracle10gDialect>()
                .AutoQuoteKeywords()
                .LogSqlInConsole()
                .EnableLogFormattedSql()
            .Connected
                .Through<DriverConnectionProvider>()
                .By<OracleDataClientDriver>()
                .ByAppConfing("ConnectionString")
            .CreateCommands
                .Preparing()
                .WithTimeout(10)
                .AutoCommentingSql()
                .WithMaximumDepthOfOuterJoinFetching(11)
                .WithHqlToSqlSubstitutions("true 1, false 0, yes 'Y', no 'N'");
     SessionFactory = FluentNHibernate.Cfg.Fluently.Configure(cfg)
            .Database(OracleDataClientConfiguration.Oracle10.ShowSql())
            .Mappings(m => GetMappingsAssemblies().ToList()
                .ForEach(o => m.FluentMappings.AddFromAssembly(o))).BuildSessionFactory();
 }
        /// <summary>
        /// Carga las listas de la BD que se necesitan para las consultas
        /// </summary>
        private void CargarListas()
        {
            //Iniciar sesión
            var cfg = new Configuration();
            cfg.Configure();
            var sessions = cfg.BuildSessionFactory();
            var sess = sessions.OpenSession();

            //Consulta a la BD
            IQuery q1 = sess.CreateQuery("FROM Cliente");
            var clientesTodos = q1.List<Cliente>();

            //Actualización de la lista global de clientes
            clientes = clientesTodos.ToList<Cliente>();

            //Consulta a la BD
            IQuery q2 = sess.CreateQuery("FROM Empleada");
            var empleadosTodos = q2.List<Empleada>();

            //Actualización de la lista global de clientes
            empleados = empleadosTodos.ToList<Empleada>();

            //Carga en las tablas
            sess.Close();
        }
예제 #7
0
        /// <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();
        }
예제 #8
0
		public void SpecifiedForeignKeyNameInByCodeMappingIsUsedInGeneratedSchema()
		{
			var mapper = new ModelMapper();

			// Generates a schema in which a Person record cannot be created unless an Employee
			// with the same primary key value already exists. The Constrained property of the
			// one-to-one mapping is required to create the foreign key constraint on the Person
			// table, and the optional ForeignKey property is used to name it; otherwise a
			// generated name is used

			mapper.Class<Person>(rc =>
			{
				rc.Id(x => x.Id, map => map.Generator(Generators.Foreign<Employee>(p => p.Person)));
				rc.Property(x => x.Name);
				rc.OneToOne(x => x.Employee, map =>
				{
					map.Constrained(true);
					map.ForeignKey(ForeignKeyName);
				});
			});

			mapper.Class<Employee>(rc =>
			{
				rc.Id(x => x.Id);
				rc.OneToOne(x => x.Person, map => { });
			});

			var script = new StringBuilder();
			var cfg = new Configuration();
			cfg.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

			new SchemaExport(cfg).Execute(s => script.AppendLine(s), false, false);
			script.ToString().Should().Contain(string.Format("constraint {0}", ForeignKeyName));
		}
예제 #9
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);
        }
예제 #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MappingEngine"/> class
 /// </summary>
 /// <param name="rootConfig">The root configuration</param>
 /// <param name="nhConfig">The current NH configuration</param>
 /// <param name="modelMapper">The model mapper</param>
 public MappingEngine(FirehawkConfig rootConfig, Configuration nhConfig, ConventionModelMapper modelMapper)
 {
     this.rootConfig = rootConfig;
     this.nhConfig = nhConfig;
     this.modelMapper = modelMapper;
     this.namingEngine = new NamingEngine(rootConfig.NamingConventionsConfig);
 }
예제 #11
0
		public OneToManyPersister(Mapping.Collection collection, ICacheConcurrencyStrategy cache, Configuration cfg, ISessionFactoryImplementor factory)
			: base(collection, cache, cfg, factory)
		{
			_cascadeDeleteEnabled = collection.Key.IsCascadeDeleteEnabled && factory.Dialect.SupportsCascadeDelete;
			_keyIsNullable = collection.Key.IsNullable;
			_keyIsUpdateable = collection.Key.IsUpdateable;
		}
예제 #12
0
		public void IncrementGeneratorShouldIncludeClassLevelSchemaWhenGettingNextId()
		{
			System.Type thisType = GetType();
			Assembly thisAssembly = thisType.Assembly;

			Configuration cfg = new Configuration();
			cfg.AddResource(thisType.Namespace + ".Mappings.hbm.xml", thisAssembly);

			PersistentClass persistentClass = cfg.GetClassMapping(typeof(TestNH1061));
			// We know the ID generator is an IncrementGenerator.  The dialect does
			// not play a big role here, so just use the MsSql2000Dialect.
			IncrementGenerator generator =
				(IncrementGenerator)
				persistentClass.Identifier.CreateIdentifierGenerator(new Dialect.MsSql2000Dialect(), null, null, null);

			// I could not find a good seam to crack to test this.
			// This is not ideal as we are reflecting into a private variable to test.
			// On the other hand, the IncrementGenerator is rather stable, so I don't
			// think this would be a huge problem.
			// Having said that, if someone sees this and have a better idea to test,
			// please feel free to change it.
			FieldInfo sqlFieldInfo = generator.GetType().GetField("sql", BindingFlags.NonPublic | BindingFlags.Instance);
			string sql = (string)sqlFieldInfo.GetValue(generator);

			Assert.AreEqual("select max(Id) from test.TestNH1061", sql);
		}
예제 #13
0
 private static void BuildSchema(Configuration configuration)
 {
     // this NHibernate tool takes a configuration (with mapping info in)
     // and exports a database schema from it
     new SchemaExport(configuration)
       .Create(false, true);
 }
 protected NHibernateSessionFactoryProvider(IEnumerable<Type> mappedTypes,
     Action<IDbIntegrationConfigurationProperties> databaseIntegration)
 {
     _mappedTypes = mappedTypes;
     _databaseIntegration = databaseIntegration;
     _configuration = CreateConfiguration();
 }
예제 #15
0
 /// <summary>
 /// Adds mappings for this model to a NHibernate configuration object.
 /// </summary>
 /// <param name="configuration">A NHibernate configuration object to which to add mappings for this model.</param>
 public static void ApplyConfiguration(Configuration configuration)
 {
     configuration.AddXml(Libro.MappingXml.ToString());
       configuration.AddXml(Resenha.MappingXml.ToString());
       configuration.AddXml(Autor.MappingXml.ToString());
       configuration.AddAssembly(typeof(ConfigurationHelper).Assembly);
 }
예제 #16
0
 /// <summary>
 /// Creates a NHibernate configuration object containing mappings for this model.
 /// </summary>
 /// <returns>A NHibernate configuration object containing mappings for this model.</returns>
 public static Configuration CreateConfiguration()
 {
     var configuration = new Configuration();
       configuration.Configure();
       ApplyConfiguration(configuration);
       return configuration;
 }
예제 #17
0
		protected override void Configure(Configuration configuration)
		{
			if (Dialect is MsSql2005Dialect)
				configuration.SetProperty(Environment.Dialect, typeof(CustomDialect).AssemblyQualifiedName);
			else
				appliesToThisDialect = false;
		}
예제 #18
0
 private static void Init()
 {
     nhConfiguration = new Configuration();
     //nhConfiguration.Configure("NhibernateUtils/NHibernate.cfg.xml");
     nhConfiguration.AddAssembly("Activos");
     sessionFactory = nhConfiguration.BuildSessionFactory();
 }
        /// <summary>
        /// Called when the feature should perform its initialization. This call will only happen if the feature is enabled.
        /// </summary>
        protected override void Setup(FeatureConfigurationContext context)
        {
            var configuration = context.Settings.GetOrDefault<Configuration>("StorageConfiguration");

            if (configuration == null)
            {
                var properties = new ConfigureNHibernate(context.Settings).SagaPersisterProperties;
                configuration = new Configuration().SetProperties(properties);
            }
            ConfigureNHibernate.ThrowIfRequiredPropertiesAreMissing(configuration.Properties);

            context.Settings.Get<SharedMappings>().ApplyTo(configuration);

            string connString;

            if (!configuration.Properties.TryGetValue(Environment.ConnectionString, out connString))
            {
                string connStringName;

                if (configuration.Properties.TryGetValue(Environment.ConnectionStringName, out connStringName))
                {
                    var connectionStringSettings = System.Configuration.ConfigurationManager.ConnectionStrings[connStringName];

                    connString = connectionStringSettings.ConnectionString;
                }
            }

            context.Container.RegisterSingleton(new SessionFactoryProvider(configuration.BuildSessionFactory()));

            var disableConnectionSharing = DisableTransportConnectionSharing(context);

            context.Container
                .ConfigureProperty<DbConnectionProvider>(p => p.DisableConnectionSharing, disableConnectionSharing)
                .ConfigureProperty<DbConnectionProvider>(p => p.DefaultConnectionString, connString);

            context.Pipeline.Register<OpenSqlConnectionBehavior.Registration>();
            context.Pipeline.Register<OpenSessionBehavior.Registration>();

            context.Container.ConfigureComponent<OpenSqlConnectionBehavior>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(p => p.ConnectionString, connString)
                .ConfigureProperty(p => p.DisableConnectionSharing, disableConnectionSharing);

            context.Container.ConfigureComponent<OpenSessionBehavior>(DependencyLifecycle.InstancePerCall)
                .ConfigureProperty(p => p.ConnectionString, connString)
                .ConfigureProperty(p => p.DisableConnectionSharing, disableConnectionSharing)
                .ConfigureProperty(p => p.SessionCreator, context.Settings.GetOrDefault<Func<ISessionFactory, string, ISession>>("NHibernate.SessionCreator"));

            context.Container.ConfigureComponent(b => new NHibernateStorageContext(b.Build<PipelineExecutor>(), connString), DependencyLifecycle.InstancePerUnitOfWork);
            context.Container.ConfigureComponent<SharedConnectionStorageSessionProvider>(DependencyLifecycle.SingleInstance)
                .ConfigureProperty(p => p.ConnectionString, connString);

            if (context.Settings.GetOrDefault<bool>("NHibernate.RegisterManagedSession"))
            {
                context.Container.ConfigureComponent(b => b.Build<NHibernateStorageContext>().Session, DependencyLifecycle.InstancePerCall);
            }

            context.Container.ConfigureComponent<Installer>(DependencyLifecycle.SingleInstance)
                .ConfigureProperty(x => x.Configuration, configuration)
                .ConfigureProperty(x => x.RunInstaller, context.Settings.Get<bool>("NHibernate.Common.AutoUpdateSchema"));
        }
예제 #20
0
		protected override void Configure(Configuration cfg)
		{
			//Points to the database created with FileStream Filegroup.
			cfg.Properties["connection.connection_string"] =
				@"Data Source=localhost\SQLEXPRESS;Initial Catalog=FileStreamDB;Integrated Security=True;Pooling=False";

			#region CREATE DATABASE example
/*
			CREATE DATABASE FileStreamDB ON PRIMARY
			  ( NAME = FileStreamDB_data,
				FILENAME = N'C:\FSDemo\FileStreamDB_data.mdf',
				SIZE = 10MB,
				MAXSIZE = 50MB,
				FILEGROWTH = 10%),
			FILEGROUP RowGroup1
			  ( NAME = FileStreamDB_group1,
				FILENAME = N'C:\FSDemo\FileStreamDB_group1.ndf',
				SIZE = 10MB,
				MAXSIZE = 50MB,
				FILEGROWTH = 5MB),
			FILEGROUP FileStreamGroup1 CONTAINS FILESTREAM
			  ( NAME = FileStreamDBResumes,
				FILENAME = N'C:\FSDemo\VendorCatalog')
			LOG ON
			  ( NAME = 'FileStreamDB_log',
				FILENAME = N'C:\FSDemo\FileStreamDB_log.ldf',
				SIZE = 5MB,
				MAXSIZE = 25MB,
				FILEGROWTH = 5MB);
*/
#endregion
		}
예제 #21
0
        public int ExecuteStatement(string sql)
        {
            if (cfg == null)
            {
                cfg = new Configuration();
            }

            using (IConnectionProvider prov = ConnectionProviderFactory.NewConnectionProvider(cfg.Properties))
            {
                IDbConnection conn = prov.GetConnection();

                try
                {
                    using (IDbTransaction tran = conn.BeginTransaction())
                    using (IDbCommand comm = conn.CreateCommand())
                    {
                        comm.CommandText = sql;
                        comm.Transaction = tran;
                        comm.CommandType = CommandType.Text;
                        int result = comm.ExecuteNonQuery();
                        tran.Commit();
                        return result;
                    }
                }
                finally
                {
                    prov.CloseConnection(conn);
                }
            }
        }
        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();
                }
            }
        }
예제 #23
0
 /// <summary>
 /// Create a schema exporter for the given Configuration, with the given
 /// database connection properties
 /// </summary>
 /// <param name="cfg">The NHibernate Configuration to generate the schema from.</param>
 /// <param name="connectionProperties">The Properties to use when connecting to the Database.</param>
 public SchemaExport(Configuration cfg, IDictionary<string, string> connectionProperties)
 {
     this.connectionProperties = connectionProperties;
     dialect = Dialect.Dialect.GetDialect(connectionProperties);
     dropSQL = cfg.GenerateDropSchemaScript(dialect);
     createSQL = cfg.GenerateSchemaCreationScript(dialect);
 }
예제 #24
0
        public global::NHibernate.Cfg.Configuration GetCfg(string[] addAssemblies)
        {
            SessionFactoryImpl sessionFactoryImpl = SpringHelper.ApplicationContext["NHibernateSessionFactory"] as SessionFactoryImpl;
            IDictionary springObjectDic = getSpringObjectPropertyValue("NHibernateSessionFactory", "HibernateProperties") as IDictionary;
            IDictionary<string, string> dic = new Dictionary<string, string>();
            foreach (DictionaryEntry de in springObjectDic)
            {
                dic.Add(de.Key.ToString(), de.Value.ToString());
                //if (de.Key.ToString().Equals("hibernate.dialect"))
                //{
                //    dialectName = de.Value.ToString();
                //}
            }

            #region //真正抓取設定檔的內容
            ISession session = sessionFactoryImpl.OpenSession();
            string connectionStr = session.Connection.ConnectionString;
            #endregion

            dic.Add("connection.connection_string", connectionStr);
            Configuration cfg = new Configuration();
            cfg.AddProperties(dic);

            foreach (string assembly in addAssemblies)
            {
                cfg.AddAssembly(assembly);
            }

            return cfg;
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="assemblyNames">The names of the assemblies containing object-relational mapping information</param>
        /// <exception cref="Exception">Thrown if an error occurred while constructing the factory</exception>
        public ReaderFactory(IEnumerable<string> assemblyNames)
        {
            Exception exception = null;

            // If SessionFactory build fails then retry
            for (int tryNumber = 1; tryNumber <= 3; tryNumber++)
            {
                try
                {
                    Configuration config = new Configuration();

                    // Add assemblies containing mapping definitions
                    foreach (string assemblyName in assemblyNames)
                    {
                        config.AddAssembly(assemblyName);
                    }

                    config.Configure();
                    sessionFactory = config.BuildSessionFactory();

                    // SessionFactory built successfully
                    exception = null;
                    break;
                }
                catch (Exception ex)
                {
                    exception = ex;
                }
            }

            if (exception != null)
            {
                throw new FingertipsException("Could not construct ReaderFactory instance", exception);
            }
        }
 private Configuration createConfiguration()
 {
     Configuration cfg = new Configuration();
     cfg.Configure();
     cfg.AddAssembly(typeof(Mesto).Assembly);
     return cfg;
 }
 public void TestFixtureSetUp()
 {
     _configuration = new Configuration();
     _configuration.Configure();
     _configuration.AddAssembly(typeof(Product).Assembly);
     _sessionFactory = _configuration.BuildSessionFactory();
 }
예제 #28
0
 public static void TestClassSetup(TestContext context)
 {
     _configuration = new Configuration();
     _configuration.Configure();
     _configuration.AddAssembly(typeof(Draft).Assembly);
     _sessionFactory = _configuration.BuildSessionFactory();
 }
예제 #29
0
		protected override void When()
		{
			this.configuration = FluentSearch.Configure()
				.Listeners(ListenerConfiguration.Custom
				           	.PostInsert(listener))
				.BuildConfiguration();
		}
        public static Configuration Initialize()
        {
            INHibernateConfigurationCache cache = new NHibernateConfigurationFileCache();

            var mappingAssemblies = new[] {
                typeof(ActionConfirmation<>).Assembly.GetName().Name
            };

            var configuration = cache.LoadConfiguration(CONFIG_CACHE_KEY, null, mappingAssemblies);

            if (configuration == null) {
                configuration = new Configuration();

                configuration
                    .Proxy(p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>())
                    .DataBaseIntegration(db => {
                        db.ConnectionStringName = "DonSharpLiteConnectionString";
                        db.Dialect<MsSql2008Dialect>();
                    })
                    .AddAssembly(typeof(ActionConfirmation<>).Assembly)
                    .CurrentSessionContext<LazySessionContext>();

                var mapper = new ConventionModelMapper();
                mapper.WithConventions(configuration);

                cache.SaveConfiguration(CONFIG_CACHE_KEY, configuration);
            }

            return configuration;
        }
예제 #31
0
        public static NHibernate.Cfg.Configuration ConfigureEntities(this NHibernate.Cfg.Configuration configuration)
        {
            var modelMapper = new ModelMapper();

            modelMapper.
            AddMappings(
                Assembly.
                GetExecutingAssembly().
                GetExportedTypes().
                Where(t => t.Name.EndsWith("Mapping"))
                );

            configuration.
            AddMapping(
                modelMapper.
                CompileMappingForAllExplicitlyAddedEntities()
                );

            return(configuration);
        }
예제 #32
0
    static void Main()
    {
        SqlHelper.CreateDatabase(ConfigurationManager.ConnectionStrings["NServiceBus/Persistence"].ConnectionString);
        Configuration nhConfiguration = new Configuration();

        nhConfiguration.SetProperty(Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider");
        nhConfiguration.SetProperty(Environment.ConnectionDriver, "NHibernate.Driver.Sql2008ClientDriver");
        nhConfiguration.SetProperty(Environment.Dialect, "NHibernate.Dialect.MsSql2008Dialect");
        nhConfiguration.SetProperty(Environment.ConnectionStringName, "NServiceBus/Persistence");

        BusConfiguration busConfiguration = new BusConfiguration();

        busConfiguration.EndpointName("Samples.CustomNhMappings.Default");
        busConfiguration.UseSerialization <JsonSerializer>();
        busConfiguration.EnableInstallers();
        //busConfiguration.Transactions().DisableDistributedTransactions();

        busConfiguration
        .UsePersistence <NHibernatePersistence>()
        .UseConfiguration(nhConfiguration);

        using (IBus bus = Bus.Create(busConfiguration).Start())
        {
            Parallel.For(0, 1000, i =>
            {
                bus.SendLocal(new StartOrder
                {
                    OrderId = "123"
                });
                bus.SendLocal(new CompleteOrder
                {
                    OrderId = "123"
                });
            });

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
예제 #33
0
 private static void CreateSchema(NHibernate.Cfg.Configuration cfg)
 {
     new SchemaUpdate(cfg).Execute(false, true);
 }
        public static void GeraSchema()
        {
            Configuration cfg = RecuperaConfiguracao();

            new SchemaExport(cfg).Create(false, true);
        }
예제 #35
0
        private ISessionFactory CreateNhSessionFactory(string connectionString)
        {
            var nhConfiguration = new Configuration();

            nhConfiguration.Cache(properties => properties.Provider <HashtableCacheProvider>());

            if (connectionString.ToUpper().Contains("SERVER="))
            {
                //is sql server
                nhConfiguration.DataBaseIntegration(dbi =>
                {
                    dbi.Dialect <MsSql2008Dialect>();
                    dbi.Driver <Sql2008ClientDriver>();
                    dbi.ConnectionProvider <DriverConnectionProvider>();
                    dbi.IsolationLevel   = IsolationLevel.ReadCommitted;
                    dbi.ConnectionString = connectionString;
                    dbi.Timeout          = 60;
                    dbi.LogFormattedSql  = false;
                    dbi.LogSqlInConsole  = false;
                });
            }
            else if (connectionString.ToUpper().Contains("MICROSOFT.ACE.OLEDB") ||
                     connectionString.ToUpper().Contains("MICROSOFT.JET.OLEDB"))
            {
                //is OLE DB
                nhConfiguration.DataBaseIntegration(dbi =>
                {
                    dbi.Dialect <GenericDialect>();
                    dbi.Driver <OleDbDriver>();
                    dbi.ConnectionProvider <DriverConnectionProvider>();
                    dbi.IsolationLevel   = IsolationLevel.ReadCommitted;
                    dbi.ConnectionString = connectionString;
                    dbi.Timeout          = 60;
                    dbi.LogFormattedSql  = false;
                    dbi.LogSqlInConsole  = false;
                });
            }
            else if (connectionString.ToUpper().EndsWith(".DB"))
            {
                //is sql lite
                nhConfiguration.DataBaseIntegration(dbi =>
                {
                    dbi.Dialect <SQLiteDialect>();
                    dbi.Driver <SQLite20Driver>();
                    dbi.ConnectionProvider <DriverConnectionProvider>();
                    dbi.IsolationLevel   = IsolationLevel.ReadCommitted;
                    dbi.ConnectionString = connectionString;
                    dbi.Timeout          = 60;
                    dbi.LogFormattedSql  = false;
                    dbi.LogSqlInConsole  = false;
                });
            }
            else
            {
                //must be oracle
                nhConfiguration.DataBaseIntegration(dbi =>
                {
                    dbi.Dialect <Oracle10gDialect>();
                    dbi.Driver <OracleManagedDataClientDriver>();
                    dbi.ConnectionProvider <DriverConnectionProvider>();
                    dbi.IsolationLevel   = IsolationLevel.ReadCommitted;
                    dbi.ConnectionString = connectionString;
                    dbi.Timeout          = 60;
                    dbi.LogFormattedSql  = false;
                    dbi.LogSqlInConsole  = false;
                });
            }

            nhConfiguration.Properties["show_sql"] = "false";

            var sessionFactory = nhConfiguration.BuildSessionFactory();

            return(sessionFactory);
        }
        public static void CreateSchema(Configuration cfg)
        {
            var schemaExport = new SchemaExport(cfg);

            schemaExport.Create(false, true);
        }
예제 #37
0
    static void Main()
    {
        Console.Title = "Samples.MultiTenant.Receiver";

        Configuration hibernateConfig = CreateBasicNHibernateConfig();
        ModelMapper   mapper          = new ModelMapper();

        mapper.AddMapping <OrderMap>();
        hibernateConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());

        BusConfiguration busConfiguration = new BusConfiguration();

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

        #region ReceiverConfiguration

        var persistence = busConfiguration.UsePersistence <NHibernatePersistence>();
        persistence.RegisterManagedSessionInTheContainer();
        persistence.UseConfiguration(hibernateConfig);
        persistence.UseSubscriptionStorageConfiguration(CreateBasicNHibernateConfig());
        persistence.UseTimeoutStorageConfiguration(CreateBasicNHibernateConfig());
        persistence.DisableSchemaUpdate();

        busConfiguration.EnableOutbox();

        SettingsHolder settingsHolder = busConfiguration.GetSettings();
        settingsHolder.Set("NHibernate.Timeouts.AutoUpdateSchema", true);
        settingsHolder.Set("NHibernate.Subscriptions.AutoUpdateSchema", true);

        #endregion

        #region ReplaceOpenSqlConnection

        busConfiguration.Pipeline.Replace("OpenSqlConnection", typeof(MultiTenantOpenSqlConnectionBehavior));

        #endregion

        #region RegisterPropagateTenantIdBehavior

        busConfiguration.Pipeline.Register <PropagateTenantIdBehavior.Registration>();

        #endregion

        busConfiguration.DisableFeature <SecondLevelRetries>();

        #region CreateSchema

        IStartableBus startableBus = Bus.Create(busConfiguration);

        CreateSchema(hibernateConfig, "A");
        CreateSchema(hibernateConfig, "B");

        #endregion

        #region CapturePipelineExecutor

        PipelineExecutor = ((UnicastBus)startableBus).Builder.Build <PipelineExecutor>();

        #endregion

        using (startableBus.Start())
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
    }
예제 #38
0
    static async Task Main()
    {
        Console.Title = Title;

        var endpointConfiguration = new EndpointConfiguration(Title);

        endpointConfiguration.UseSerialization <NewtonsoftSerializer>();

        // Transport

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

        transport.ConnectionString(TransportConnectionString);

        // Persistence

        var hibernateConfig = new Configuration();

        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionString = PersistenceConnectionString;
            x.Dialect <MsSql2012Dialect>();
        });
        endpointConfiguration.UsePersistence <NHibernatePersistence>().UseConfiguration(hibernateConfig);

        endpointConfiguration.EnableOutbox();

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

        // Dependency injection registrations

        endpointConfiguration.RegisterComponents(registration: x =>
        {
            x.ConfigureComponent <OrderRepository>(DependencyLifecycle.InstancePerUnitOfWork);
            x.ConfigureComponent <StorageContext>(DependencyLifecycle.InstancePerUnitOfWork);
        });

        // Pipeline

        endpointConfiguration.Pipeline.Register <StorageContextBehavior.Registration>();

        endpointConfiguration.EnableInstallers();


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

        try
        {
            Console.WriteLine("Press ESC key to exit, any other key to send message");

            while (Console.ReadKey().Key != ConsoleKey.Escape)
            {
                Console.WriteLine("Sending message...");
                var orderSubmitted = new OrderSubmitted
                {
                    OrderId = Guid.NewGuid(),
                    Value   = DateTime.UtcNow.ToLongTimeString()
                };
                await endpointInstance.SendLocal(orderSubmitted)
                .ConfigureAwait(false);
            }
        }
        finally
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
예제 #39
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SQLNHibernateOutbox.Receiver";
        #region NHibernate

        var hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionString = ConnectionStrings.NserviceBusConnection;
            x.Dialect <MsSql2012Dialect>();
        });

        var outBoxhibernateConfig = new NHibernate.Cfg.Configuration();
        outBoxhibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionString = ConnectionStrings.BusuinessConnection;
            x.Dialect <MsSql2012Dialect>();
        });
        outBoxhibernateConfig.SetProperty("default_schema", "dbo");
        #endregion

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

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


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


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

        var outboxpersistence = endpointConfiguration.UsePersistence <NHibernatePersistence, StorageType.Outbox>();
        outboxpersistence.UseConfiguration(outBoxhibernateConfig);

        var sagaPersistence = endpointConfiguration.UsePersistence <NHibernatePersistence, StorageType.Sagas>();
        sagaPersistence.UseConfiguration(outBoxhibernateConfig);

        var outboxEnabled = true;
        EnableOutbox(endpointConfiguration, outboxEnabled);

        #endregion

        #region RetriesConfiguration

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

        #endregion

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

        var kernel = new StandardKernel();
        kernel.Bind <IOrderRepository>()
        .To <OrderRepository>();
        kernel.Bind <IOrderRepository2>()
        .To <OrderRepository2>();

        if (outboxEnabled)
        {
            kernel.Bind <IDbContextProvider>().To <NsbDbContextProvider>();
        }

        endpointConfiguration.UseContainer <NinjectBuilder>(
            customizations: customizations =>
        {
            customizations.ExistingKernel(kernel);
        });

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

        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
예제 #40
0
 /// <summary>
 /// To be implemented by subclasses that want to to register further mappings
 /// on the Configuration object after this FactoryObject registered its specified
 /// mappings.
 /// </summary>
 /// <remarks>
 /// Invoked <i>before</i> the <code>BuildMappings</code> call,
 /// so that it can still extend and modify the mapping information.
 /// </remarks>
 /// <param name="config">the current Configuration object</param>
 protected virtual void PostProcessMappings(Configuration config)
 {
 }
예제 #41
0
        /// <summary>
        /// Initialize the SessionFactory for the given or the
        /// default location.
        /// </summary>
        public virtual void AfterPropertiesSet()
        {
            // Create Configuration instance.
            Configuration config = NewConfiguration();

            if (this.dbProvider != null)
            {
                config.SetProperty(Environment.ConnectionString, dbProvider.ConnectionString);
                config.SetProperty(Environment.ConnectionProvider, typeof(DbProviderWrapper).AssemblyQualifiedName);
                configTimeDbProvider = this.dbProvider;
            }

            if (ExposeTransactionAwareSessionFactory)
            {
                // Set ICurrentSessionContext implementation,
                // providing the Spring-managed ISession s current Session.
                // Can be overridden by a custom value for the corresponding Hibernate property
                config.SetProperty(Environment.CurrentSessionContextClass, typeof(SpringSessionContext).AssemblyQualifiedName);
            }

            if (this.entityInterceptor != null)
            {
                // Set given entity interceptor at SessionFactory level.
                config.SetInterceptor(this.entityInterceptor);
            }

            if (this.namingStrategy != null)
            {
                // Pass given naming strategy to Hibernate Configuration.
                config.SetNamingStrategy(this.namingStrategy);
            }

#if NH_2_1
            if (this.typeDefinitions != null)
            {
                // Register specified Hibernate type definitions.
                IDictionary <string, string> typedProperties = new  Dictionary <string, string>();
                foreach (DictionaryEntry entry in hibernateProperties)
                {
                    typedProperties.Add((string)entry.Key, (string)entry.Value);
                }

                Dialect  dialect  = Dialect.GetDialect(typedProperties);
                Mappings mappings = config.CreateMappings(dialect);
                for (int i = 0; i < this.typeDefinitions.Length; i++)
                {
                    IObjectDefinition           typeDef       = this.typeDefinitions[i];
                    Dictionary <string, string> typedParamMap = new Dictionary <string, string>();
                    foreach (DictionaryEntry entry in typeDef.PropertyValues)
                    {
                        typedParamMap.Add((string)entry.Key, (string)entry.Value);
                    }
                    mappings.AddTypeDef(typeDef.ObjectTypeName, typeDef.ObjectTypeName, typedParamMap);
                }
            }
#endif

            if (this.filterDefinitions != null)
            {
                // Register specified NHibernate FilterDefinitions.
                for (int i = 0; i < this.filterDefinitions.Length; i++)
                {
                    config.AddFilterDefinition(this.filterDefinitions[i]);
                }
            }

#if NH_2_1
            // check whether proxy factory has been initialized
            if (config.GetProperty(Environment.ProxyFactoryFactoryClass) == null &&
                (hibernateProperties == null || !hibernateProperties.Contains(Environment.ProxyFactoryFactoryClass)))
            {
                // nothing set by user, lets use Spring.NET's proxy factory factory
                #region Logging
                if (log.IsInfoEnabled)
                {
                    log.Info("Setting proxy factory to Spring provided one as user did not specify any");
                }
                #endregion
                config.Properties.Add(
                    Environment.ProxyFactoryFactoryClass, typeof(Bytecode.ProxyFactoryFactory).AssemblyQualifiedName);
            }
#endif

            if (this.hibernateProperties != null)
            {
                if (config.GetProperty(Environment.ConnectionProvider) != null &&
                    hibernateProperties.Contains(Environment.ConnectionProvider))
                {
                    #region Logging
                    if (log.IsInfoEnabled)
                    {
                        log.Info("Overriding use of Spring's Hibernate Connection Provider with [" +
                                 hibernateProperties[Environment.ConnectionProvider] + "]");
                    }
                    #endregion
                    config.Properties.Remove(Environment.ConnectionProvider);
                }

                Dictionary <string, string> genericHibernateProperties = new Dictionary <string, string>();
                foreach (DictionaryEntry entry in hibernateProperties)
                {
                    genericHibernateProperties.Add((string)entry.Key, (string)entry.Value);
                }
                config.AddProperties(genericHibernateProperties);
            }
            if (this.mappingAssemblies != null)
            {
                foreach (string assemblyName in mappingAssemblies)
                {
                    config.AddAssembly(assemblyName);
                }
            }

            if (this.mappingResources != null)
            {
                IResourceLoader loader = this.ResourceLoader;
                if (loader == null)
                {
                    loader = this.applicationContext;
                }
                foreach (string resourceName in mappingResources)
                {
                    config.AddInputStream(loader.GetResource(resourceName).InputStream);
                }
            }

            if (configFilenames != null)
            {
                foreach (string configFilename in configFilenames)
                {
                    config.Configure(configFilename);
                }
            }

#if NH_2_1
            // Tell Hibernate to eagerly compile the mappings that we registered,
            // for availability of the mapping information in further processing.
            PostProcessMappings(config);
            config.BuildMappings();

            if (this.entityCacheStrategies != null)
            {
                // Register cache strategies for mapped entities.
                foreach (string className in this.entityCacheStrategies.Keys)
                {
                    String[] strategyAndRegion = StringUtils.CommaDelimitedListToStringArray(this.entityCacheStrategies.GetProperty(className));
                    if (strategyAndRegion.Length > 1)
                    {
                        config.SetCacheConcurrencyStrategy(className, strategyAndRegion[0], strategyAndRegion[1]);
                    }
                    else if (strategyAndRegion.Length > 0)
                    {
                        config.SetCacheConcurrencyStrategy(className, strategyAndRegion[0]);
                    }
                }
            }

            if (this.collectionCacheStrategies != null)
            {
                // Register cache strategies for mapped collections.
                foreach (string collRole in collectionCacheStrategies.Keys)
                {
                    string[] strategyAndRegion = StringUtils.CommaDelimitedListToStringArray(this.collectionCacheStrategies.GetProperty(collRole));
                    if (strategyAndRegion.Length > 1)
                    {
                        throw new Exception("Collection cache concurrency strategy region definition not supported yet");
                        //config.SetCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0], strategyAndRegion[1]);
                    }
                    else if (strategyAndRegion.Length > 0)
                    {
                        config.SetCollectionCacheConcurrencyStrategy(collRole, strategyAndRegion[0]);
                    }
                }
            }
#endif

            if (this.eventListeners != null)
            {
                // Register specified NHibernate event listeners.
                foreach (DictionaryEntry entry in eventListeners)
                {
                    ListenerType listenerType;
                    try
                    {
                        listenerType = (ListenerType)Enum.Parse(typeof(ListenerType), (string)entry.Key);
                    }
                    catch
                    {
                        throw new ArgumentException(string.Format("Unable to parse string '{0}' as valid {1}", entry.Key, typeof(ListenerType)));
                    }

                    object listenerObject = entry.Value;
                    if (listenerObject is ICollection)
                    {
                        ICollection    listeners        = (ICollection)listenerObject;
                        EventListeners listenerRegistry = config.EventListeners;

                        // create the array and check that types are valid at the same time
                        ArrayList items         = new ArrayList(listeners);
                        object[]  listenerArray = (object[])items.ToArray(listenerRegistry.GetListenerClassFor(listenerType));
                        config.SetListeners(listenerType, listenerArray);
                    }
                    else
                    {
                        config.SetListener(listenerType, listenerObject);
                    }
                }
            }

            // Perform custom post-processing in subclasses.
            PostProcessConfiguration(config);

#if NH_2_1
            if (BytecodeProvider != null)
            {
                // set custom IBytecodeProvider
                Environment.BytecodeProvider = BytecodeProvider;
            }
            else
            {
                // use Spring's as default
                // Environment.BytecodeProvider = new Bytecode.BytecodeProvider(this.applicationContext);
            }
#endif

            // Build SessionFactory instance.
            log.Info("Building new Hibernate SessionFactory");
            this.configuration  = config;
            this.sessionFactory = NewSessionFactory(config);

            AfterSessionFactoryCreation();

            // set config time DB provider back to null
            configTimeDbProvider = null;
        }
예제 #42
0
 protected ReadModel(ReadModelConnectionString connectionString)
 {
     _configuration = buildConfig(connectionString);
 }
예제 #43
0
파일: Fixture.cs 프로젝트: jrauber/GH1429
 protected override void Configure(NHibernate.Cfg.Configuration configuration)
 {
     configuration.SetProperty(Environment.FormatSql, "false");
 }
예제 #44
0
        public static NHibernate.ISessionFactory BuildSessionFactory(
            string connectionString,
            bool useCache,
            bool useUnitTest = false)
        {
            var mapper = new PostgresNamingConventionAutomapper(useCache); //  NHibernate.Mapping.ByCode.ConventionModelMapper();


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


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

                c.ConnectionString = connectionString;

                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;

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


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



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

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

            cfg.AddMapping(mapping);



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



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

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


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

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


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


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

            var sf = cfg.BuildSessionFactory();


            return(sf);
        }
 protected override void Configure(NHibernate.Cfg.Configuration configuration)
 {
     configuration.LinqToHqlGeneratorsRegistry <MyLinqToHqlGeneratorsRegistry>();
 }
예제 #46
0
 static SessionProvider()
 {
     configuration  = new NHibernate.Cfg.Configuration().Configure();
     sessionFactory = configuration.BuildSessionFactory();
 }
예제 #47
0
 protected virtual void AlterConfiguration(Configuration config)
 {
 }
예제 #48
0
 /// <summary>
 /// To be implemented by subclasses that want to to perform custom
 /// post-processing of the Configuration object after this FactoryObject
 /// performed its default initialization.
 /// </summary>
 /// <param name="config">The current configuration object.</param>
 protected virtual void PostProcessConfiguration(Configuration config)
 {
 }
예제 #49
0
        public static NHibernate.ISessionFactory BuildSessionFactory(bool useUnitTest = false)
        {
            var mapper = new NHibernate.Mapping.ByCode.ConventionModelMapper();


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

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

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



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


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

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

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


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



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

            cfg.AddMapping(mapping);


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



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

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


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

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



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



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


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


            var sf = cfg.BuildSessionFactory();



            return(sf);
        }
        /// <summary>
        /// Main NHibernate configuration method.
        /// It configures NHibernate in an opinionated way, with an option to override various small NHibernate settings by overriding
        /// other virtual methods.
        /// This method can be overridden to completely customize NHibernate configuration.
        /// </summary>
        /// <param name="shouldMapDtos">See the constructor</param>
        /// <param name="configurationFileName">See the constructor</param>
        /// <param name="connectionString">See the constructor</param>
        /// <param name="sessionFactory">NHibernate session factory</param>
        /// <param name="configuration">NHibernate configuration</param>
        protected virtual void ConfigureNhibernate(
            bool shouldMapDtos,
            string configurationFileName,
            string connectionString,
            out ISessionFactory sessionFactory,
            out Configuration configuration
            )
        {
            configuration = new Configuration();
            if (string.IsNullOrWhiteSpace(configurationFileName))
            {
                configuration.Configure();
            }
            else
            {
                configuration.Configure(configurationFileName);
            }

            var assembliesToMap = GetAssembliesToMap();
            var isTypeDto       = GetIsTypeDtoFunc();

            var autoPersistenceModel = AutoMap.Assemblies(
                GetAutomappingConfiguration(shouldMapDtos, isTypeDto),
                assembliesToMap
                );

            GetIncludeBaseTypes().Each(x => autoPersistenceModel.IncludeBase(x));
            GetIgnoreBaseTypes().Each(x => autoPersistenceModel.IgnoreBase(x));
            assembliesToMap.Each(x => autoPersistenceModel.UseOverridesFromAssembly(x));

            _configureConventions();

            configuration.SetNamingStrategy(GetNamingStrategy());

            var fluentConfiguration = Fluently.Configure(configuration)
                                      .Mappings(x =>
            {
                var mappingsContainer            = x.AutoMappings.Add(autoPersistenceModel);
                var exportNhibernateMappingsPath = GetExportNhibernateMappingsPath();
                if (!string.IsNullOrWhiteSpace(exportNhibernateMappingsPath))
                {
                    mappingsContainer.ExportTo(exportNhibernateMappingsPath);
                }
            });

            if (!string.IsNullOrWhiteSpace(connectionString))
            {
                configuration.SetProperty(Environment.ConnectionString, connectionString);
            }

            AdditionalConfiguration(configuration);

            sessionFactory = fluentConfiguration.BuildSessionFactory();

            void _configureConventions()
            {
                if (ShouldUseDefaultConventions())
                {
                    DisableLazyLoadForDtosConvention.Initialize(isTypeDto);
                    HasManyConvention.Initialize(
                        GetCollectionCascadeInstanceAction(),
                        GetBackingFieldNameFromPropertyNameFunc(),
                        GetCollectionInstanceAccessAction()
                        );
                    PrimaryKeyConvention.Initialize(GetIdentityHiLoMaxLo());

                    var disabledConventions = GetDisabledConventions();
                    var conventionTypes     = Assembly.GetExecutingAssembly().GetTypes()
                                              .Where(type => typeof(IConvention).IsAssignableFrom(type) &&
                                                     !type.IsInterface &&
                                                     !disabledConventions.Contains(type))
                                              .ToList();

                    conventionTypes.Each(conventionType => autoPersistenceModel.Conventions.Add(conventionType));
                }

                GetAssembliesWithAdditionalConventions().Each(assembly => autoPersistenceModel.Conventions.AddAssembly(assembly));
                GetAdditionalConventions().Each(conventionType => autoPersistenceModel.Conventions.Add(conventionType));
            }
        }
예제 #51
0
        public virtual EndpointConfiguration BuildConfig()
        {
            GCSettings.LatencyMode = GCLatencyMode.Batch; // https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/latency
            ServicePointManager.Expect100Continue      = false;
            ServicePointManager.UseNagleAlgorithm      = false;
            ServicePointManager.DefaultConnectionLimit = 125; // Querying of DefaultConnectionLimit on dotnet core does not return assigned value
            //logger
            ConfigureNsbLogger();

            //endpoint name
            if (string.IsNullOrEmpty(_configEndpointName))
            {
                throw new ArgumentNullException(_configEndpointName, "Endpoint name cannot be null");
            }

            var endpointConfiguration = new EndpointConfiguration(_configEndpointName);

            endpointConfiguration.LimitMessageProcessingConcurrencyTo(Environment.ProcessorCount * 4);

            if (_isSendOnly)
            {
                endpointConfiguration.SendOnly();
            }

            //Transport
            var transportType = TransportType.Sqs;

            //serializer
            endpointConfiguration.UseSerialization <XmlSerializer>();

            var connectionString = "Server=.;Initial Catalog=support/20180629;Integrated Security=True";
            var persistence      = endpointConfiguration.UsePersistence <NHibernatePersistence>();
            var nhConfig         = new NHibernate.Cfg.Configuration();

            nhConfig.SetProperty(NHibernate.Cfg.Environment.ConnectionProvider, typeof(NHibernate.Connection.DriverConnectionProvider).FullName);
            nhConfig.SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, typeof(NHibernate.Driver.Sql2008ClientDriver).FullName);
            nhConfig.SetProperty(NHibernate.Cfg.Environment.Dialect, typeof(NHibernate.Dialect.MsSql2012Dialect).FullName);
            nhConfig.SetProperty(NHibernate.Cfg.Environment.ConnectionString, connectionString);
            nhConfig.SetProperty(NHibernate.Cfg.Environment.DefaultSchema, "dbo");

            persistence.UseConfiguration(nhConfig);
            persistence.EnableCachingForSubscriptionStorage(TimeSpan.FromSeconds(10));

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

            switch (transportType)
            {
            case TransportType.Sql:
            {
                var transport = endpointConfiguration.UseTransport <SqlServerTransport>();
                transport.ConnectionString(connectionString);
                transport.DefaultSchema("dbo");
                transport.Transactions(TransportTransactionMode.ReceiveOnly);
                BuildEndpointSQLRouting(transport.Routing());
                break;
            }

            case TransportType.Sqs:
            {
                var region       = RegionEndpoint.EUWest1;
                var S3BucketName = "ramon-sqs";
                var S3KeyPrefix  = "support/20180629";


                var transport = endpointConfiguration.UseTransport <SqsTransport>();
                transport.ClientFactory(() => new AmazonSQSClient(
                                            new AmazonSQSConfig
                    {
                        RegionEndpoint = region,
                        MaxErrorRetry  = 2,
                    }));

                var s3Configuration = transport.S3(S3BucketName, S3KeyPrefix);
                s3Configuration.ClientFactory(() => new AmazonS3Client(
                                                  new AmazonS3Config
                    {
                        RegionEndpoint = region
                    }));

                //Routing
                BuildEndpointSQSRouting(transport.Routing());
                transport.QueueNamePrefix("ramon-support-20180629-");
                break;
            }

            case TransportType.Learning:
            {
                endpointConfiguration.UsePersistence <LearningPersistence>();
                var transport = endpointConfiguration.UseTransport <LearningTransport>();
                endpointConfiguration.DisableFeature <TimeoutManager>();        // REVIEW: Why are you disabling the timeout manager??
                BuildEndpointLearningRouting(transport.Routing());
                break;
            }

            default:
                throw new Exception("Unexpected Case");
            }


            //Auto installer
            //#if DEBUG
            endpointConfiguration.EnableInstallers();
            //#else
            //           endpointConfiguration.DisableInstallers();
            //#endif


            var performanceCounters = endpointConfiguration.EnableWindowsPerformanceCounters();

            performanceCounters.EnableSLAPerformanceCounters(TimeSpan.FromSeconds(100));


            return(endpointConfiguration);
        }
 /// <summary>
 /// Override this method to add additional configuration. Can be used to set interceptors, etc.
 /// </summary>
 /// <param name="configuration">Configuration instance</param>
 protected virtual void AdditionalConfiguration(Configuration configuration)
 {
 }
예제 #53
0
        public static ISessionFactory GetSessionFactory(string connectionKey, params Assembly[] assemblies)
        {
            var cfg  = new NHibernate.Cfg.Configuration();
            var sett = Alma.Common.Config.Settings;
            var conn = sett.GetConnectionString(connectionKey);

            switch (conn.Provider)
            {
            case DBMS.MsSql:

                cfg.DataBaseIntegration(db =>
                {
                    db.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
                    db.Dialect <NHibernate.Dialect.MsSql2008Dialect>();
                    //db.Driver<DriverSqlClient>();
                    db.Driver <NHibernate.Driver.SqlClientDriver>();
                    db.ConnectionString = conn.ConnectionString;
                    db.ConnectionProvider <ConnectionProvider>();
                    db.PrepareCommands = sett.PrepareCommands;

                    db.LogFormattedSql = true;
                    db.LogSqlInConsole = false;
                    if (sett.IsolationLevel != null)
                    {
                        db.IsolationLevel = sett.IsolationLevel.Value;
                    }
                    //UseReflectionOptimizer
                });

                break;

            case DBMS.SqLite:
                cfg.DataBaseIntegration(db =>
                {
                    db.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
                    db.Dialect <NHibernate.Dialect.SQLiteDialect>();
                    //db.Driver<DriverSQLite20>();
                    db.Driver <NHibernate.Driver.SQLite20Driver>();
                    db.ConnectionString = conn.ConnectionString;
                    db.ConnectionProvider <ConnectionProvider>();
                    db.PrepareCommands = sett.PrepareCommands;
                    db.LogFormattedSql = true;
                    db.LogSqlInConsole = false;
                    if (sett.IsolationLevel != null)
                    {
                        db.IsolationLevel = sett.IsolationLevel.Value;
                    }
                    //UseReflectionOptimizer
                });
                break;

            case DBMS.Oracle:
                cfg.DataBaseIntegration(db =>
                {
                    db.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
                    db.Dialect <NHibernate.Dialect.Oracle10gDialect>();
                    if (true /* isManagedOracle */)
                    {
                        db.Driver <NHibernate.Driver.OracleManagedDataClientDriver>();
                    }
                    //else
                    //    db.Driver<NHibernate.Driver.OracleDataClientDriver>();
                    db.ConnectionString = conn.ConnectionString;
                    db.ConnectionProvider <ConnectionProvider>();
                    db.PrepareCommands = sett.PrepareCommands;
                    db.LogFormattedSql = true;
                    db.LogSqlInConsole = false;
                    if (sett.IsolationLevel != null)
                    {
                        db.IsolationLevel = sett.IsolationLevel.Value;
                    }
                    db.Batcher <OracleLoggingBatchingBatcherFactory>();
                    //UseReflectionOptimizer
                });
                break;

            case DBMS.MySql:

                cfg.DataBaseIntegration(db =>
                {
                    db.ConnectionProvider <NHibernate.Connection.DriverConnectionProvider>();
                    db.Dialect <NHibernate.Dialect.MySQL55Dialect>();
                    //db.Driver<DriverMySql>();
                    db.Driver <NHibernate.Driver.MySqlDataDriver>();
                    db.ConnectionString = conn.ConnectionString;
                    db.ConnectionProvider <ConnectionProvider>();
                    db.PrepareCommands = sett.PrepareCommands;
                    db.LogFormattedSql = true;
                    db.LogSqlInConsole = false;
                    if (sett.IsolationLevel != null)
                    {
                        db.IsolationLevel = sett.IsolationLevel.Value;
                    }
                    //UseReflectionOptimizer
                });

                break;

            default:
                throw new NotImplementedException("Not implemented provider: " + conn.Provider);
            }

            if (sett.Logging.Enable)
            {
                cfg.SessionFactory()
                .GenerateStatistics();
            }

            var types =
                assemblies.SelectMany(a => a.GetTypes());

            AddFilters(cfg, types);

            AddEvents(cfg, types);

            AddMappings(cfg, types);

            try
            {
                var fact = cfg.BuildSessionFactory();
                return(fact);
            }
            catch (HibernateException ex)
            {
                if (ex.Message.Contains("NHibernate.Driver") && (conn.Provider == DBMS.Oracle))
                {
                    throw new System.Configuration.ConfigurationErrorsException(
                              @"Cannot find Oracle.DataAcces or Oracle.ManagedDataAccess binaries in GAC or working directory. 

Minimum Unmanaged Version: Oracle Client 11.2 with ODP.NET if using Full Framework 4.0/4.5. 
Remove all installed versions and install the required version and try again.", ex);
                }
                else
                {
                    throw;
                }
            }
        }
예제 #54
0
 protected void RegisterEntityCaches(NHibernate.Cfg.Configuration configuration)
 {
     //xconfiguration.EntityCache<AgentStatusType>(eccp => eccp.Strategy = EntityCacheUsage.ReadWrite);
     //configuration.EntityCache<TermStyle>(eccp => eccp.Strategy = EntityCacheUsage.ReadWrite);
 }
예제 #55
0
파일: Fixture.cs 프로젝트: jrauber/GH1429
 protected override void Configure(NHibernate.Cfg.Configuration configuration)
 {
     // needed to be sure of StaleStateException that the user has reported in the issue
     configuration.DataBaseIntegration(x => x.BatchSize = 1);
 }
예제 #56
0
 private static void InitializeSearch(NHibernate.Cfg.Configuration configuration)
 {
     configuration.SetListener(ListenerType.PostUpdate, new AuditEventListener());
     configuration.SetListener(ListenerType.PostInsert, new AuditEventListener());
     configuration.SetListener(ListenerType.PostDelete, new AuditEventListener());
 }
예제 #57
0
 private void AppSpecificConfiguration(NHibernate.Cfg.Configuration configuration)
 {
     MrCMSApp.AppendAllAppConfiguration(configuration);
 }
 public override void Configure(NHibernate.Cfg.Configuration configuration)
 {
     Add(new ChildObjectMap());
     Add(new OneToManyTargetMap());
     base.Configure(configuration);
 }
예제 #59
0
        protected virtual void TreatConfiguration(NHConfig.Configuration configuration)
        {
            var update = new SchemaUpdate(configuration);

            update.Execute(false, true);
        }
예제 #60
0
        static void Main(string[] args)
        {
            IApplicationContext context = new XmlApplicationContext("IrcBot-applicationContext.xml");

            XmlConfigurator.Configure(new System.IO.FileInfo("log4net.xml"));

            botResponders = (List <Responder>)context.GetObject("responderList");
            pollers       = (List <Poller>)context.GetObject("pollerList");
            managers      = (Dictionary <String, AbstractManager>)context.GetObject("managers");
            connection    = ((IrcConnectionManager)getManager(IrcConnectionManager.MANAGER_NAME)).connection;
            CHANNEL       = (String)context.GetObject("IrcChannel");

            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.Configure();
            config.AddAssembly(typeof(User).Assembly);
            ISessionFactory sessionFactory = config.BuildSessionFactory();

            //var schema = new SchemaExport(config);
            //schema.Create(true, true);
            mySession = sessionFactory.OpenSession();
            List <User> savedUsers = (List <User>)mySession.CreateCriteria <User>().List <User>();

            users.AddRange(savedUsers);

            //Start pollers

            //set the channel and connection objects.
            foreach (Poller poller in pollers)
            {
                poller.connection = connection;
                poller.channel    = CHANNEL;
            }
            pollerManager = new PollerManager(pollers);


            log.Debug("Starting Skill Enumeration");
            skillList = getSkillList();
            foreach (SkillTree.Skill skill in skillList)
            {
                try
                {
                    skillIds.Add(skill.TypeName.ToLower(), skill.TypeId);
                }
                catch (ArgumentException ae)
                {
                    log.Warn("Argument exception: " + ae.Message);
                }
            }

            foreach (User user in users)
            {
                log.Debug("Adding user " + user.userName);
                nickDict.Add(user.userName, user);
            }
            string inputLine;

            while (true)
            {
                try {
                    PingSender ping = new PingSender(connection);
                    ping.setServer(connection.server);
                    ping.start();

                    ActionThread actionThread = new ActionThread();
                    actionThread.start();

                    connection.joinChannel(CHANNEL);

                    connection.privmsg(CHANNEL, "Reporting for duty!");
                    ArrayList results = new ArrayList();

                    while (true)
                    {
                        while ((inputLine = connection.ReadLine()) != null)
                        {
                            inputQueue.Enqueue(inputLine);
                        }
                    }
                }
                catch (Exception e) {
                    log.Error("Caught exception in operation: " + e.Message);
                    Thread.Sleep(5000);

                    string[] argv = { };
                }
            }
        }