Ejemplo n.º 1
0
        protected void CreateDatabase()
        {
            NHibernate.Cfg.Configuration configuration = _config.GetConfiguration();
            var session = configuration.BuildSessionFactory().OpenSession();

            CreateSchema(configuration, session);
        }
Ejemplo n.º 2
0
        private void EnsureMasterDatabaseExistence()
        {
            if (configuration == null)
            {
                lock (masterDatabaseSync)
                {
                    if (configuration == null)
                    {
                        string connectionString = BuildConnectionString(masterDatabaseFileName);

                        if (File.Exists(masterDatabaseFileName))
                        {
                            File.Delete(masterDatabaseFileName);
                        }

                        using (var engine = new SqlCeEngine(connectionString))
                        {
                            engine.CreateDatabase();
                        }

                        configuration  = BuildConfigurationInternal(masterDatabaseFileName);
                        sessionFactory = configuration.BuildSessionFactory();

                        using (var masterConnection = new SqlCeConnection(connectionString))
                        {
                            masterConnection.Open();

                            SchemaExport schemaExport = new SchemaExport(configuration);
                            schemaExport.Execute(false, true, false, masterConnection, TextWriter.Null);
                        }
                    }
                }
            }
        }
Ejemplo n.º 3
0
        static NHibernateConfigurator()
        {
            var sqlitePersistenceConfigurerProvider = new SqlitePersistenceConfigurerProvider();

#if DEBUG
            FluentConfigurationSerializer.IsEnabled = false;
#endif
            var configurationProvider = new FluentConfigurationProvider(sqlitePersistenceConfigurerProvider, new AssemblyLocator());

            _configuration = configurationProvider.Configure().GetEnumerator().Current;

            _configuration = _configuration.DataBaseIntegration(db => db.ConnectionProvider <TestConnectionProvider> ());
            _configuration.SetProperty(Environment.CurrentSessionContextClass, "thread_static");

            var props = _configuration.Properties;
            if (props.ContainsKey(Environment.ConnectionStringName))
            {
                props.Remove(Environment.ConnectionStringName);
            }

            // This line is only for TFS integration build MSTest runner
            ForceLoadingAssembliesForMsTestRunner();

            _sessionFactory = _configuration.BuildSessionFactory();
        }
Ejemplo n.º 4
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();
        }
        /// <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;
              }
        }
 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);
 }
Ejemplo n.º 7
0
 public static void Init()
 {
     try
     {
         NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
         string path        = string.Empty;
         string wanted_path = System.IO.Directory.GetCurrentDirectory();
         if (string.IsNullOrEmpty(configfilepath))
         {
             path = wanted_path + "\\hibernate.cfg.xml";
         }
         else
         {
             path = configfilepath;
         }
         config.Configure(path);
         config.AddAssembly(Assembly.GetExecutingAssembly());//adds all the embedded resources .hbm.xml
         sFactory = config.BuildSessionFactory();
     }
     catch (Exception ex)
     {
         throw ex;
         //Console.Write(ex.StackTrace);
         //logger.Error(ex.Message);
     }
 }
 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);
 }
Ejemplo n.º 9
0
        private TagsDAO()
        {
            //在构造函数中获取配置,并产生SessionFactory
            var cfg = new NHibernate.Cfg.Configuration().Configure("../../Config/hibernate.cfg.xml");

            sessionFactory = cfg.BuildSessionFactory();
        }
        public ProgrammaticDatabaseConfiguration()
        {
            var config = new NHibernate.Cfg.Configuration()
                         .SetProperty(Environment.ReleaseConnections, "on_close")
                         .SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName)
                         .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
                         .SetProperty(Environment.ConnectionString, "data source=:memory:")
                         .SetProperty(Environment.ShowSql, "true")
                         .SetProperty(Environment.FormatSql, "true");

            var modelMapper = new ModelMapper();

            modelMapper.AddMapping <EmployeeMappings>();
            modelMapper.AddMapping <AddressMappings>();
            modelMapper.AddMapping <BenefitMappings>();
            modelMapper.AddMapping <LeaveMappings>();
            modelMapper.AddMapping <SkillsEnhancementAllowanceMappings>();
            modelMapper.AddMapping <SeasonTicketLoanMappings>();
            modelMapper.AddMapping <CommunityMappings>();

            config.AddMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities());

            var sessionFactory = config.BuildSessionFactory();

            session = sessionFactory.OpenSession();
            using (var tx = session.BeginTransaction())
            {
                new SchemaExport(config).Execute(true, true, false, session.Connection, Console.Out);
                tx.Commit();
            }
            session.Clear();
        }
Ejemplo n.º 11
0
        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);
            }
        }
Ejemplo n.º 12
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();
        }
        public InMemoryNHibernateSessionSource(IEnumerable <Assembly> mappingAssemblies)
        {
            _configuration = Fluently.Configure()
                             .Database(SQLiteConfiguration.Standard.ConnectionString("FullUri=file:memorydb.db?mode=memory&cache=shared"))
                             .ExposeConfiguration(
                c =>
            {
                c.SetProperty(NHibernate.Cfg.Environment.CommandTimeout,
                              TimeSpan.FromMinutes(3).TotalSeconds.ToString(CultureInfo.InvariantCulture));
            })
                             .Mappings(x =>
            {
                foreach (var mappingAssembly in mappingAssemblies)
                {
                    x.FluentMappings.AddFromAssembly(mappingAssembly);
                }
            }).BuildConfiguration();

            _factory = _configuration.BuildSessionFactory();
            _connectionCreatingSession = _factory.OpenSession();
            var connection = _connectionCreatingSession.Connection;

            new SchemaExport(_configuration).Execute(
                false,
                true,
                justDrop: false,
                connection: connection,
                exportOutput: null);
            var export = new SchemaUpdate(_configuration);

            export.Execute(true, true);
        }
Ejemplo n.º 14
0
        public static void Init()
        {
            //数据库配置文件完全地址
            string dbConfigFullPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App.config");

            //Hibernate加载数据库配置文件
            NHibernate.Cfg.Configuration nHConfiguration = new NHibernate.Cfg.Configuration().Configure("App.config");
            //获得session工厂
            var sessionFactory = nHConfiguration.BuildSessionFactory();

            using (var session = sessionFactory.OpenSession())
            {
                var customer = new DAO.Model.Person()
                {
                    Id      = 5,
                    Name    = "卤鸽",
                    Address = "博客园",
                };
                //插入数据
                session.Save(customer);
                session.Flush();
                //get是直接执行sql语句得到实体对象
                var getCustomer = session.Get <DAO.Model.Person>(1);
                getCustomer.Name = "飞鸽";
                session.SaveOrUpdate(getCustomer);
                session.Flush();
                //load主要在是需要调用的时候才进行执行sql语句
                //var loadCustomer = session.Load<Person>("luge");
                //session.Delete(loadCustomer);
                //session.Flush();
// 测试主修该 ,forer变化
            }
        }
Ejemplo n.º 15
0
        public MsSqlSessionFactory(IUnityContainer unityContainer)
        {
            //string connectionstring = @"Initial Catalog=trex.dk;user id=trexUser;Password=ch33seD1pper;";

            //String hostName = Environment.MachineName;
            //switch (hostName)
            //{
            //    case "otherpc":
            //        connectionstring = @"";
            //        break;
            //    case "WIN-B8C38AQEHEF":
            //    case "WIN-5F68BM93R0K":
            //        connectionstring = @"Server=.;Database=Trex_test;Trusted_Connection=true;";
            //        break;
            //}

            if (TenantConnectionProvider.DynamicString == null)
            {
                TenantConnectionProvider.DynamicString = ConfigurationManager.ConnectionStrings["TrexBase"].ConnectionString;
            }

            _config = Fluently.Configure().Database(MsSqlConfiguration.MsSql2008.ConnectionString(TenantConnectionProvider.DynamicString)
                                                    .ShowSql().Provider <TenantConnectionProvider>())
                      .Mappings(m => m.FluentMappings.AddFromAssemblyOf <TaskMap>()
                                .Conventions.AddFromAssemblyOf <FluentNhibernateConfig>())
                      .BuildConfiguration();
            _config.SetListener(ListenerType.PostInsert, new GenericEntityChangeTracker(unityContainer));
            _config.SetListener(ListenerType.PostUpdate, new GenericEntityChangeTracker(unityContainer));
            _sessionFactory = _config.BuildSessionFactory();

            _schema = new SchemaExport(_config);

            CreateSchema();
        }
Ejemplo n.º 16
0
        private static void BuildSessionFactory(NHibernate.Cfg.Configuration cfg)
        {
            try
            {
                // Use NHibernate.Mapping.Attributes to create information about our entities
                System.IO.MemoryStream stream = new System.IO.MemoryStream();        // Where the information will be written in
                NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true; // Enable validation (optional)
                // Ask to NHibernate to use fields instead of properties
                NHibernate.Mapping.Attributes.HbmSerializer.Default.HbmDefaultAccess = "field.camelcase-underscore";
                // Gather information from this assembly (can also be done class by class)
                //System.Console.Out.WriteLine("NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize()...\n");
                NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(stream, System.Reflection.Assembly.GetExecutingAssembly());
                stream.Position = 0;
                //               StreamReader sr = new StreamReader(stream);

                //            string IbDoc = sr.ReadToEnd();
                cfg.AddInputStream(stream); // Send the Mapping information to NHibernate Configuration
                stream.Close();
                // Create table(s) in the database for our entities
                //   System.Console.Out.WriteLine("new NHibernate.Tool.hbm2ddl.SchemaExport(cfg).Create()...");
                // Build the SessionFactory
                //   System.Console.Out.WriteLine("\n\nsessionFact = cfg.BuildSessionFactory();\n\n");
                SessionFactory = cfg.BuildSessionFactory();
            }
            catch (Exception e)
            {
                throw new Exception("An error occurred while building the NHibernate Session Factory used for internal data storage." + Environment.NewLine +
                                    "Error CNF-370 in " + PROJ_FILE_NAME + ".BuildSessionFactory(): " + e.Message);
            }
        }
Ejemplo n.º 17
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();
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 创建 SessionFactory
        /// </summary>
        public static void CreateSessionFactory(string cfgFile)
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure(cfgFile);

            // where the xml will be written
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                // Enable validation (optional)
                NHibernate.Mapping.Attributes.HbmSerializer.Default.Validate = true;
                // Here, we serialize all decorated classes (but you can also do it class by class)
                NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize(stream, Assembly.GetAssembly(typeof(Model.D_User_Model)));
                // Rewind
                stream.Position = 0;

                try
                {
                    System.IO.File.WriteAllBytes(cfgFile.Substring(0, cfgFile.LastIndexOf("\\") + 1) + "Mapping.cfg.xml", stream.GetBuffer());
                }
                catch (System.UnauthorizedAccessException) { }
                finally
                {
                    cfg.AddInputStream(stream); // Use the stream here
                }
            }

            m_SessionFactory = cfg.BuildSessionFactory();

            //m_SessionFactory = new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory();
        }
        /// <summary>
        /// Adds NHibernate core components to the DI system.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="databaseConfiguration">NHibernate database configuration.</param>
        /// <param name="configurationStoreOptions">Configuration store options (needed to configure NHibernate mappings).</param>
        /// <param name="operationalStoreOptions">Operational store options (needed to configure NHibernate mappings).</param>
        private static IIdentityServerBuilder AddNHibernatePersistenceSupport(
            this IIdentityServerBuilder builder,
            NHibernate.Cfg.Configuration databaseConfiguration,
            ConfigurationStoreOptions configurationStoreOptions,
            OperationalStoreOptions operationalStoreOptions)
        {
            // Adds NHibernate mappings
            databaseConfiguration.AddConfigurationStoreMappings(configurationStoreOptions);
            databaseConfiguration.AddOperationalStoreMappings(operationalStoreOptions);

            //We need this to quote fields named with reserved keyword
            SchemaMetadataUpdater.QuoteTableAndColumns(databaseConfiguration, Dialect.GetDialect(databaseConfiguration.Properties));

            // Registers NHibernate components
            builder.Services.AddSingleton(databaseConfiguration.BuildSessionFactory());
            builder.Services.AddScoped(provider =>
            {
                var factory = provider.GetService <ISessionFactory>();
                return(factory.OpenSession());
            });
            builder.Services.AddScoped(provider =>
            {
                var factory = provider.GetService <ISessionFactory>();
                return(factory.OpenStatelessSession());
            });

            return(builder);
        }
Ejemplo n.º 20
0
        private static void Init()
        {
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.AddAssembly(typeof(Product).Assembly);

            _factory = config.BuildSessionFactory();
        }
        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();
        }
Ejemplo n.º 22
0
        private void PrepareSessionFactory(string connectionString)
        {
            IDictionary <string, string> properties = new Dictionary <string, string>
            {
                {
                    "connection.driver_class",
                    "NHibernate.Driver.MySqlDataDriver"
                },
                { "connection.connection_string", connectionString },
                {
                    "proxyfactory.factory_class",
                    "NHibernate.ByteCode.Castle.ProxyFactoryFactory,NHibernate.ByteCode.Castle"
                },
                { "dialect", "NHibernate.Dialect.MySQL5Dialect" }
            };

            NHibernate.Cfg.Configuration configuration = new NHibernate.Cfg.Configuration();
            configuration.SetProperties(properties);

            foreach (
                FileInfo file in
                new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "database")).GetFiles("*.dll"))
            {
                configuration.AddAssembly(Assembly.LoadFile(file.FullName));
            }

            _nHibernateSessionFactory = configuration.BuildSessionFactory();
        }
Ejemplo n.º 23
0
 public static void Init()
 {
     try
     {
         NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
         string path        = string.Empty;
         string wanted_path = System.IO.Directory.GetCurrentDirectory();
         if (string.IsNullOrEmpty(configfilepath))
         {
             //                  var appEnv = CallContextServiceLocator.Locator.ServiceProvider
             //.GetService(typeof(IApplicationEnvironment)) as IApplicationEnvironment;
             //  path = System.IO.Path.Combine(System.Reflection.Assembly.GetExecutingAssembly().Location, "hibernate.cfg.xml");
             //path = System.Reflection.Assembly.GetExecutingAssembly().Location;
             // path = @"D:\bitbucket\Updated\src\SocioboardDataServices\hibernate.cfg.xml";
             path = wanted_path + "\\hibernate.cfg.xml";
         }
         else
         {
             path = configfilepath;
         }
         config.Configure(path);
         config.AddAssembly(Assembly.GetExecutingAssembly());//adds all the embedded resources .hbm.xml
         sFactory = config.BuildSessionFactory();
     }
     catch (Exception ex)
     {
         throw ex;
         //Console.Write(ex.StackTrace);
         //logger.Error(ex.Message);
     }
 }
Ejemplo n.º 24
0
        private static ISessionFactory GetFactory()
        {
            if (sessionFactory == null)
            {
                HttpContext currentContext = HttpContext.Current;

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

                if (config == null)
                {
                    throw new InvalidOperationException("Nhibernate configuration is null");
                }

                var path = string.IsNullOrEmpty(HttpRuntime.AppDomainAppId) ? AppDomain.CurrentDomain.BaseDirectory : HttpRuntime.AppDomainAppPath;

                config.Configure(string.Format("{0}/Config/Nhibernate/HttpReadNHibernate.cfgl.xml", path));

                sessionFactory = config.BuildSessionFactory();

                if (sessionFactory == null)
                {
                    throw new InvalidOperationException("Call to Configuration.BuildSessionFactory() returned null.");
                }
            }
            return(sessionFactory);
        }
Ejemplo n.º 25
0
        /// <summary>
        ///   Initializes this instance.
        /// </summary>
        /// <param name="configure"></param>
        public void Initialize(Action <Configuration> configure)
        {
            Configuration = new Configuration();
            if (string.IsNullOrWhiteSpace(ConfigurationFile))
            {
                missingConfigurations.Add(
                    new MissingConfiguration(
                        "Property ConfigurationFile of NHibernateContext is required. Maybe you forgot to add the key NHibernate.ConfigurationFile in the <appSettings> section of your configuration file."));
                return;
            }

            var path = LocalPath.From(ConfigurationFile);

            Log.Info(string.Format("Loading NHibernate Configuration from {0}", path));
            Configuration.Configure(path);
            Log.Info(string.Format("End Loading NHibernate Configuration from {0}", path));

            if (!ValidateConnectionStringExistence(Configuration))
            {
                return;
            }

            configure(Configuration);

            Log.Info("Building new Hibernate Session Factory");
            sessionFactory = Configuration.BuildSessionFactory();
            Log.Info("En Building new Hibernate Session Factory");
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Adds NHibernate core components to the DI system.
        /// </summary>
        /// <param name="builder">The builder.</param>
        /// <param name="databaseConfiguration">NHibernate database configuration.</param>
        /// <param name="configurationStoreOptions">Configuration store options (needed to configure NHibernate mappings).</param>
        /// <param name="operationalStoreOptions">Operational store options (needed to configure NHibernate mappings).</param>
        private static IIdentityServerBuilder AddNHibernatePersistenceSupport(
            this IIdentityServerBuilder builder,
            NHibernate.Cfg.Configuration databaseConfiguration,
            ConfigurationStoreOptions configurationStoreOptions,
            OperationalStoreOptions operationalStoreOptions)
        {
            // Adds NHibernate mappings
            databaseConfiguration.AddConfigurationStoreMappings(configurationStoreOptions);
            databaseConfiguration.AddOperationalStoreMappings(operationalStoreOptions);

            // Registers NHibernate components
            builder.Services.AddSingleton(databaseConfiguration.BuildSessionFactory());
            builder.Services.AddScoped(provider =>
            {
                var factory = provider.GetService <ISessionFactory>();
                return(factory.OpenSession());
            });
            builder.Services.AddScoped(provider =>
            {
                var factory = provider.GetService <ISessionFactory>();
                return(factory.OpenStatelessSession());
            });

            return(builder);
        }
Ejemplo n.º 27
0
 public static void Init(IHostingEnvironment env)
 {
     try
     {
         NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
         string path = string.Empty;
         if (string.IsNullOrEmpty(configfilepath))
         {
             //  var appEnv = CallContextServiceLocator.Locator.ServiceProvider.GetService(typeof(IHostingEnvironment)) as IHostingEnvironment;
             path = System.IO.Path.Combine(env.ContentRootPath, "hibernate.cfg.xml");
             //path = @"D:\Suresh\BickBucket\src\Api.Socioboard\hibernate.cfg.xml";
         }
         else
         {
             path = configfilepath;
         }
         config.Configure(path);
         config.AddAssembly(Assembly.GetExecutingAssembly());//adds all the embedded resources .hbm.xml
         sFactory = config.BuildSessionFactory();
     }
     catch (Exception ex)
     {
         throw ex;
         //Console.Write(ex.StackTrace);
         //logger.Error(ex.Message);
     }
 }
Ejemplo n.º 28
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

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

            configuration.Configure();
            configuration.AddAssembly(typeof(Log).Assembly);
            ISessionFactory sessionFactory = configuration.BuildSessionFactory();

            // Ninject
            Ninject.IKernel container = new StandardKernel();

            // Set Web API Resolver
            GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(container);
            container.Bind <ISessionFactory>().ToConstant(sessionFactory);

            container.Bind <ISessionManager>().To <SessionManager>();
            container.Bind <IRepository>().To <GenericRepository>();

            container.Bind <IApplicationService>().To <ApplicationService>();
            container.Bind <ITokenService>().To <TokenService>();
            container.Bind <ILogService>().To <LogService>();

            container.Bind <IApplicationMapper>().To <ApplicationMapper>();
        }
Ejemplo n.º 29
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();
            }
        }
Ejemplo n.º 30
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            log4net.Config.XmlConfigurator.Configure();
            MvcHandler.DisableMvcResponseHeader = true;

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            EmailVerifier.RuntimeLicenseKey = "G016NUILAeGgF81JMB03zbbnuDKKCWJhQ9XYfo8HVhhJLA+Uk2l8Jqyqumxb9Pn78MEhaA==";

            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            Core.User.CurrentUserId = "NewWebsite";
            foreach (var t in  typeof(Area).Assembly.GetTypes().Where(t => t.IsSubclassOf(typeof(MetaBase))))
            {
                BaseEntity.MetaTypes.Add(t);
            }

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

            config.Configure();
            config.AddAssembly(typeof(NHibernateHelper).Assembly);
            config.AddAssembly(typeof(Page).Assembly);
            Global.SessionFactory = config.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;
        }
Ejemplo n.º 32
0
        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);
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// 静态构造函数
        /// </summary>
        static NHHelper()
        {
            var config = new NHibernate.Cfg.Configuration();

            config.Configure();
            factory = config.BuildSessionFactory();
        }
Ejemplo n.º 34
0
        static void Main(string[] args)
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            cfg.AddAssembly("DomainObjects");

            ISessionFactory sessionFactory = cfg.BuildSessionFactory();
        }
Ejemplo n.º 35
0
        public static ISessionFactory FactoryGet()
        {
            ISessionFactory factory = null;

            if (HttpContext.Current != null)
            {
                try
                {
                    factory = (ISessionFactory)HttpContext.Current.Application[ContextFactoryKey];
                }
                catch (Exception)
                {
                }
            }

            if (factory == null)
            {
                try
                {
                    NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
                    cfg.Configure(System.Web.HttpContext.Current.Server.MapPath("~/hibernate.cfg.xml.config"));
                    factory = cfg.BuildSessionFactory();

                    if (HttpContext.Current != null)
                    {
                        HttpContext.Current.Application[ContextFactoryKey] = factory;
                    }
                }
                catch (Exception)
                {
                }
            }

            return(factory);
        }
Ejemplo n.º 36
0
        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();
        }
Ejemplo n.º 37
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 ProgrammaticDatabaseConfigurationFull()
        {
            var config = new NHibernate.Cfg.Configuration()
                         .SetProperty(Environment.ReleaseConnections, "on_close")
                         .SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName)
                         .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName)
                         .SetProperty(Environment.ConnectionString, "data source=:memory:")
                         .SetProperty(Environment.ShowSql, "true")
                         .SetProperty(Environment.UseQueryCache, "true")
                         .SetProperty(Environment.CurrentSessionContextClass,
                                      typeof(ThreadLocalSessionContext).AssemblyQualifiedName)
                         .SetProperty(Environment.BatchSize, "20")
                         .SetProperty(Environment.CommandTimeout, "30");

            var modelMapper = new ModelMapper();

            modelMapper.AddMappings(typeof(EmployeeMappings).Assembly.GetTypes());
            config.AddMapping(modelMapper.CompileMappingForAllExplicitlyAddedEntities());

            var sessionFactory = config.BuildSessionFactory();

            session = sessionFactory.OpenSession();
            using (var tx = session.BeginTransaction())
            {
                new SchemaExport(config).Execute(true, true, false, session.Connection, Console.Out);
                tx.Commit();
            }
            session.Clear();
        }
        public void configTest()
        {
            var cfg = new NHibernate.Cfg.Configuration().Configure("hibernate.cfg.xml");
            using (ISessionFactory sessionFactory = cfg.BuildSessionFactory()) {

            }
        }
Ejemplo n.º 40
0
        private void InitNHibernate()
        {
            var mapper = new ModelMapper();

            mapper.AddMappings(typeof(ProductoMap).Assembly.ExportedTypes);
            HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            string connectionString = _appConfiguration.GetConnectionString("DefaultConnection");

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

            configuration.DataBaseIntegration(c =>
            {
                c.Dialect <NHibernate.Dialect.MySQLDialect>();
                c.ConnectionString = connectionString;
                //c.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                //c.SchemaAction = SchemaAutoAction.Validate;
                #if (DEBUG)
                c.LogFormattedSql = true;
                c.LogSqlInConsole = true;
                #endif
            });

            configuration.AddMapping(domainMapping);

            var sessionFactory = configuration.BuildSessionFactory();

            this.DbSession = sessionFactory.OpenSession();

            #if (DEBUG)
            NHibernateLogger.SetLoggersFactory(new NHLoggerFactory(this.Log));
            #endif
        }
Ejemplo n.º 41
0
        public void Init()
        {
            var t      = ConfigurationManager.ConnectionStrings["Northwind"];
            var config = new NHibernate.Cfg.Configuration().Configure();

            sessionFactory = config.BuildSessionFactory();
        }
        public void TestFixtureSetUp()
        {
            container = new WindsorContainer();
            log4net.Config.XmlConfigurator.Configure();

            ConfigureWindsorContainer();

            Environment.UseReflectionOptimizer = true;
            Environment.BytecodeProvider       = new EnhancedBytecode(container);

            cfg = new NHibernate.Cfg.Configuration();

            cfg.Configure();

            cfg.Properties[Environment.ProxyFactoryFactoryClass]   = GetProxyFactoryFactory();
            cfg.Properties[Environment.CurrentSessionContextClass] = "thread_static";
            cfg.RegisterEntityNameResolver();
            cfg.Interceptor = GetInterceptor();
            cfg.AddAssembly(typeof(IntegrationBaseTest).Assembly);

            new SchemaExport(cfg).Create(true, true);
            sessions = (ISessionFactoryImplementor)cfg.BuildSessionFactory();


            var componentInterceptor = cfg.Interceptor as Castle.NHibernateInterceptor.ComponentBehaviorInterceptor;

            if (componentInterceptor != null)
            {
                componentInterceptor.SessionFactory = sessions;
            }
        }
Ejemplo n.º 43
0
 public virtual void SetUp()
 {
     var dataDirectory = ConfigurationManager.AppSettings["DataDirectory"];
     var absoluteDataDirectory = Path.GetFullPath(dataDirectory);
     AppDomain.CurrentDomain.SetData("DataDirectory", absoluteDataDirectory);
     _configuration = NHibernateInitializer.Initialize();
     _sessionFactory = _configuration.BuildSessionFactory();
 }
Ejemplo n.º 44
0
        /// <summary>
        /// initializes the session for database
        /// </summary>
        private static void Init()
        {
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();

            config.AddFile("db.cfg.xml");//adds all the embedded resources .hbm.xml
            config.AddFile("models.xml");
            sFactory = config.BuildSessionFactory();
        }
 protected void Application_Start(object sender, EventArgs e)
 {
     var cfg = new NHibernate.Cfg.Configuration().Configure(Server.MapPath("Config\\hibernate.cfg.xml"));
     NHibernate.ISessionFactory sessionFactory = cfg.BuildSessionFactory();
     Application.Add("sessionFactory", sessionFactory);
     SystemController sys = new SystemController((NHibernate.ISessionFactory)Application["sessionFactory"]);
     Application.Add("systemController", sys);
 }
Ejemplo n.º 46
0
 private SessionManager()
 {
     Configuration config = new Configuration();
     config.Properties[NHibernate.Cfg.Environment.ConnectionString] =
         ConfigurationManager.ConnectionStrings["AtomicCms"].ConnectionString;
     config.Configure();
     this.sessionFactory = config.BuildSessionFactory();
 }
        public ISessionFactory BuildSessionFactory(Configuration config)
        {
            var sessionFactory = config.BuildSessionFactory();

            if (sessionFactory == null)
                throw new Exception("Cannot build NHibernate Session Factory");

            return sessionFactory;
        }
 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;
 }
Ejemplo n.º 49
0
        static ISessionFactory BuildNHibernateSessionFactory()
        {
            var typesThatShouldBeMapped = Assembly.GetAssembly(typeof(UserProjection)).GetExportedTypes().Where(t => t.Namespace.EndsWith("DTOs"));
            var cfg = new NHibernate.Cfg.Configuration()
                .AddAutoMappings(typesThatShouldBeMapped)
                .Configure()
                .CreateDatabase();

            return cfg.BuildSessionFactory();
        }
Ejemplo n.º 50
0
        public static IDictionary<string, ISessionFactory> BuildSessionFactory()
        {
           // var configure = new Configuration();
            var mapping = GetMappings();
            //configure.Configure();
            //configure.AddDeserializedMapping(mapping, "NHSchema");
            if (!CommonHelper.AllowMultiTenancy(out _ConnectionStringName))
            {
                var config = new Configuration();
                // config.SetInterceptor(new NHSQLInterceptor());
                config.Configure();
                var _host = EngineContext.Current.Resolve<HttpContextBase>().Request.Url.Authority;
                config.AddDeserializedMapping(mapping, "NHSchema");

                config.Configure()
                    .SetProperty(NHibernate.Cfg.Environment.ConnectionStringName, _ConnectionStringName)
                    .
                    SetProperty(NHibernate.Cfg.Environment.ShowSql, "true")
                    .SetProperty(NHibernate.Cfg.Environment.BatchSize, "0")
                    .SetProperty(NHibernate.Cfg.Environment.CacheRegionPrefix, _host);

                if (!_allFactories.ContainsKey(_host))
                    _allFactories.Add(_host, config.BuildSessionFactory());

            }
            else
            {
                XmlNodeList nodes = ConfigurationFile.GetElementsByTagName("Tenant");

                foreach (XmlNode n in nodes)
                {

                    var config = new Configuration();
                    // config.SetInterceptor(new NHSQLInterceptor());
                    config.Configure();

                    config.AddDeserializedMapping(mapping, "NHSchema");

                    config.Configure()
                        .SetProperty(NHibernate.Cfg.Environment.ConnectionString, n["ConnectionString"].InnerText)
                        .
                        SetProperty(NHibernate.Cfg.Environment.ShowSql, "true")
                        .SetProperty(NHibernate.Cfg.Environment.BatchSize, "0")
                        .SetProperty(NHibernate.Cfg.Environment.CacheRegionPrefix, n["HostName"].InnerText);
                    //  config.SetInterceptor(new NHSQLInterceptor());

                    if (!_allFactories.ContainsKey(n["HostName"].InnerText))
                        _allFactories.Add(n["HostName"].InnerText, config.BuildSessionFactory());

                }
            }
            return _allFactories;


        }
Ejemplo n.º 51
0
        private static ISessionFactory BuildNHibernateSessionFacotory()
        {
            var typesThatShouldBeMapped = Assembly.GetAssembly(typeof(Entity)).GetExportedTypes().Where(t => t.Namespace.EndsWith("DTOs"));
            var cfg = new NHibernate.Cfg.Configuration();
            cfg.Properties[NHibernate.Cfg.Environment.CollectionTypeFactoryClass] = typeof(Sharetronix.Cfg.ForNHibernate.Net4CollectionTypeFactory).AssemblyQualifiedName;
            cfg = cfg.AddAutoMappings(typesThatShouldBeMapped, customClassMappings);

            if (isNewInstance)
                cfg.CreateDatabaseTables();

            return cfg.BuildSessionFactory();
        }
Ejemplo n.º 52
0
        public static void ClassInitialize(TestContext context)
        {
            var cfg = new NHibernate.Cfg.Configuration();

            Assembly assembly = Assembly.GetAssembly(typeof (TestDomain));
            var stream = assembly.GetManifestResourceStream("Jobsearch.Model.Tests.hibernate.cfg.xml");
            var reader = new XmlTextReader(stream);

            cfg.Configure(reader);
            NHibernateProfiler.Initialize();
            Session = cfg.BuildSessionFactory().OpenSession();
        }
Ejemplo n.º 53
0
        /// <summary>
        /// initializes the session for database
        /// </summary>
        private static void Init()
        {
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.SetProperty(NHibernate.Cfg.Environment.Dialect, "NHibernate.Dialect.PostgreSQL82Dialect");
            //NHibernate.Driver.NpgsqlDriver
            //config.SetProperty(NHibernate.Cfg.Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider");
            config.SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, "NHibernate.Driver.NpgsqlDriver");
            config.SetProperty(NHibernate.Cfg.Environment.ConnectionString, SessionFactory.connectionString);
            config.AddXmlFile(".\\AppFiles\\Database\\models.xml");

            sFactory = config.BuildSessionFactory();
        }
 public static void RegisterDependencies(IWindsorContainer container)
 {
     container
         .Register(
             Component
                 .For<IWindsorContainer>()
                 .Instance(container)
                 .LifestyleSingleton())
         .Register(
             Component
                 .For<IDispatcher>()
                 .ImplementedBy<Dispatcher>()
                 .LifestyleTransient())
         .Register(
             AllTypes
                 .FromAssemblyNamed("DotNetAcademy.NhibernateArch.Domain")
                 .BasedOn<IHandler>()
                 .WithService
                 .AllInterfaces()
                 .LifestyleTransient())
         .Register(
             Component
                 .For<IPostService>()
                 .ImplementedBy<PostService>()
                 .LifestyleTransient())
         .Register(
             Component
                 .For<ISessionFactory>()
                 .UsingFactoryMethod(fm =>
                 {
                     var configuration = new NHibernate.Cfg.Configuration().Configure();
                     var sessionFactory = configuration.BuildSessionFactory();
                     return sessionFactory;
                 })
                 .LifestyleSingleton())
         .Register(
             Component
                 .For<ISession>()
                 .UsingFactoryMethod(fm => fm.Resolve<ISessionFactory>().OpenSession())
                 .LifestylePerWebRequest())
         .Register(
             AllTypes
                 .FromThisAssembly()
                 .BasedOn<IController>()
                 .LifestyleTransient())
         .Register(
             Component
                 .For<IActionInvoker>()
                 .ImplementedBy<WindsorActionInvoker>()
                 .LifestyleTransient())
         ;
 }
Ejemplo n.º 55
0
        public DbContext(string connectionString, DbOption dbOption)
        {
            if (_sessionFactory == null)
            {
                _configuration = ConfigurationBuilder.New()
                    .ForSql2008(connectionString)
                    .MapEntities(GetEntityTypes());

                CreateOrUpdateDatabaseAndSchema(connectionString, dbOption);

                _sessionFactory = _configuration.BuildSessionFactory();
            }
            Session = _sessionFactory.OpenSession();
        }
Ejemplo n.º 56
0
        private static ISessionFactory CreateSessionFactory()
        {
            var mapper = new ModelMapper();
            mapper.AddMappings(Assembly.Load("MessageBoard.Domain").GetTypes());
            HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

            config = new NHibernate.Cfg.Configuration();
            config.Configure();
               config.AddDeserializedMapping(domainMapping,"domainMapping");

             config.Properties[NHibernate.Cfg.Environment.CurrentSessionContextClass]="web";
             config.SetProperty(NHibernate.Cfg.Environment.ShowSql, "true").SetProperty(NHibernate.Cfg.Environment.BatchSize, "100");
            return config.BuildSessionFactory();
        }
Ejemplo n.º 57
0
        private static void BuildSessionFactory()
        {
            try
            {
                _configuration = new Configuration();
                _configuration.Configure();

                _sessionFactory = _configuration.BuildSessionFactory();
            }
            catch(Exception ex)
            {
                log4net.LogManager.GetLogger(typeof(NHibernateHelper)).Error(ex);
                throw;
            }
        }
Ejemplo n.º 58
0
        /// <summary>
        /// Static constructor
        /// Inintializes default settings
        /// </summary>
        static Settings()
        {
            _connectionString = "";
            _isDebug = false;

            Configuration cfg = new Configuration();
            IDictionary section = ConfigurationManager.GetSection(NhibernateSectionName) as IDictionary;
            if (section == null)
            {
                throw new NHibernateSectionLoadException();
            }
            cfg.AddProperties(section);
            cfg.AddAssembly(typeof(Settings).Assembly);

            _sessionFactory = cfg.BuildSessionFactory();
        }
Ejemplo n.º 59
0
        public static void configSession()
        {
            //gets the connection string data associated with this db
            string dsn = ConfigurationManager.ConnectionStrings[connectionString].ConnectionString;
            config = new NHibernate.Cfg.Configuration();

            config.SetProperty(NHibernate.Cfg.Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider");
            config.SetProperty(NHibernate.Cfg.Environment.Dialect, "NHibernate.Dialect.MsSqlCeDialect");
            config.SetProperty(NHibernate.Cfg.Environment.ConnectionDriver, "NHibernate.Driver.SqlClientDriver");
            config.SetProperty("hibernate.show_sql", "true");
            config.SetProperty(NHibernate.Cfg.Environment.ConnectionString, dsn);

            ///important to add assembly, which is the name of the app or project usually;
            config.AddAssembly("OnBudgetApp");
            SessionFactory = config.BuildSessionFactory();
        }
        /// <summary>
        /// Creates NHibernate Session Factory.
        /// </summary>
        /// <returns>NHibernate Session Factory</returns>
        private static ISessionFactory CreateNhSessionFactory(IKernel kernel, CreationContext context)
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure();            
            cfg.AddAssembly("Konekti.Model");

            // update schema or create one if not exist
            new SchemaUpdate(cfg).Execute(false, true);

            return cfg.BuildSessionFactory();

            /*string connStr = ConfigurationManager.ConnectionStrings["Konekti"].ConnectionString;

            return Fluently.Configure()
                .Database(MySQLConfiguration.Standard.ConnectionString(connStr))
                .Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetAssembly(typeof(MenuGroup))))
                .BuildSessionFactory();*/
        }