Beispiel #1
0
        static void Main(string[] args)
        {
            var iconFolderPath = ConfigurationManager.AppSettings["iconPath"];
            var dbFile = ConfigurationManager.AppSettings["dbPath"];

            var cfg = new NHibernate.Cfg.Configuration().Configure();
            var sessionFactory = cfg.BuildSessionFactory();

            using (var session = sessionFactory.OpenSession())
            {
                using (var tx = session.BeginTransaction())
                {
                    Console.WriteLine("Building database tables");
                    new SchemaExport(cfg).Execute(false, true, false, session.Connection, null);
                    tx.Commit();
                }
                Console.WriteLine("Parsing XML in to memory database");
                new Schedule(ScheduleFile, iconFolderPath).Export(session);
            }
            Console.WriteLine("Saving memory database to disk");

            var tmpFile = Path.GetTempFileName();
            new BulkCopy(cfg, sessionFactory).Export(tmpFile, true);
            PersistentConnectionProvider.CloseDatabase();
            Console.WriteLine("Copying from temporary disk location to production.");
            File.Copy(tmpFile, dbFile, true);
            File.Delete(tmpFile);
            Console.WriteLine("All done. Press any key.");
            Console.ReadKey();
        }
Beispiel #2
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            var configuration = new NHibernate.Cfg.Configuration();
            configuration.Configure();
            configuration.AddAssembly(typeof(doCS.Models.Project).Assembly);
            SessionFactory = configuration.BuildSessionFactory();

            // Build up your application container and register your dependencies.
            var builder = new ContainerBuilder();
            builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly());
            builder.Register(x => SessionFactory.OpenSession()).As<ISession>().HttpRequestScoped();
            builder.RegisterType<doCS.Web.Helpers.Implimentation.ProjectContext>().As<doCS.Web.Helpers.IProjectContext>().HttpRequestScoped();

            //register extractor helpers
            builder.RegisterType<doCS.Web.Helpers.Implimentation.Extractor.ExtractorHelper>().As<doCS.Web.Helpers.IExtractorHelper>().HttpRequestScoped();
            builder.RegisterType<doCS.Web.Helpers.Implimentation.Extractor.ProjectUpdaterProvider>().InstancePerDependency();

            //register extractor dependencies
            builder.RegisterType<doCS.Extractor.Implementation.Extractor>().As<doCS.Extractor.IExtractor>().HttpRequestScoped();
            builder.RegisterType<doCS.Extractor.Implementation.DllExtractor>();
            builder.RegisterType<doCS.Extractor.Implementation.XmlExtractor>();

            //register view helpers
            builder.RegisterType<doCS.Web.ViewHelpers.XmlDocumentationHelper>();

            _containerProvider = new ContainerProvider(builder.Build());
            ControllerBuilder.Current.SetControllerFactory(new AutofacControllerFactory(ContainerProvider));

            SetupAutoMapper();
        }
 private static void AddListeners(Configuration configuration)
 {
     Configuration = configuration;
     var timeStampListener = new TimeStampListener();
     configuration.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] {timeStampListener};
     configuration.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] {timeStampListener};
 }
        /// <summary>
        /// Builds an NHibernate session factory instance.
        /// </summary>
        /// <returns>
        /// An NHibernate session factory.
        /// </returns>
        /// <exception cref="Exception">An error occurred while configuring the database connection.</exception>
        public ISessionFactory Build()
        {
            ISessionFactory sessionFactory = null;

            try
            {
                sessionFactory = Fluently.Configure()
                    .Database(MsSqlConfiguration.MsSql2008.ConnectionString("Server=ZIRCON;Database=NHibernateExample;Trusted_Connection=True;"))
                    .Mappings(m => { m.FluentMappings.AddFromAssemblyOf<Blog>(); })
                    .ExposeConfiguration(config =>
                    {
                        Configuration = config;
                        new SchemaExport(config).Execute(true, true, false);
                    })
                    .Diagnostics(d => d.Enable()).BuildSessionFactory();
            }
            catch (Exception ex)
            {
                throw new Exception("An error occurred while configuring the database connection.", ex);
            }

            NHibernateProfiler.Initialize();

            return sessionFactory;
        }
Beispiel #5
0
 private static void BuildSchema(Configuration config)
 {
     // this NHibernate tool takes a configuration (with mapping info in)
     // and exports a database schema from it
     new SchemaExport(config)
             .Create(true, true);
 }
 /// <summary>
 /// Standar Configuration for tests.
 /// </summary>
 /// <returns>The configuration using merge between App.Config and hibernate.cfg.xml if present.</returns>
 public static NHibernate.Cfg.Configuration GetDefaultConfiguration()
 {
     NHibernate.Cfg.Configuration result = new NHibernate.Cfg.Configuration();
     if (hibernateConfigFile != null)
         result.Configure(hibernateConfigFile);
     return result;
 }
 public void Init()
 {
     //StudentController studentController = (StudentController)Session["studentController"];
     var cfg = new NHibernate.Cfg.Configuration().Configure("hibernate.cfg.xml");
     sessionFactory = cfg.BuildSessionFactory();
     studentController = new StudentController(sessionFactory);
 }
        /// <summary>
        /// Builds the session factory with the given properties. Database is updated if updateSchema is set
        /// </summary>
        /// <param name="nhibernateProperties"></param>
        /// <param name="updateSchema"></param>
        /// <returns></returns>
        public ISessionFactory Build(IDictionary<string, string> nhibernateProperties, bool updateSchema)
        {
            var scannedAssemblies = typesToScan.Select(t => t.Assembly).Distinct();

              var nhibernateConfiguration = new Configuration().SetProperties(nhibernateProperties);

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

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

              HackIdIntoMapping(mapping);

              nhibernateConfiguration.AddMapping(mapping.Compile());

              ApplyDefaultsTo(nhibernateConfiguration);

              if (updateSchema)
            UpdateDatabaseSchemaUsing(nhibernateConfiguration);

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

            throw;
              }
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            var configuration = new Configuration()
                .SetProperty(Environment.ReleaseConnections, "on_close")
                .SetProperty(Environment.Dialect, typeof(MsSql2008Dialect).AssemblyQualifiedName)
                .SetProperty(Environment.ConnectionDriver, typeof(SqlClientDriver).AssemblyQualifiedName)
                .SetProperty(Environment.ConnectionString, ConfigurationManager.ConnectionStrings["db"].ToString())
                .SetProperty(Environment.ProxyFactoryFactoryClass, typeof(NHibernate.ByteCode.Castle.ProxyFactoryFactory).AssemblyQualifiedName);

            configuration.AddAssembly(typeof(Blog).Assembly);

            SessionManager.Init(configuration, new SingleSessionStorage());

            var session = SessionManager.Current;

            new SchemaExport(configuration).Execute(false, true, false, session.Connection, null);

            if (args.Count() > 0)
            {
                if (string.Compare(args[0], "/DEMODATA", StringComparison.InvariantCultureIgnoreCase) == 0)
                {

                    DemoData.SetupData(session);
                }
            }
        }
        public NHibernateConfigurator()
        {
            string conectionString = ConfigurationManager.ConnectionStrings.Cast<ConnectionStringSettings>().Last().ConnectionString;

            var configurationProperties = new Dictionary<string, string>
                {
                    {NHibernate.Cfg.Environment.Dialect, typeof (NHibernate.Dialect.PostgreSQL82Dialect).FullName},
                    {NHibernate.Cfg.Environment.ConnectionDriver, typeof (NHibernate.Driver.NpgsqlDriver).FullName},
                    {NHibernate.Cfg.Environment.ConnectionString, conectionString},
                };

            var assemblyWithEntities = Assembly.GetExecutingAssembly();

            var serializer = HbmSerializer.Default;
            serializer.Validate = true;

            MemoryStream hbmStream = serializer.Serialize(assemblyWithEntities);
            string hbmXml;
            using (var reader = new StreamReader(hbmStream))
            {
                hbmXml = reader.ReadToEnd();
            }

            var config = new Configuration()
                .SetProperties(configurationProperties)
                .Configure()  // add properties from app.config
                .AddXml(hbmXml);

            SessionFactory = config.BuildSessionFactory();
        }
        public void configTest()
        {
            var cfg = new NHibernate.Cfg.Configuration().Configure("hibernate.cfg.xml");
            using (ISessionFactory sessionFactory = cfg.BuildSessionFactory()) {

            }
        }
        protected NhibernateConfigurator(bool mapDtoAssembly)
        {
            var assembliesToMap = GetAssembliesToMap(mapDtoAssembly);
            var includeBaseTypes = GetIncludeBaseTypes();
            var ignoreBaseTypes = GetIgnoreBaseTypes();
            var discriminatedTypes = GetDiscriminatedTypes();
            var mapDefaultConventions = ShouldMapDefaultConventions();
            var assemblyWithAdditionalConventions = GetAssembliesWithAdditionalConventions();

            _configuration = new Configuration();
            _configuration.Configure();
            var autoPersistenceModel = AutoMap.Assemblies(new AutomappingConfiguration(discriminatedTypes.ToArray()), assembliesToMap);
            includeBaseTypes.Each(x => autoPersistenceModel.IncludeBase(x));
            ignoreBaseTypes.Each(x => autoPersistenceModel.IgnoreBase(x));
            assembliesToMap.Each(x => autoPersistenceModel.UseOverridesFromAssembly(x));
            if (mapDefaultConventions) autoPersistenceModel.Conventions.AddFromAssemblyOf<PrimaryKeyConvention>();
            assemblyWithAdditionalConventions.Each(x => autoPersistenceModel.Conventions.AddAssembly(x));

            _sessionFactory = Fluently.Configure(_configuration)
                .Mappings(x =>
                              {
                                  var mappingsContainer = x.AutoMappings.Add(autoPersistenceModel);
                                  var exportNhibernateMappingsFolder = ConfigurationManager.AppSettings["ExportNhibernateMappingsFolder"];
                                  if (!string.IsNullOrWhiteSpace(exportNhibernateMappingsFolder)) mappingsContainer.ExportTo(exportNhibernateMappingsFolder);
                              })
                .BuildSessionFactory();
        }
       /// <summary>
        /// This method attempts to find a session factory stored in <see cref="_sessionFactories" />
        /// via its name; if it can't be found it creates a new one and adds it the hashtable.
        /// </summary>
        /// <param name="sessionFactoryConfigPath">Path location of the factory config</param>
        public ISessionFactory GetSessionFactoryFor(string sessionFactoryConfigPath) {
            Check.Require(!string.IsNullOrEmpty(sessionFactoryConfigPath),
                "sessionFactoryConfigPath may not be null nor empty");

            //  Attempt to retrieve a stored SessionFactory from the hashtable.
            ISessionFactory sessionFactory = (ISessionFactory) _sessionFactories[sessionFactoryConfigPath];

            //  Failed to find a matching SessionFactory so make a new one.
            if (sessionFactory == null) {
                Check.Require(File.Exists(sessionFactoryConfigPath),
                    "The config file at '" + sessionFactoryConfigPath + "' could not be found");

                NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
                cfg.Configure(sessionFactoryConfigPath);

                //  Now that we have our Configuration object, create a new SessionFactory
                sessionFactory = cfg.BuildSessionFactory();

                if (sessionFactory == null) {
                    throw new InvalidOperationException("cfg.BuildSessionFactory() returned null.");
                }

                _sessionFactories.Add(sessionFactoryConfigPath, sessionFactory);
            }

            return sessionFactory;
        }
Beispiel #14
0
        public static void Main(string[] args)
        {
            IList<Product> products;

            // Don't need to use schema export because of the hbm2dll property.
            var cfg = new NHibernate.Cfg.Configuration();
            cfg.Configure();
            // ensure that mapping hbm.xml file is loaded
            cfg.AddAssembly(typeof(MainClass).Assembly);

            Product p = new Product() {Name="Captains of Crush Gripper #1", Category="fitness" };

            ISessionFactory factory =
                cfg.BuildSessionFactory();

            using (ISession session = factory.OpenSession())
            {
                session.Save(p);
                session.Flush();

              	ICriteria sc = session.CreateCriteria<Product>();
              	products = sc.List<Product>();
                Console.WriteLine(products[0].Name);
              	session.Close();
            }
            factory.Close();

            Console.WriteLine( products.Count );

            Console.WriteLine ("Hello World!");
        }
        public static NHibernate.ISessionFactory GetSessionFactory(
            string connectionString, List<String> DllNames)
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            // set provider & driver properties
            cfg.Properties.Add(
            "connection.provider",
                "NHibernate.Connection.DriverConnectionProvider");

            cfg.Properties.Add(
            "connection.driver_class",
                "NHibernate.Driver.SQLite20Driver");

            cfg.Properties.Add(
            "dialect",
                "NHibernate.Dialect.SQLiteDialect");

            cfg.Properties.Add(
            "max_fetch_depth","-1"); // allows for unlimited outer joins (recommeded value is maximum 4

            cfg.Properties.Add(
            "connection.connection_string",
                 ConfigurationManager.ConnectionStrings[connectionString].ConnectionString);

            cfg.Properties.Add("connection.isolation", "ReadCommitted");
            cfg.Properties.Add("query.substitutions", "true 1, false 0");

            // here we add all the needed assemblies that contain mappings or objects
            foreach (String assemblyName in DllNames)
                cfg.AddAssembly(System.Reflection.Assembly.Load(assemblyName));

            return cfg.BuildSessionFactory();
        }
Beispiel #16
0
 private static ISessionFactory CreateSessionFactory()
 {
     Configuration cfg = new Configuration().Configure();
     ISessionFactory rez = Fluently.Configure(cfg).Mappings(x => x.FluentMappings.AddFromAssemblyOf<UserMap>()).BuildSessionFactory();
     new SchemaExport(cfg).Execute(false, true, false, rez.OpenSession().Connection, null);
     return rez;
 }
        public void ApplyWrongConstraint()
        {
            XmlConfigurator.Configure();
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            if (TestConfigurationHelper.hibernateConfigFile != null)
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            cfg.AddResource("NHibernate.Validator.Tests.Integration.WrongClass.whbm.xml", Assembly.GetExecutingAssembly());
            Environment.SharedEngineProvider = null;
            XmlConfiguration nhvc = new XmlConfiguration();
            nhvc.Properties[Environment.ApplyToDDL] = "true";
            nhvc.Properties[Environment.AutoregisterListeners] = "true";
            nhvc.Properties[Environment.ValidatorMode] = "UseAttribute";

            using (LoggerSpy ls = new LoggerSpy(typeof(ValidatorInitializer), Level.Warn))
            {
                ValidatorInitializer.Initialize(cfg);
                int found =
                    ls.GetOccurenceContaining(
                        string.Format("Unable to apply constraints on DDL for [MappedClass={0}]", typeof (WrongClass).FullName));
                Assert.AreEqual(1, found);
                found =
                    ls.GetOccurenceContaining(
                        string.Format("Unable to apply constraints on DDL for [MappedClass={0}]", typeof (WrongClass1).FullName));
                Assert.AreEqual(1, found);
            }
        }
Beispiel #18
0
        private SessionManager()
        {
            if (sessionFactory == null)
            {
                var configuration = new Configuration()
                    .AddAssembly(Assembly.GetExecutingAssembly())
                    .SetProperty("connection.connection_string", GetCoreConnectionString())
                    .Configure();

            //#if (DEBUG)
            //                {
                //var schemadrop = new SchemaExport(configuration);
                //schemadrop.Drop(true, false);

                //var schemaUpdate = new SchemaUpdate(configuration);

                //schemaUpdate.Execute(true, true);

                //var schemaCreate = new SchemaExport(configuration);
                //schemaCreate.Create(true, true);
            //                }
            //#endif

                sessionFactory = configuration.BuildSessionFactory();
            }
        }
        public void WorkWithOutSharedEngine()
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            if (TestConfigurationHelper.hibernateConfigFile != null)
                cfg.Configure(TestConfigurationHelper.hibernateConfigFile);
            string[] mappings =
                new string[]
                    {
                        "Integration.Address.hbm.xml",
                        "Integration.Tv.hbm.xml",
                        "Integration.TvOwner.hbm.xml",
                        "Integration.Martian.hbm.xml",
                        "Integration.Music.hbm.xml"
                    };
            foreach (string file in mappings)
            {
                cfg.AddResource("NHibernate.Validator.Tests" + "." + file, Assembly.GetExecutingAssembly());
            }
            Environment.SharedEngineProvider = null;
            XmlConfiguration nhvc = new XmlConfiguration();
            nhvc.Properties[Environment.ApplyToDDL] = "true";
            nhvc.Properties[Environment.AutoregisterListeners] = "true";
            nhvc.Properties[Environment.ValidatorMode] = "UseAttribute";

            ValidatorInitializer.Initialize(cfg);
        }
        private static ISessionFactory CreateSessionFactory()
        {
            if ( Configuration == null )
            {
                // FluentNHibernate Configuration API for configuring NHibernate
                Configuration = Fluently.Configure()
                    .Database( SQLiteConfiguration.Standard.ConnectionString( c => c.FromConnectionStringWithKey( SqLiteConnectionStringName ) ) )
                    .Mappings( m => m.FluentMappings.AddFromAssemblyOf<Scrumee.Data.Entities.Project>()
                                        .Conventions.Add( PrimaryKey.Name.Is( x => x.EntityType.Name + "Id" ), ForeignKey.EndsWith( "Id" ) ) )
                    .BuildConfiguration();

                // Loquacious ( NHibernate v3.0+ ) Configuration API for configuring NHibernate
                /*
                Configuration = new NHibernate.Cfg.Configuration()
                    .Proxy( p => p.ProxyFactoryFactory<ProxyFactoryFactory>() )
                    .DataBaseIntegration( db =>
                                              {
                                                  db.Dialect<SQLiteDialect>();
                                                  db.ConnectionStringName = SqLiteConnectionStringName;
                                                  db.Driver<NHibernate.Driver.SQLite20Driver>();
                                              } )
                    .AddAssembly( typeof( Scrumee.Data.Entities.Entity ).Assembly );
                */

                DropAndRecreateSqliteDatabase();
            }

            var sessionFactory = Configuration.BuildSessionFactory();

            return sessionFactory;
        }
        /// <summary>
        /// Builds the session factory with the given properties. Database is updated if updateSchema is set
        /// </summary>
        /// <param name="nhibernateProperties"></param>
        /// <param name="updateSchema"></param>
        /// <returns></returns>
        public ISessionFactory Build(IDictionary<string, string> nhibernateProperties, bool updateSchema)
        {
            var model = Create.SagaPersistenceModel(typesToScan);
            var scannedAssemblies = typesToScan.Select(t => t.Assembly).Distinct();

            var nhibernateConfiguration = new Configuration().SetProperties(nhibernateProperties);

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

            var fluentConfiguration = Fluently.Configure(nhibernateConfiguration)
                                        .Mappings(m => m.AutoMappings.Add(model));

            ApplyDefaultsTo(fluentConfiguration);

            if (updateSchema)
            {
                UpdateDatabaseSchemaUsing(fluentConfiguration);
            }

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

                throw;
            }
        }
        void ApplyMappings(Configuration config)
        {
            var mapper = new ModelMapper();
            mapper.AddMapping<OutboxEntityMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
        public void InitSessionFactory()
        {
            try
            {
                string connectionString = "Data Source=Pets.sdf";
                string owner = String.Empty;

                NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration();
                configuration.Properties.Add("dialect", "NHibernate.Dialect.MsSqlCeDialect");
                configuration.Properties.Add("connection.driver_class", "NHibernate.Driver.SqlServerCeDriver");
                AppDomain.CurrentDomain.SetData("SQLServerCompactEditionUnderWebHosting", true);

                configuration.Properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
                configuration.Properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
                configuration.Properties.Add("connection.connection_string", connectionString);
                configuration.Properties.Add("show_sql", "true");
                configuration.AddAssembly("DataDriver, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");

                //ToDo :: Add more entity assembly keys if you nHibernate stuff crashes and you don't know why...

                _sessionFactory = configuration.BuildSessionFactory();
            }
            catch (Exception ex)
            {
                Trace.TraceInformation("Creating the session factory failed with {0}", ex.Message);
            }
        }
Beispiel #24
0
		public static NHibernate.Cfg.Configuration CreateConfiguration([CanBeNull] string connectionString, [CanBeNull] Action<NHibernate.Cfg.Configuration> configurator)
		{
			Assert.NotNull(typeof(SQLiteConnection));

			connectionString = connectionString ?? "Data Source=:memory:";

			var cfg = new NHibernate.Cfg.Configuration()
				.SetProperty(Environment.ConnectionDriver, typeof (SQLite20Driver).AssemblyQualifiedName)
				.SetProperty(Environment.Dialect, typeof (SQLiteDialect).AssemblyQualifiedName)
				//.SetProperty(Environment.ConnectionDriver, typeof(Sql2008ClientDriver).AssemblyQualifiedName)
				//.SetProperty(Environment.Dialect, typeof(MsSql2008Dialect).AssemblyQualifiedName)
				.SetProperty(Environment.ConnectionString, connectionString)
				//.SetProperty(Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName)
				//.SetProperty(Environment.ReleaseConnections, "never")
				.SetProperty(Environment.UseSecondLevelCache, "true")
				.SetProperty(Environment.UseQueryCache, "true")
				.SetProperty(Environment.CacheProvider, typeof (HashtableCacheProvider).AssemblyQualifiedName)
				//.SetProperty(Environment.DefaultSchema, "bus")
				.AddAssembly(typeof (RegisterUserStateMachine).Assembly)
				.AddAssembly(typeof (SagaRepository_Specs).Assembly);

			if (configurator != null)
				configurator(cfg);

			return cfg;
		}
Beispiel #25
0
        /// <summary>
        /// 创建StatelessDbSession对象
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="dbDialectProvider">数据库特性对象提供程序</param>
        /// <param name="mappingXml">实体关系映射配置Xml文本</param>
        /// <returns>返回StatelessDbSession对象</returns>
        public virtual StatelessDbSession CreateStatelessDbSession(string connectionString, IDbDialectProvider dbDialectProvider, string mappingXml)
        {
            ISessionFactory sf = null;
            while (!sessionFactories.TryGetValue(connectionString, out sf))
            {
                IDictionary<string, string> dbSetting = new Dictionary<string, string>
                {
                    ["dialect"] = dbDialectProvider.DialectName,
                    ["connection.connection_string"] = connectionString,
                };
                CustomizeNHSessionFactory(dbSetting);
                var x = new NHibernate.Cfg.Configuration();
                x = x.AddProperties(dbSetting);
                //允许采用配置文件修改NHibernate配置
                var hc = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName) as NHibernate.Cfg.IHibernateConfiguration;
                if ((hc != null && hc.SessionFactory != null) || File.Exists(GetDefaultConfigurationFilePath()))
                {
                    x = x.Configure();
                }
                if (System.Transactions.Transaction.Current != null)
                {
                    //如果在分布式事务范围内,就将连接释放模式更改为on_close模式,防止auto模式下,重新获取连接,导致分布式事务升级
                    x.AddProperties(new Dictionary<string, string> {["connection.release_mode"] = "on_close" });
                }
                //添加实体关系映射
                if (!string.IsNullOrWhiteSpace(mappingXml))
                {
                    x.AddXml(mappingXml);
                }

                sf = x.BuildSessionFactory();
                sessionFactories.TryAdd(connectionString, sf);
            }
            return new StatelessDbSession(sf, connectionString);
        }
		private ServerConnection GetServerConnection(Configuration configuration)
		{
			string connectionString = GetConnectionString(configuration);
			var conn = new SqlConnection(connectionString);
			var server = new Server(new ServerConnection(conn));
			return server.ConnectionContext;
		}
Beispiel #27
0
 static void Main(string[] args)
 {
     NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
     cfg.Configure();
     NHibernate.Tool.hbm2ddl.SchemaExport schema = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
     schema.Create(false, true);
 }
 public void Init()
 {
     //SystemController sys = (SystemController)Application["systemController"];
     var cfg = new NHibernate.Cfg.Configuration().Configure("hibernate.cfg.xml");
     sessionFactory = cfg.BuildSessionFactory();
     sys = new SystemController(sessionFactory);
 }
Beispiel #29
0
        public static void Configure(Configuration cfg)
        {
            if (configCollection == null)
            {
                configCollection = LoadConfiguration();
            }

            string sessionFactoryName = string.Empty;

            if (cfg.Properties.ContainsKey(NHibernate.Cfg.Environment.SessionFactoryName))
            {
                sessionFactoryName = cfg.Properties[NHibernate.Cfg.Environment.SessionFactoryName];
            }

            INHSConfiguration configuration = configCollection.GetConfiguration(sessionFactoryName);

            if (configuration == null)
            {
                return;
            }

            foreach (KeyValuePair<string, string> pair in configuration.Properties)
            {
                cfg.Properties[pair.Key] = pair.Value;
            }
        }
Beispiel #30
0
 private static void InitNHibernate()
 {
     _configuration = NHibernateSession.Init(
         new SimpleSessionStorage(),
         new[] { "Honeypot.Infrastructure.dll" },
         new AutoPersistenceModelGenerator().Generate(),
         "../../../../Src/Honeypot.Web/NHibernate.config");
 }
Beispiel #31
0
 static void BuildSchema(NHibernate.Cfg.Configuration config)
 {
     // this NHibernate tool takes a configuration (with mapping info in)
     // and exports a database schema from it
     //new SchemaExport(config)
     //    .Create(true, true);
     new SchemaUpdate(config).Execute(false, true);
 }
Beispiel #32
0
        private static void BuildSchema(NHibernate.Cfg.Configuration config)
        {
            new SchemaUpdate(config).Execute(false, true);

            string schemaFile = Path.Combine(Path.GetDirectoryName(typeof(TimeoutService).Assembly.Location), typeof(TimeoutService).Name + ".sql");

            new SchemaExport(config).SetOutputFile(schemaFile).Execute(false, false, false);
        }
        public static NHibernate.Cfg.Configuration Deploy(this NHibernate.Cfg.Configuration config, string ConnectionString)
        {
            var schemas = config.ClassMappings.Select(a => a.Table.Schema).Distinct().Where(a => !string.IsNullOrEmpty(a)).ToArray();

            PreDatabaseCreate(ConnectionString, schemas);
            new NHibernate.Tool.hbm2ddl.SchemaExport(config).Execute(true, true, false);
            return(config);
        }
        public void RegisterConponents(ContainerBuilder builder, Configuration config)
        {
            builder.RegisterInstance(config).As <Configuration>().SingleInstance();

            builder.RegisterInstance(SessionFactory).As <ISessionFactory>().SingleInstance();

            builder.Register(x => x.Resolve <ISessionFactory>().OpenSession()).As <ISession>().InstancePerLifetimeScope();
        }
Beispiel #35
0
        private static void BuildSchema()
        {
            NHibernate.Cfg.Configuration cfg = NHibernateConfigurator.Configuration;
            var schemaExport = new SchemaExport(cfg);

            schemaExport.Create(false, true);
            // A new session is created implicitly to run the create scripts. But this new session is not the context session
        }
        private ServerConnection GetServerConnection(Configuration configuration)
        {
            string connectionString = GetConnectionString(configuration);
            var    conn             = new SqlConnection(connectionString);
            var    server           = new Server(new ServerConnection(conn));

            return(server.ConnectionContext);
        }
        private void RenameForeignKeys(Configuration configuration)
        {
            ServerConnection connection = GetServerConnection(configuration);

            string sql = File.ReadAllText("RenameForeignKeys.sql");

            connection.ExecuteNonQuery(sql);
        }
Beispiel #38
0
 /// <summary>Adds default assemblies to NHibernate configuration.</summary>
 /// <param name="cfg"></param>
 protected virtual void AddAssemblies(NHibernate.Cfg.Configuration cfg)
 {
     foreach (Assembly a in Assemblies)
     {
         cfg.AddAssembly(a);
     }
     Debug.WriteLine(String.Format("Added {0} assemblies to configuration", Assemblies.Count));
 }
 private static void ConfigureConnectionSettings(Configuration nhConfig)
 {
     nhConfig.Properties["dialect"] = ConfigurationManager.AppSettings["nhf.dialect"];
     nhConfig.Properties["connection.driver_class"]      = ConfigurationManager.AppSettings["nhf.connection.driver_class"];
     nhConfig.Properties["connection.provider"]          = ConfigurationManager.AppSettings["nhf.connection.provider"];
     nhConfig.Properties["connection.connection_string"] =
         ConfigurationManager.AppSettings["nhf.connection.connection_string.1"];
 }
Beispiel #40
0
        public ISessionFactory CreateSessionFactory(IList <IShardConfiguration> shardConfigs)
        {
            Configuration         prototypeConfig      = GetConfigurationTemplate("Shard1", 1);
            IShardStrategyFactory shardStrategyFactory = BuildShardStrategyFactory();
            var shardedConfig = new ShardedConfiguration(prototypeConfig, shardConfigs, shardStrategyFactory);

            return(shardedConfig.BuildShardedSessionFactory());
        }
        void ApplyMappings(Configuration config)
        {
            var mapper = new ModelMapper();

            mapper.AddMapping <OutboxEntityMap>();

            config.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
Beispiel #42
0
        public NHibernateProviderManager(NHibernate.Cfg.Configuration configuration)
        {
            // Build the NHibernate session factory for the configuration
            this.SessionFactory = configuration.BuildSessionFactory();

            // Extract the connection string from the NHibernate configuration
            this.ConnectionString = configuration.Properties[ConnectionStringKey];
        }
Beispiel #43
0
        public virtual void SetUp()
        {
            var mappingAssemblies = new List <Assembly> {
                typeof(UserMapping).Assembly
            };

            cfg = ConfigurationBuilder.CreateFluentConfiguration(MsSqlConfiguration.MsSql2008.ConnectionString(@"Server=.\SQLEXPRESS;Database=dev_tfs2.com;Trusted_Connection=yes;"), mappingAssemblies);
        }
Beispiel #44
0
 public void Initialized(NHibernate.Cfg.Configuration configuration, ISessionFactory sessionFactory)
 {
     if (!Enabled)
     {
         return;
     }
     //NHibernateProfiler.Initialize();
 }
Beispiel #45
0
        /// <summary>
        /// Configurates and instanciates a Nhibernate session factory.
        /// </summary>
        static NHibernateHelper()
        {
            var configuration = new NHibernate.Cfg.Configuration();

            configuration.AddAssembly(Config.Metrics.MetricsNhibernateAssembly);

            SessionFactory = configuration.BuildSessionFactory();
        }
Beispiel #46
0
 public ISession OpenSession()
 {
     if (_config == null)
     {
         _config = Configure();
     }
     return(_config.BuildSessionFactory().OpenSession());
 }
 private void SaveConfigurationToFile(Configuration cfg)
 {
     using (var file = File.Open(SERIALIZED_CFG, FileMode.Create))
       {
     var bf = new BinaryFormatter();
     bf.Serialize(file, cfg);
       }
 }
        public NHibernate.Cfg.Configuration GetConfiguration()
        {
            if (_configuration != null)
            {
                return(_configuration);
            }

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

            {
                cfg.Configure(@"OrmNhib/NHibernateConfig/hibernate.cfg.xml");

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

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

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

                try
                {
                    SchemaValidator schemaValidator = new SchemaValidator(cfg);
                    schemaValidator.Validate();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Exception: {ex}");
                }


                // Note
                // SchemaUpdate.Execute is way cooler than SchemaExport.Filename.Execute
                // When I added a new property in Movie.hbm.xml (and in the .cs), SchemaUpdate automatically created statement
                // to tell the diff in schema, and only this got executed:

                /*
                 *  alter table Movie
                 *      add column NewProp VARCHAR(255)
                 *
                 * */
                //
                // However, it does not work as expected all the times, for eg,
                // if I rename a column in HBM, it just adds a new column with new name
                // if I change the sql-type from VARCHAR(255) to VARCHAR(100), nothing is executed and the column type remains unchanged
                // So we will need manual scripts for migration
                //
            }

            _configuration = cfg;
            return(_configuration);
        }
        private void SaveConfigurationToFile(Configuration cfg)
        {
            using (var file = File.Open(SERIALIZED_CFG, FileMode.Create))
            {
                var bf = new BinaryFormatter();

                bf.Serialize(file, cfg);
            }
        }
        public void CanGenerateSchema()
        {
            var cfg = new NHibernate.Cfg.Configuration();

            cfg.Configure();
            cfg.AddAssembly(Assembly.Load("InfoHub.Entity"));

            new SchemaExport(cfg).Execute(false, true, false);
        }
 public MyPropertySelector(NHibernate.Cfg.Configuration cfg, string keyName)
 {
     _configuration = cfg;
     _keyColumns = _configuration.GetClassMapping(typeof(T))
                             .Table
                             .UniqueKeyIterator
                             .First(key => key.Name == keyName)
                             .ColumnIterator);
 }
 /// <summary>
 /// Standar Configuration for tests.
 /// </summary>
 /// <returns>The configuration using merge between App.Config and hibernate.cfg.xml if present.</returns>
 public static NHibernate.Cfg.Configuration GetDefaultConfiguration()
 {
     NHibernate.Cfg.Configuration result = new NHibernate.Cfg.Configuration();
     if (hibernateConfigFile != null)
     {
         result.Configure(hibernateConfigFile);
     }
     return(result);
 }
 protected override void AdjustConfiguration(NHibernate.Cfg.Configuration cfg)
 {
     //XmlConfigurator.Configure();
     cfg.Cache(x =>
     {
         x.UseQueryCache = true;
         x.Provider <HashtableCacheProvider>();
     });
 }
 static void Main(string[] args)
 {
     NHibernate.Cfg.Configuration         configuration = new NHibernate.Cfg.Configuration().Configure();
     NHibernate.Tool.hbm2ddl.SchemaExport schemaExport  = new NHibernate.Tool.hbm2ddl.SchemaExport(configuration);
     //打印Sql脚本,但不执行
     schemaExport.Create(true, false);
     schemaExport.SetOutputFile(@"c:/hibernate_test.sql");
     Console.Read();
 }
Beispiel #55
0
        public NetworksController(
            INHibernateInitializer nHibernateInitializer,
            ISessionFactory sessionFactory)
        {
            this._nHibernateInitializer = nHibernateInitializer ?? throw new ArgumentNullException(nameof(nHibernateInitializer));
            this._sessionFactory        = sessionFactory ?? throw new ArgumentNullException(nameof(sessionFactory));

            _configuration = _nHibernateInitializer.GetConfiguration();
        }
        public NHibernateHelper()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["wowstats_azure"].ConnectionString;

            _dbConfiguration = Fluently.Configure()
                               .Database(MsSqlConfiguration.MsSql2012.ConnectionString(connectionString).ShowSql)
                               .Mappings(m => m.FluentMappings.AddFromAssemblyOf <ZoneMappings>())
                               .BuildConfiguration();
        }
Beispiel #57
0
        protected override void Configure(NHibernate.Cfg.Configuration protoConfig)
        {
            protoConfig.Properties[NHibernate.Cfg.Environment.ShowSql] = "True";

            var mapper = new ModelMapper();

            mapper.AddMapping <PersonMap>();
            protoConfig.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
Beispiel #58
0
        private SessionManager()
        {
            Configuration config = new Configuration();

            config.Properties[NHibernate.Cfg.Environment.ConnectionString] =
                ConfigurationManager.ConnectionStrings["AtomicCms"].ConnectionString;
            config.Configure();
            this.sessionFactory = config.BuildSessionFactory();
        }
Beispiel #59
0
        public virtual void SetUp()
        {
            log4net.Config.XmlConfigurator.Configure();

            string[] mappingAssemblies = RepositoryTestsHelper.GetMappingAssemblies();
            configuration = NHibernateSession.Init(new SimpleSessionStorage(), mappingAssemblies,
                                                   new AutoPersistenceModelGenerator().Generate(),
                                                   "../../../../tests/FashionAde.TestsUsingDevDatabase/Hibernate.Test.cfg.xml");
        }
        public static ISessionFactory CreateSessionFactory(string connectionString)
        {
            var configuration = new NHibernateConfiguration().SetNamingStrategy(new PostgresNamingStrategy());

            return(Fluently.Configure(configuration)
                   .Database(PostgreSQLConfiguration.PostgreSQL82.ConnectionString(connectionString))
                   .Mappings(ConfigureMappings)
                   .BuildSessionFactory());
        }