public static ISessionFactory AppDomainFactory()
 {
     if (_appDomainFactory == null)
     {
         lock (_synRoot3)
         {
             if (_appDomainFactory == null)
             {
                 var createSchema = false;
                 var configuration = new Configuration()
                     .DataBaseIntegration(d =>
                     {
                         d.ConnectionStringName = Constants.APP_DB;
                         d.Dialect<MsSql2012Dialect>();
                         //d.Dialect<Oracle10gDialect>();
                         d.SchemaAction = SchemaAutoAction.Validate;
                     })
                     .Proxy(p => p.ProxyFactoryFactory<DefaultProxyFactoryFactory>())
                     .CurrentSessionContext<LazySessionContext>()
                     .SetProperty(NHibernate.Cfg.Environment.Hbm2ddlKeyWords, "none")
                     .SetProperty(NHibernate.Cfg.Environment.Hbm2ddlAuto, (createSchema == true) ? SchemaAutoAction.Update.ToString() : SchemaAutoAction.Validate.ToString());
                 configuration.AddMapping(GetAppMappings());
                 configuration.BuildMapping();
                 if (File.Exists(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY])))
                     configuration.Configure(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY]));
                 if (File.Exists(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY_App])))
                     configuration.Configure(Util.GetFullPath(System.Configuration.ConfigurationManager.AppSettings[Constants.HIBERNATE_CONFIG_KEY_App]));
                 //new NHibernate.Tool.hbm2ddl.SchemaExport(configuration).SetOutputFile(@"c:\temp\MyDDL.sql").Execute(true /*script*/, true /*export to db*/, false /*just drop*/);
                 _appDomainFactory = configuration.BuildSessionFactory();
             }
         }
     }
     return _appDomainFactory;
 }
Example #2
0
        public override void Load()
        {
            Bind<IUnitOfWorkFactory>().ToFactory();
            Bind<IRepositoryFactory>().ToFactory();
            Bind<IUnitOfWork>().To<UnitOfWork>();
            Bind<ISessionFactory>().ToMethod(ctx =>
            {
                var cfg = new Configuration();
#if DEBUG
                cfg.Configure();
#else
                cfg.Configure(Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, "hibernate-release.cfg.xml"));
#endif
                cfg.AddAssembly(Assembly.GetExecutingAssembly());
                return cfg.BuildSessionFactory();
            });
            Bind<IRepository<User>, IUserRepository>().To<UserRepository>();
            Bind<IRepository<Artist>>().To<ArtistRepository>();
            Bind<IRepository<Album>>().To<AlbumRepository>();
            Bind<IRepository<Track>>().To<TrackRepository>();
            Bind<IRepository<Playlist>, IPlaylistRepository>().To<PlaylistRepository>();
            Bind<IRepository<SocialNetwork>, ISocialNetworkRepository>().To<SocialNetworkRepository>();
            Bind<IRepository<UserSocialNetwork>, IUserSocialNetworkRepository>().To<UserSocialNetworkRepository>();
            Bind<IRepository<PlaylistTrack>>().To<PlaylistTrackRepository>();
            Bind<IRepository<PlaylistListener>>().To<PlaylistListenersRepository>();
            Bind<IRepository<SharedPlaylist>>().To<SharedPlaylistRepository>();
            Bind<IRepository<PlaylistLike>>().To<PlaylistLikerRepository>();
            Bind<IRepository<Notification>, INotificationRepository>().To<NotificationRepository>();
        }
Example #3
0
        private void BuildSessionFactory()
        {
            try
            {
                var config = new Configuration();

                if (string.IsNullOrEmpty(_configurationFile))
                {
                    config.Configure();
                }
                else
                {
                    config.Configure(_configurationFile);
                }

                config.AddAssembly(typeof (NhUnitOfWork).Assembly);

                _sessionFactory = config.BuildSessionFactory();
            }
            catch (Exception)
            {
                _sessionFactory = null;
                throw;
            }
        }
        /// <summary>
        /// Configure according to hibernate.cfg.xml
        /// </summary>
        /// <param name="config">Configuration to apply the config file to</param>
        /// <param name="hibernateFile">Hibernate file path</param>
        /// <returns>Updated configuration</returns>
        private static Configuration Configure(Configuration config,
                string hibernateFile)
        {
            // In case that hibernate config file location is null find hibernate.cfg.xml
            // file in classpath
            if (hibernateFile == null)
                return config.Configure();

            return config.Configure(hibernateFile);
        }
Example #5
0
        public static void Initialize()
        {
            NhibernateConfiguration = new Configuration();
            NhibernateConfiguration.Properties[NHibernate.Cfg.Environment.CollectionTypeFactoryClass] = typeof(Net4CollectionTypeFactory).AssemblyQualifiedName;
            NhibernateConfiguration.Configure();

            // Mapping by Mapping XML-Files
            foreach (var xmlMappingAssembly in GetXmlMappingAssemblies())
            {
                NhibernateConfiguration.AddAssembly(xmlMappingAssembly);
            }

            // Mapping by Code
            var modelMapper = new ModelMapper();

            foreach (var modelAssembly in GetModelAssemblies())
            {
                modelMapper.AddMappings(modelAssembly.GetExportedTypes());
                NhibernateConfiguration.AddAssembly(modelAssembly);
            }
            if (GetModelAssemblies().Any())
            {
                HbmMapping domainMapping = modelMapper.CompileMappingForAllExplicitlyAddedEntities();
                NhibernateConfiguration.AddMapping(domainMapping);
            }


            SessionFactory = NhibernateConfiguration.BuildSessionFactory();
        }
Example #6
0
		public void SetUp() {
			if (this._sessionFactory == null) {
				var cfg = new Configuration();
				cfg.Configure();
				this._sessionFactory = cfg.BuildSessionFactory();
			}
		}
Example #7
0
 /// <summary>
 /// Standar Configuration for tests.
 /// </summary>
 /// <returns>The configuration using merge between App.Config and hibernate.cfg.xml if present.</returns>
 public static Configuration GetDefaultConfiguration()
 {
     Configuration result = new Configuration();
     if (hibernateConfigFile != null)
         result.Configure(hibernateConfigFile);
     return result;
 }
        /// <summary>
        /// Se crea la configuración de inicio de la aplicación y
        /// muestra, usando la vista Index.cshtml la pagina de iniio
        /// </summary>
        /// <returns>Devuelve Index.cshtml, la vista asociada a la funcion Index()</returns>
        public ActionResult Index()
        {
            myConfiguration = new NHibernate.Cfg.Configuration();
            myConfiguration.Configure();
            myISessionFactory = myConfiguration.BuildSessionFactory();
            myISession        = myISessionFactory.OpenSession();
            string msgSalida = "";

            using (SqlConnection con = new SqlConnection(conString))
            {
                try//tratamos de crear la tabla, si existe atrapa la excepcion y lanza el mensaje correspondiente
                {
                    // Abrir conexion sql.
                    con.Open();
                    // Creamos la tabla.
                    using (SqlCommand command = new SqlCommand("CREATE TABLE requests (id int IDENTITY(1,1) PRIMARY KEY, request text NOT NULL);", con))
                    {
                        command.ExecuteNonQuery();//verificamos que el comando afecta la base de datos
                        msgSalida = "La tabla requests no existe, creando tabla en base de datos";
                    }
                }
                catch (Exception ex)
                {
                    msgSalida = "La tabla requests ya existe, no es necesario crearla.";
                }
            }
            ViewData["msgSalida"] = msgSalida;
            return(View());
        }
        private void button1_Click(object sender, EventArgs e)
        {
            var cfg = new Configuration();
            cfg.Configure();
            cfg.AddAssembly(typeof(Domain.User).Assembly);

            var sessions = cfg.BuildSessionFactory();
            var sess = sessions.OpenSession();
            var new_user = new Domain.User

            {
                Name = textBox1.Text,
                Surname = textBox2.Text,
                Patronymic = textBox3.Text,
                Role_id = 1,
                Login = textBox4.Text,
                Pass = textBox5.Text
            };
            if (new_user.Name.Length > 0 && new_user.Surname.Length > 0 && new_user.Patronymic.Length > 0 && new_user.Login.Length > 0 && new_user.Pass.Length > 0)
            {
                sess.Save(new_user);
                sess.Flush();
                this.Hide();
            }
            else
            {
                label6.Text = "Не все поля заполнены!";
            }
        }
        /// <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();
        }
Example #11
0
        public void TestEvent()
        {
            var config = new NHibernate.Cfg.Configuration();

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

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

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

            var factory = config.BuildSessionFactory();

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

            using (var session = factory.OpenSession())
            {
                var message = session.Get <Message>(1);
                Assert.IsNotNull(message.Creator);
                Assert.AreEqual(message.LastEditor, "Leoli_SaveOrUpdate_Event");
            }
        }
Example #12
0
        public void TestEvent2()
        {
            var config = new NHibernate.Cfg.Configuration();

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

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

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

            var factory = config.BuildSessionFactory();

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

            using (var session = factory.OpenSession())
            {
                var message = session.Get <Message>(1);
                message.Content = "Message_Leoli2";
                session.Save(message);
                session.Flush();
                Assert.AreEqual(message.LastEditor, "Leoli_Update_Event");
            }
        }
Example #13
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;
 }
Example #14
0
		/// <summary>
		/// Called by the framework to initialize the persistent store.
		/// </summary>
		public void Initialize()
		{
			Platform.Log(LogLevel.Info, "Initializing NHibernate subsystem...");

			// create the hibernate configuration
			_cfg = new Configuration();

			// this will automatically read from the app.config
			_cfg.Configure();

			Platform.Log(LogLevel.Debug, "NHibernate connection string: {0}", this.ConnectionString);

			// add each assembly to the hibernate configuration
			// this tells NHibernate to look for .hbm.xml embedded resources in these assemblies
			// TODO: we should only scan plugins that are tied to this PersistentStore, but there is currently no way to know this
			var orderer = new AssembliesHbmOrderer(Platform.PluginManager.Plugins);
			orderer.AddToConfiguration(_cfg);

			// setup default caching strategies for all classes/collections that don't have one explicitly
			// specified in the mapping files
			CreateDefaultCacheStrategies();

			// create the session factory
			_sessionFactory = _cfg.BuildSessionFactory();

			Platform.Log(LogLevel.Info, "NHibernate initialization complete.");
		}
        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());
        }
        public BusinessSafeSessionFactory()
        {
            var hibernateConfigFilePath = new NHibernateConfigPathGenerator(Database.BusinessSafe).GetConfigFilePath();
            Log4NetHelper.Logger.Debug("BusinessSafeSessionFactory() - NHibernate Configuration File path: " + hibernateConfigFilePath);

            var configuration = new Configuration();
            configuration.Configure(hibernateConfigFilePath);
            configuration.SetProperty(Environment.ConnectionStringName, "BusinessSafe");

            configuration.EventListeners.PostUpdateEventListeners = new IPostUpdateEventListener[]
                                                                        {
                                                                            new AuditUpdateListener()
                                                                        };
            configuration.EventListeners.PostInsertEventListeners = new IPostInsertEventListener[]
                                                                        {
                                                                            new AuditUpdateListener()
                                                                        };
            configuration.EventListeners.PostDeleteEventListeners = new IPostDeleteEventListener[]
                                                                        {
                                                                            new AuditUpdateListener()
                                                                        };
            configuration.EventListeners.PostCollectionUpdateEventListeners = new IPostCollectionUpdateEventListener[]
                                                                        {
                                                                            new AuditUpdateListener()
                                                                        };

            _sessionFactory = configuration.BuildSessionFactory();
        }
 private static ISessionFactory CriaSessionFactory()
 {
     Configuration cfg = new Configuration();
     cfg.Configure();
     return Fluently.Configure(cfg)
     .Mappings(x => x.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())).BuildSessionFactory();
 }
Example #18
0
        public void TestEvent()
        {
            var config = new NHibernate.Cfg.Configuration();
            config.Configure();
            config.DataBaseIntegration(db =>
            {
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

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

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

            var factory = config.BuildSessionFactory();

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

            using (var session = factory.OpenSession())
            {
                var message = session.Get<Message>(1);
                Assert.IsNotNull(message.Creator);
                Assert.AreEqual(message.LastEditor, "Leoli_SaveOrUpdate_Event");
            }
        }
        /// <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 static Configuration GetConfiguration()
 {
     var config = new Configuration();
     config.Configure();
     config.AddMapping(GetMappings());
     return config;
 }
Example #21
0
 public static Configuration InitConfiguration()
 {
     Configuration = new Configuration();
     Configuration.Configure(@"Config\NHibernate.cfg.xml");
     Configuration.AddAssembly("Org.Limingnihao.Application");
     return Configuration;
 }
		private static void Init()
		{
			var config = new Configuration();
			config.Configure();
			config.AddAssembly(Assembly.GetCallingAssembly());
			_sessionFactory = config.BuildSessionFactory();
		}
        public static void NHibernateConfiguration(TestContext context)
        {
            log4net.Config.XmlConfigurator.Configure();

            Configuration = new Configuration();
            // lendo o arquivo hibernate.cfg.xml
            Configuration.Configure();

            FilterDefinition filterDef = new FilterDefinition(
                "Empresa","EMPRESA = :EMPRESA",
                new Dictionary<string, IType>() {{"EMPRESA", NHibernateUtil.Int32}}, false);
            Configuration.AddFilterDefinition(filterDef);
            filterDef = new FilterDefinition(
                "Ativa", "ATIVO = 'Y'",
                new Dictionary<string, IType>(), false);
            Configuration.AddFilterDefinition(filterDef);

            // Mapeamento por código
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
            HbmMapping mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            Configuration.AddMapping(mapping);

            // Gerar o XML a partir do mapeamento de codigo.
            //var mappingXMl = mapping.AsString();

            // Mapeamento por arquivo, in resource.
            Configuration.AddAssembly(Assembly.GetExecutingAssembly());

            // Gerando o SessionFactory
            SessionFactory = Configuration.BuildSessionFactory();
        }
Example #24
0
        /// <summary>
        /// Método que crea la session factory
        /// </summary>
        public ISessionFactory SessionFactory()
        {
            try
            {
                //Siempre que no la hayamos creado antes
                if (_sessionFactory == null)
                {
                    var cfg = new NHibernate.Cfg.Configuration();
                    cfg.Configure();

                    var mapper = new ModelMapper();

                    //Especifico uno por unos los mapeos de las entidades
                    //mapper.AddMappings(typeof(BE.AfiliadoDatos).Assembly.GetTypes());
                    mapper.AddMapping <MapAfiBeneficiariosOspep>();
                    mapper.AddMapping <MapTest>();
                    mapper.AddMapping <MapAuditoriaWS>();
                    mapper.AddMapping <MapAfiBeneficiarios>();

                    var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

                    cfg.AddMapping(mapping);

                    _sessionFactory = cfg.BuildSessionFactory();
                }
                return(_sessionFactory);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Example #25
0
 private static void CreateConfiguration()
 {
     _config = new NHibernate.Cfg.Configuration();
     _config.Configure();
     // Add interceptor, if you need to.
     // _config.Interceptor = new Interceptor();
 }
Example #26
0
 public void Gerar_schema()
 {
     var cgc = new Configuration();
     cgc.Configure();
     cgc.AddAssembly("Comercio.Mapeamento");
     new SchemaExport(cgc).Execute(false, true, false);
 }
 public void TestFixtureSetUp()
 {
     _configuration = new Configuration();
     _configuration.Configure();
     _configuration.AddAssembly(typeof(Product).Assembly);
     _sessionFactory = _configuration.BuildSessionFactory();
 }
 public static void TestClassSetup(TestContext context)
 {
     _configuration = new Configuration();
     _configuration.Configure();
     _configuration.AddAssembly(typeof(Draft).Assembly);
     _sessionFactory = _configuration.BuildSessionFactory();
 }
 private Configuration createConfiguration()
 {
     Configuration cfg = new Configuration();
     cfg.Configure();
     cfg.AddAssembly(typeof(Mesto).Assembly);
     return cfg;
 }
Example #30
0
        public void CanGenerateSchema()
        {
            var cfg = new Configuration();
            cfg.Configure();

            new SchemaExport(cfg).Execute(true, false, false);
        }
Example #31
0
 private void button3_Click(object sender, EventArgs e)
 {
     var cfg = new Configuration();
     cfg.Configure();
     cfg.AddAssembly(typeof(Domain.User).Assembly);
     var sessions = cfg.BuildSessionFactory();
     var sess = sessions.OpenSession();
     var login = textBox1.Text;
     IQuery q = sess.CreateQuery("FROM User u where u.Login=:login").SetParameter("login",login);
     var list = q.List<Domain.User>();
     if (list.Count > 0 && list[0].Pass == textBox2.Text)
     {
         var role_id = list[0].Role_id;
         IQuery q_role = sess.CreateQuery("FROM Role u where u.Id=:role_id").SetParameter("role_id", role_id);
         var list_role = q_role.List<Domain.Role>();
         if (list_role[0].Name.Equals("reader"))
         {
             LibraryForm lib_form = new LibraryForm(list[0]);
             lib_form.ShowDialog();
         }
         else
         {
             AdminForm admin_form = new AdminForm();
             admin_form.ShowDialog();
         }
     }
     else
     {
         MessageBox.Show("Неверный логин или пароль");
     }
 }
Example #32
0
 public void init()
 {
     cfg = new Configuration();
     if (ConfigurationHelper.hibernateConfigFile != null)
         cfg.Configure(ConfigurationHelper.hibernateConfigFile);
     BuildSessionFactory();
 }
Example #33
0
        public void TestEvent2()
        {
            var config = new NHibernate.Cfg.Configuration();
            config.Configure();
            config.DataBaseIntegration(db =>
            {
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
            });

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

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

            var factory = config.BuildSessionFactory();

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

            using (var session = factory.OpenSession())
            {
                var message = session.Get<Message>(1);
                message.Content = "Message_Leoli2";
                session.Save(message);
                session.Flush();
                Assert.AreEqual(message.LastEditor, "Leoli_Update_Event");
            }
        }
Example #34
0
 public void generate()
 {
     var cfg = new Configuration();
     cfg.Configure();
     cfg.AddAssembly(typeof(Question).Assembly);
     new SchemaExport(cfg).Execute(false, true, false);
 }
        static void Main(string[] args)
        {
            Console.WriteLine("Started publisher and inserting data.");
            Publisher.Start();
    
            var config = new Configuration();
            config.Configure("nh.sqlserver.config");
            config.SessionFactoryName("Test session factory");
            config.AddAssembly(typeof(Dog).Assembly);

            new SchemaUpdate(config).Execute(false, true);
            
            using(var sessionFactory = config.BuildSessionFactory())
            {
                Stopwatch sw = new Stopwatch();

                sw.Start();
                InsertData(sessionFactory);
                Console.WriteLine("Inserting data  with logging took: {0}", sw.Elapsed);

                sw.Restart();
                Publisher.Shutdown();
                Console.WriteLine("Publisher shutdown complete in {0}", sw.Elapsed);

                Console.WriteLine("inserting data with publisher shutdown");
                sw.Restart();
                InsertData(sessionFactory);
                Console.WriteLine("Inserting data  without logging took: {0}", sw.Elapsed);
            }
            Console.ReadLine();
        }
 private static Configuration GetConfiguration()
 {
     var config = new Configuration();
     config.Configure();
     config.ConfigureMembershipReboot();
     return config;
 }
Example #37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SessionManager"/> class.
 /// </summary>
 private SessionManager()
 {
     _configuration = new NHibernate.Cfg.Configuration();
     _configuration.Configure();
     _sessionFactory = Fluently.Configure(_configuration)
                       .Mappings(m => m.FluentMappings.AddFromAssemblyOf <CategoryMap>())
                       .BuildSessionFactory();
 }
Example #38
0
        static SessionFactory()
        {
            mapper.AddMappings(typeof(SessionFactory).Assembly.GetTypes());

            configuraion.Configure();

            configuraion.AddMapping(mapper.CompileMappingForAllExplicitlyAddedEntities());
        }
Example #39
0
        public static void Generate()
        {
            var cfg = new NHibernate.Cfg.Configuration();

            cfg.Configure();
            cfg.AddAssembly(typeof(Domain.Contact).Assembly);
            new NHibernate.Tool.hbm2ddl.SchemaExport(cfg).Execute(true, true, false);
        }
        /// <summary>
        /// Create a nhibernate Session Factory for Given client
        /// </summary>
        /// <returns></returns>

        public static ISessionFactory GetSessionFactory()
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            cfg.Configure();

            ISessionFactory sessionFactory = cfg.BuildSessionFactory();

            return(sessionFactory);
        }
Example #41
0
        static DataAccesser()
        {
            //NHibernate's Config Initialize
            config = new NHibernate.Cfg.Configuration();
            config.Configure();
            config.AddClass(typeof(Computer));

            //SessionFactory Initialize
            sessionFactory = config.BuildSessionFactory();
        }
Example #42
0
        /// <summary>
        /// 初始化session工程
        /// </summary>
        private void InitSessionFactory()
        {
            NHibernate.Cfg.Configuration sourceConfig
                = new NHibernate.Cfg.Configuration();


            Configuration config = null;

            if (string.IsNullOrWhiteSpace(ConfigFile))
            {
                config = sourceConfig.Configure();
            }
            else
            {
                config = sourceConfig.Configure(ConfigFile);
            }

            var fluentlyConfig = Fluently.Configure(config)
                                 .ExposeConfiguration(AddAuditor)
                                 .Mappings(m =>
            {
                CommonFunctions.LoadAssembly(
                    assembly =>
                {
                    m.HbmMappings.AddFromAssembly(assembly);
                },
                    "*.xml.dll");
                CommonFunctions.LoadAssembly(
                    assembly =>
                {
                    m.FluentMappings.AddFromAssembly(assembly);
                },
                    "*.Model.dll");
                // m.MergeMappings();
            }
                                           )
                                 // .Mappings(m => m.FluentMappings.Add<AuditLogMasterMap>())
                                 // .Mappings(m => m.FluentMappings.Add<AuditLogDetailMap>())
            ;

            this.sessionFactory = fluentlyConfig.BuildSessionFactory();
        }
Example #43
0
        public static ISessionFactory GetSessionFactory()
        {
            var configuration = new NHibernate.Cfg.Configuration();

            configuration.Configure();
            configuration.AddAssembly(typeof(SessionFactoryFactory).Assembly.GetName().Name);
            log4net.Config.XmlConfigurator.Configure();
            var sessionFactory = configuration.BuildSessionFactory();

            return(sessionFactory);
        }
Example #44
0
        ISession OpenSession()
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            cfg.Configure("hibernate-attr.cfg.xml");

            NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true; // Enable validation (optional)
            cfg.AddInputStream(NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(System.Reflection.Assembly.GetAssembly(typeof(DeliveryOrder))));
            ISessionFactory f = cfg.BuildSessionFactory();

            return(f.OpenSession());
        }
        public void Configure(IEnumerable <Type> typesToMap, string tablePrefix)
        {
            _tablePrefix = tablePrefix;

            configuration = new NHibernate.Cfg.Configuration();

            configuration.Configure();

            var xml = BuildMappingXml(typesToMap);

            configuration.AddXml(xml);
        }
        public static void SetUp()
        {
            Configuration cfg = new NHibernate.Cfg.Configuration();

            cfg.Configure();

            NHibernate.Tool.hbm2ddl.SchemaExport schema = new NHibernate.Tool.hbm2ddl.SchemaExport(cfg);
            //schema.Create(true, false);

            schema.Execute(false, true, false);
            Console.WriteLine("Done");
            Console.ReadLine();
        }
Example #47
0
        /// <summary>
        /// 初始化session工程
        /// </summary>
        public static ISessionFactory ExposeConfiguration(
            Action <MappingConfiguration> mappings,
            Action <Configuration> config)
        {
            NHibernate.Cfg.Configuration sourceConfig = new NHibernate.Cfg.Configuration();

            return
                (Fluently.Configure(sourceConfig.Configure())
                 .Mappings(mappings)
                 .ExposeConfiguration(config)
                 .ExposeConfiguration(AddAuditor)
                 .BuildSessionFactory());
        }
Example #48
0
        public static ISession OpenSession()
        {
            var configuration     = new NHibernate.Cfg.Configuration();
            var configurationPath = HttpContext.Current.Server.MapPath(@"~\Models\Nhibernate\nhibernate.cfg.xml");

            configuration.Configure(configurationPath);
            var candidateConfigurationFile = HttpContext.Current.Server.MapPath(@"~\Models\Nhibernate\nhibernate.hbm.xml");

            configuration.AddFile(candidateConfigurationFile);
            ISessionFactory sessionFactory = configuration.BuildSessionFactory();

            return(sessionFactory.OpenSession());
        }
        public static ISession OpenSession()
        {
            Configuration configuration1    = new NHibernate.Cfg.Configuration();
            string        configurationPath = HttpContext.Current.Server.MapPath(@"~\Models\hibernate.cfg.xml");

            configuration1.Configure(configurationPath);
            string bookConfigurationFile = HttpContext.Current.Server.MapPath(@"~\Mappings\Book.hbm.xml");

            configuration1.AddFile(bookConfigurationFile);
            ISessionFactory sessionFactory = configuration1.BuildSessionFactory();

            return(sessionFactory.OpenSession());
        }
Example #50
0
        public void TestConfigMappingByCode()
        {
            var config = new NHibernate.Cfg.Configuration();

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

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

            var factory = config.BuildSessionFactory();
        }
Example #51
0
        public NHibernate.Cfg.Configuration Configure()
        {
            SetAssemblyBinding();

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

            // NOTE: the NHibernate documentation states that this file would be automatically loaded, however in testings this was not the case.
            // The expectation is that this file will be in the binaries location.
            configuration.Configure(
                Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "hibernate.cfg.xml"));

            // Add the configuration to the container
            configuration.BeforeBindMapping += Configuration_BeforeBindMapping;

            // Configure the mappings
            var ormMappingFileData = _ormMappingFileDataProvider.OrmMappingFileData();

            configuration.AddResources(ormMappingFileData.MappingFileFullNames, ormMappingFileData.Assembly);

            //Resolve all extension assemblies and add to NHibernate configuration
            _extensionConfigurationProviders.ForEach(
                e => configuration.AddResources(e.OrmMappingFileData.MappingFileFullNames, e.OrmMappingFileData.Assembly));

            // Invoke configuration activities
            foreach (var configurationActivity in _configurationActivities)
            {
                configurationActivity.Execute(configuration);
            }

            configuration.AddCreateDateHooks();

            return(configuration);

            void SetAssemblyBinding()
            {
                // NHibernate does not behave nicely with assemblies that are loaded from another folder.
                // By default NHibernate tries to load the assembly from the execution folder.
                // In our case we have pre loaded the assemblies into the domain, so we just need to tell NHibernate to pull the loaded
                // assembly. Setting the AssemblyResolve event fixes this. c.f. https://nhibernate.jira.com/browse/NH-2063 for further details.
                var assemblies = AppDomain.CurrentDomain.GetAssemblies();

                AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
                {
                    var assemblyName = e.Name.Split(",")[0];

                    return(assemblies.FirstOrDefault(a => a.GetName().Name.EqualsIgnoreCase(assemblyName)));
                };
            }
        }
        private static ISessionFactory BuildSessionFactory()
        {
            _config = new NHibernate.Cfg.Configuration();

            var hibernateConfig = "hibernate.cfg.xml";

            //if not rooted, assume path from base directory
            if (System.IO.Path.IsPathRooted(hibernateConfig) == false)
            {
                hibernateConfig = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, hibernateConfig);
            }
            if (System.IO.File.Exists(hibernateConfig))
            {
                using (var xmlTextReader = new System.Xml.XmlTextReader(hibernateConfig))
                {
                    _config.Configure(xmlTextReader);
                }
            }
            else
            {
                // Look for config section in web.config
                _config.Configure();
            }

            ServiceLocator.Current.GetInstance <IDatabaseManager>().RemoveSchemas(_config);

            var factory = _config.BuildSessionFactory();

            ServiceLocator.Current.GetInstance <IDatabaseManager>().ExportDBSchema(_config);

            //UpdateDatabaseSchema(_config);

            ObjectGraphWalker.Initialize(_config);

            return(factory);
        }
        public static ISessionFactory GetSessionFactory()
        {
            var configuration = new NHibernate.Cfg.Configuration();

            configuration.Configure();
            configuration.AddAssembly(typeof(SessionFactoryFactory).Assembly.GetName().Name);

            configuration.SetProperty(Environment.ConnectionString,
                                      ConfigurationManager.ConnectionStrings["ProjectTemplate"].ConnectionString);

            log4net.Config.XmlConfigurator.Configure();
            var sessionFactory = configuration.BuildSessionFactory();

            return(sessionFactory);
        }
 private void Init()
 {
     /*Configuration config = new Configuration();
      * config.AddAssembly("ContactManager.Repository");
      * //log4net.Config.XmlConfigurator.Configure();
      * config.Configure();
      * _sessionFactory = config.BuildSessionFactory();
      * */
     NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
     config.Configure();
     //string mappingAssembly = ConfigurationManager.AppSettings["NHibernate.Mapping.Assembly"];
     _sessionFactory = Fluently.Configure(config).Mappings(m => m.FluentMappings
                                                           .AddFromAssemblyOf <UserMap>()
                                                           )
                       .BuildSessionFactory();
 }
        public static CoreNHibernate.ISessionFactory CreateSessionFactoryFromXML(string assemblyPath)
        {
            CoreNHibernate.Cfg.Configuration config = new CoreNHibernate.Cfg.Configuration();

            config.Configure();
            //config.AddFile(@"D:\Bilisim\SVN\bilisimHR\Web\trunk\bilisimHR.DataLayer.NHibernate.Tests\bin\x64\Debug\Mappings\HBM\Roles.hbm.xml");
            //config.AddFile(@"D:\Bilisim\SVN\bilisimHR\Web\trunk\bilisimHR.DataLayer.NHibernate.Tests\bin\x64\Debug\Mappings\HBM\Users.hbm.xml");
            //config.AddFile(@"D:\Bilisim\SVN\bilisimHR\Web\trunk\bilisimHR.DataLayer.NHibernate.Tests\bin\x64\Debug\Mappings\HBM\Category.hbm.xml");
            //config.AddFile(@"D:\Bilisim\SVN\bilisimHR\Web\trunk\bilisimHR.DataLayer.NHibernate.Tests\bin\x64\Debug\Mappings\HBM\Item.hbm.xml");
            config.AddAssembly("bilisimHR.DataLayer.Core");
            //..Todo.....

            new SchemaExport(config).Execute(true, false, false);
            //new SchemaUpdate(config).Execute(false, true);
            return(config.BuildSessionFactory());
        }
Example #56
0
        /// <summary>
        /// 根据NHibernate配置节点,获得DbConnection
        /// </summary>
        /// <returns></returns>
        public static DbConnection CreateConnection()
        {
            NHibernate.Cfg.Configuration sourceConfig
                = new NHibernate.Cfg.Configuration();

            var configure = sourceConfig.Configure().Properties["connection.connection_string_name"];

            var providerName     = System.Configuration.ConfigurationManager.ConnectionStrings[configure].ProviderName;
            var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[configure].ConnectionString;

            var DbProviderFactory = DbProviderFactories.GetFactory(providerName);

            DbConnection connection = DbProviderFactory.CreateConnection();

            connection.ConnectionString = connectionString;
            return(connection);
        }
        NHibernate.Cfg.Configuration ApplyDatabaseIntegration(NHibernate.Cfg.Configuration configuration)
        {
            if (_databaseIntegration == null)
            {
                configuration = configuration.Configure();
            }

            configuration.DataBaseIntegration(c =>
            {
                if (_databaseIntegration != null)
                {
                    _databaseIntegration(c);
                }

                c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                c.SchemaAction       = SchemaAutoAction.Update;
            });

            return(configuration);
        }
        private static ISessionFactory CriaSessionFactory()
        {
            try
            {
                NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
                cfg.Configure();
                ISessionFactory factory = Fluently.Configure(cfg)
                                          .Mappings(x =>
                {
                    x.FluentMappings.AddFromAssembly(
                        Assembly.GetExecutingAssembly());
                }).BuildSessionFactory();

                return(factory);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public static Configuration GetConfig()
        {
            var cfg = new Configuration();

            cfg.Configure()
            .CurrentSessionContext <ThreadStaticSessionContext>()
            .Cache(c =>
            {
                //c.UseQueryCache = true;
                //c.UseMinimalPuts = true;
            });

            Utils.Config.Load();
            cfg.DataBaseIntegration(
                properties => properties.ConnectionString = Utils.Config.GetProperty("DefaultConnectionString"));

            InitProperties(cfg);

            InitMapping(cfg);

            return(cfg);
        }
Example #60
0
        /// <summary>
        /// 初始化session工程
        /// </summary>
        public static ISessionFactory ExposeConfiguration(
            Action <MappingConfiguration> mappings,
            string fileName)
        {
            NHibernate.Cfg.Configuration sourceConfig = new NHibernate.Cfg.Configuration();

            return
                (Fluently.Configure(sourceConfig.Configure())
                 .Mappings(mappings)
                 .ExposeConfiguration(config =>
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }


                new SchemaExport(config).SetOutputFile(fileName).Create(true, false);
            })
                 .ExposeConfiguration(AddAuditor)
                 .BuildSessionFactory());
        }