public global::NHibernate.Cfg.Configuration GetCfg(string[] addAssemblies)
        {
            SessionFactoryImpl sessionFactoryImpl = SpringHelper.ApplicationContext["NHibernateSessionFactory"] as SessionFactoryImpl;
            IDictionary springObjectDic = getSpringObjectPropertyValue("NHibernateSessionFactory", "HibernateProperties") as IDictionary;
            IDictionary<string, string> dic = new Dictionary<string, string>();
            foreach (DictionaryEntry de in springObjectDic)
            {
                dic.Add(de.Key.ToString(), de.Value.ToString());
                //if (de.Key.ToString().Equals("hibernate.dialect"))
                //{
                //    dialectName = de.Value.ToString();
                //}
            }

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

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

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

            return cfg;
        }
示例#2
0
 protected override void Load(ContainerBuilder builder)
 {
     var cfg = new Configuration().Configure();
     cfg.AddProperties(new Dictionary<string, string>
                           {
                               {"current_session_context_class", "NHibernate.Context.WebSessionContext"}
                           });
     ISessionFactory sessionFactory = cfg.BuildSessionFactory();
     builder.RegisterInstance(sessionFactory);
     builder.RegisterType<NHibernateAmbientSessionManager>().AsSelf();
 }
示例#3
0
 internal static void InitHibernate(string ConnectionString)
 {
     Console.WriteLine("Configuring Hibernate...");
     Configuration configuration = new Configuration();
     configuration.Configure();//預設抓目錄下的hibernate.cfg.xml
     configuration.AddAssembly(Assembly.GetCallingAssembly());
     configuration.AddProperties(new Dictionary<string, string>
                           {
                              {"connection.connection_string", ConnectionString}
                           });
     SessionFactory = configuration.BuildSessionFactory();
     Console.WriteLine("Created SessionFactory!");
 }
        public MySessionSource(IDictionary<string, string> properties, PersistenceModel model)
        {
            if(model == null) throw new ArgumentException("Model cannot be null!");

            _configuration = new Configuration();
            if (properties == null)
                _configuration.Configure();
            else
                _configuration.AddProperties(properties);

            Model = model;
            model.Configure(_configuration);

            _sessionFactory = _configuration.BuildSessionFactory();
        }
        public ISessionFactory BuildSessionFactory()
        {
            FileHelper.DeletePreviousDbFiles();
            var dbFile = FileHelper.GetDbFileName();
            var configuration = new Configuration();

            configuration.AddProperties(new Dictionary<string, string>
                                                {
                                                    { Environment.ConnectionString, string.Format("Data Source={0};Version=3;New=True;", dbFile) }
                                                });

            configuration.Configure();
            var schemaExport = new SchemaExport(configuration);
            schemaExport.Create(true, true);
            return configuration.BuildSessionFactory();
        }
示例#6
0
        public void FixtureSetup()
        {
            BasicConfigurator.Configure();
            var cfg = new Configuration();
            cfg.AddProperties(new Dictionary<string, string> {
                {Environment.ConnectionProvider, typeof(DriverConnectionProvider).FullName},
                {Environment.Dialect, typeof(SQLiteDialect).FullName},
                {Environment.ConnectionDriver, typeof(SQLite20Driver).FullName},
                {Environment.ConnectionString, "Data Source=test.db;Version=3;New=True;"},
                //{"connection.release_mode", "on_close"},
            });

            cfg.AddClass(typeof (Simple));
            new SchemaExport(cfg).Create(true, true);
            sessionFactory = cfg.BuildSessionFactory();
        }
    public void Open()
    {
      _database = new DatabaseManager();
      _database.Recreate();

      IDictionary<string, string> properties = SqlHelper.Provider.CreateNhibernateProperties();
      properties["connection.provider"] = "NHibernate.Connection.DriverConnectionProvider";
      properties["connection.connection_string"] = _database.Connection.ConnectionString;
      properties["connection.release_mode"] = "on_close";
      properties["proxyfactory.factory_class"] = "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle";

      Configuration configuration = new Configuration();
      configuration.AddProperties(properties);
      HbmSerializer.Default.Validate = true;
      MemoryStream stream = HbmSerializer.Default.Serialize(typeof(NorthwindEmployee).Assembly);
      stream.Position = 0;
      configuration.AddInputStream(stream);
      stream.Close();

      _sessionFactory = configuration.BuildSessionFactory();
    }
示例#8
0
        /// <summary>
        /// Initialize the SessionFactory for the given or the
        /// default location.
        /// </summary>
        public virtual void AfterPropertiesSet()
        {
            // Create Configuration instance.
            Configuration config = NewConfiguration();

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

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

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

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



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

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

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

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

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

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

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

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

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

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

            AfterSessionFactoryCreation();

            // set config time DB provider back to null
            configTimeDbProvider = null;
        }
示例#9
0
 private static void InitializeNHibernateForBus(IUnityContainer container)
 {
    Configuration cfg = new Configuration().Configure();
    cfg.AddProperties(new Dictionary<string, string>
                         {
                            {"current_session_context_class", "NHibernate.Context.ThreadStaticSessionContext"}
                         });
    ISessionFactory factory = cfg.BuildSessionFactory();
    container.RegisterInstance(factory);
 }
示例#10
0
        /// <summary>
        /// Initialize the SessionFactory for the given or the
        /// default location.
        /// </summary>
        public virtual void AfterPropertiesSet()
        {
            // Create Configuration instance.
            Configuration config = NewConfiguration();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            AfterSessionFactoryCreation();

            // set config time DB provider back to null
            configTimeDbProvider = null;
        }
示例#11
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        protected override void ExecuteTask()
        {
            Configuration config = new Configuration();
            Dictionary<string, string> properties = new Dictionary<string, string>();

            properties[NHibernate.Cfg.Environment.ConnectionProvider] = ConnectionProvider;
            properties[NHibernate.Cfg.Environment.Dialect] = Dialect;
            properties[NHibernate.Cfg.Environment.ConnectionDriver] = ConnectionDriverClass;
            properties[NHibernate.Cfg.Environment.ConnectionString] = ConnectionString;

            config.AddProperties(properties);

            foreach (string filename in Assemblies.FileNames)
            {
                Log(Level.Info, "Adding assembly file {0}", filename);
                try
                {
                    Assembly asm = Assembly.LoadFile(filename);
                    config.AddAssembly(asm);
                }
                catch (Exception e)
                {
                    Log(Level.Error, "Error loading assembly {0}: {1}", filename, e);
                }
            }

            SchemaExport se = new SchemaExport(config);
            if (!IsStringNullOrEmpty(OutputFilename))
            {
                se.SetOutputFile(OutputFilename);
            }
            se.SetDelimiter(Delimiter);
            Log(Level.Debug, "Exporting ddl schema.");
            se.Execute(OutputToConsole, ExportOnly, DropOnly, FormatNice);

            if (!IsStringNullOrEmpty(OutputFilename))
            {
                Log(Level.Info, "Successful DDL schema output: {0}", OutputFilename);
            }
        }
        private static Configuration ConfigureNHibernate(string cfgFile, IDictionary<string, string> cfgProperties)
        {
            Configuration cfg = new Configuration();

            if (cfgProperties != null)
                cfg.AddProperties(cfgProperties);

            if (string.IsNullOrEmpty(cfgFile) == false)
                return cfg.Configure(cfgFile);

            if (File.Exists("Hibernate.cfg.xml"))
                return cfg.Configure();

            return cfg;
        }
示例#13
0
 public void RealEntities_Test()
 {
     var cfg = new Configuration();
     cfg.AddProperties(new Dictionary<string, string> {
         {Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider"},
         {Environment.Dialect, "NHibernate.Dialect.SQLiteDialect"},
         {Environment.ConnectionDriver, "NHibernate.Driver.SQLite20Driver"},
         {Environment.ConnectionString, "Data Source=test.db;Version=3;New=True;"},
     });
     cfg.AddXml(one_xml);
     cfg.AddXml(two_xml);
     cfg.AddXml(three_xml);
     new SchemaExport(cfg).Create(true, true);
     using (var factory = cfg.BuildSessionFactory()) {
         using (var session = factory.OpenSession()) {
             var three = new Three();
             session.Save(three);
             var two = new Two { Three = three };
             session.Save(two);
             session.Save(new One { Two = two });
             session.Flush();
         }
         using (var session = factory.OpenSession()) {
             var one = session.CreateCriteria(typeof (One)).List<One>()[0];
             Assert.IsFalse(NHibernateUtilEx.IsInitialized(() => one.Two));
             Assert.IsFalse(NHibernateUtilEx.IsInitialized(() => one.Two.Three));
             var t = one.Two.Three;
             Assert.IsTrue(NHibernateUtilEx.IsInitialized(() => one.Two));
             Assert.IsFalse(NHibernateUtilEx.IsInitialized(() => one.Two.Three));
         }
     }
 }
示例#14
0
      private void InitializeNHibernate()
      {         
         var cfg = new Configuration();
            cfg.AddProperties(new Dictionary<string, string>
                              {
                                 {Environment.ConnectionDriver, typeof (SQLite20Driver).FullName},
                                 {Environment.Dialect, typeof (SQLiteDialect).FullName},
                                 {Environment.ConnectionProvider, typeof (DriverConnectionProvider).FullName},
                                 {Environment.ConnectionString, "Data Source=:memory:;Version=3;New=True;"},
                                 {
                                    Environment.ProxyFactoryFactoryClass,
                                    typeof (ProxyFactoryFactory).AssemblyQualifiedName
                                    },
                                 {
                                    Environment.CurrentSessionContextClass,
                                    typeof (ThreadStaticSessionContext).AssemblyQualifiedName
                                    },
                                 {Environment.ReleaseConnections,"on_close"},
                                 {Environment.Hbm2ddlAuto, "create"},
                                 {Environment.ShowSql, true.ToString()}
                              });
         cfg.AddAssembly("DDDSample.DomainModel.Persistence");

         _sessionFactory = cfg.BuildSessionFactory();
         _ambientContainer.RegisterInstance(_sessionFactory);         

         ISession session = _sessionFactory.OpenSession();

         new SchemaExport(cfg).Execute(false, true, false, session.Connection, Console.Out);

         SampleLocations.CreateLocations(session);
         SampleTransportLegs.CreateTransportLegs(session);
         SampleVoyages.CreateVoyages(session);
         SampleCustomers.CreateCustomers(session);
         session.Flush();

         _currentSession = session;

         CurrentSessionContext.Bind(_currentSession);
      }
示例#15
0
    private Configuration GetCfg()
    {
        SessionFactoryImpl s = (SessionFactoryImpl)ctx.GetObject("NHibernateSessionFactory");

        IResource resource = ctx.GetResource("file://~/App_Data/Dao.xml");
        IDictionary<string, string> dic = new Dictionary<string, string>();

        XmlDocument xdoc = new XmlDocument();
        xdoc.Load(resource.InputStream);

        XmlElement root = xdoc.DocumentElement;

        XmlNodeList nodeList = root.GetElementsByTagName("object");

        foreach (XmlNode node in nodeList)
        {
            if (node.Attributes["id"] != null && "NHibernateSessionFactory".Equals(node.Attributes["id"].Value))
            {
                XmlNodeList nodeList2 = node.ChildNodes[3].FirstChild.ChildNodes;

                foreach (XmlNode node2 in nodeList2)
                {
                    string key = node2.Attributes["key"].Value;
                    string value = node2.Attributes["value"].Value;
                    // log.Debug(key + ":" + value);
                    dic.Add(key, value);
                }
            }
        }

        XmlNode dbNode = root.GetElementsByTagName("db:provider")[0];
        string connectionStr = dbNode.Attributes["connectionString"].Value;

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

        foreach (string assem in ASSEMBLES)
        {
            cfg.AddAssembly(assem);
        }

        return cfg;
    }