Esempio n. 1
0
        public Settings BuildSettings(IDictionary <string, string> properties)
        {
            Settings settings = new Settings();

            Dialect.Dialect dialect;
            try
            {
                dialect = Dialect.Dialect.GetDialect(properties);
                Dictionary <string, string> temp = new Dictionary <string, string>();

                foreach (KeyValuePair <string, string> de in dialect.DefaultProperties)
                {
                    temp[de.Key] = de.Value;
                }
                foreach (KeyValuePair <string, string> de in properties)
                {
                    temp[de.Key] = de.Value;
                }
                properties = temp;
            }
            catch (HibernateException he)
            {
                log.Warn("No dialect set - using GenericDialect: " + he.Message);
                dialect = new GenericDialect();
            }
            settings.Dialect = dialect;

            settings.LinqToHqlGeneratorsRegistry = LinqToHqlGeneratorsRegistryFactory.CreateGeneratorsRegistry(properties);

            #region SQL Exception converter

            ISQLExceptionConverter sqlExceptionConverter;
            try
            {
                sqlExceptionConverter = SQLExceptionConverterFactory.BuildSQLExceptionConverter(dialect, properties);
            }
            catch (HibernateException)
            {
                log.Warn("Error building SQLExceptionConverter; using minimal converter");
                sqlExceptionConverter = SQLExceptionConverterFactory.BuildMinimalSQLExceptionConverter();
            }
            settings.SqlExceptionConverter = sqlExceptionConverter;

            #endregion

            bool comments = PropertiesHelper.GetBoolean(Environment.UseSqlComments, properties);
            log.Info("Generate SQL with comments: " + EnabledDisabled(comments));
            settings.IsCommentsEnabled = comments;

            int maxFetchDepth = PropertiesHelper.GetInt32(Environment.MaxFetchDepth, properties, -1);
            if (maxFetchDepth != -1)
            {
                log.Info("Maximum outer join fetch depth: " + maxFetchDepth);
            }

            IConnectionProvider connectionProvider = ConnectionProviderFactory.NewConnectionProvider(properties);
            ITransactionFactory transactionFactory = CreateTransactionFactory(properties);
            // TransactionManagerLookup transactionManagerLookup = TransactionManagerLookupFactory.GetTransactionManagerLookup( properties );

            // Not ported: useGetGeneratedKeys, useScrollableResultSets

            bool useMinimalPuts = PropertiesHelper.GetBoolean(Environment.UseMinimalPuts, properties, false);
            log.Info("Optimize cache for minimal puts: " + useMinimalPuts);

            string releaseModeName = PropertiesHelper.GetString(Environment.ReleaseConnections, properties, "auto");
            log.Info("Connection release mode: " + releaseModeName);
            ConnectionReleaseMode releaseMode;
            if ("auto".Equals(releaseModeName))
            {
                releaseMode = ConnectionReleaseMode.AfterTransaction;                 //transactionFactory.DefaultReleaseMode;
            }
            else
            {
                releaseMode = ConnectionReleaseModeParser.Convert(releaseModeName);
            }
            settings.ConnectionReleaseMode = releaseMode;

            string defaultSchema  = PropertiesHelper.GetString(Environment.DefaultSchema, properties, null);
            string defaultCatalog = PropertiesHelper.GetString(Environment.DefaultCatalog, properties, null);
            if (defaultSchema != null)
            {
                log.Info("Default schema: " + defaultSchema);
            }
            if (defaultCatalog != null)
            {
                log.Info("Default catalog: " + defaultCatalog);
            }
            settings.DefaultSchemaName  = defaultSchema;
            settings.DefaultCatalogName = defaultCatalog;

            int batchFetchSize = PropertiesHelper.GetInt32(Environment.DefaultBatchFetchSize, properties, 1);
            log.Info("Default batch fetch size: " + batchFetchSize);
            settings.DefaultBatchFetchSize = batchFetchSize;

            //Statistics and logging:

            bool showSql = PropertiesHelper.GetBoolean(Environment.ShowSql, properties, false);
            if (showSql)
            {
                log.Info("echoing all SQL to stdout");
            }
            bool formatSql = PropertiesHelper.GetBoolean(Environment.FormatSql, properties);

            bool useStatistics = PropertiesHelper.GetBoolean(Environment.GenerateStatistics, properties);
            log.Info("Statistics: " + EnabledDisabled(useStatistics));
            settings.IsStatisticsEnabled = useStatistics;

            bool useIdentifierRollback = PropertiesHelper.GetBoolean(Environment.UseIdentifierRollBack, properties);
            log.Info("Deleted entity synthetic identifier rollback: " + EnabledDisabled(useIdentifierRollback));
            settings.IsIdentifierRollbackEnabled = useIdentifierRollback;

            // queries:

            settings.QueryTranslatorFactory = CreateQueryTranslatorFactory(properties);

            settings.LinqQueryProviderType = CreateLinqQueryProviderType(properties);

            IDictionary <string, string> querySubstitutions = PropertiesHelper.ToDictionary(Environment.QuerySubstitutions,
                                                                                            " ,=;:\n\t\r\f", properties);
            if (log.IsInfoEnabled)
            {
                log.Info("Query language substitutions: " + CollectionPrinter.ToString((IDictionary)querySubstitutions));
            }

            #region Hbm2DDL
            string autoSchemaExport = PropertiesHelper.GetString(Environment.Hbm2ddlAuto, properties, null);
            if (SchemaAutoAction.Update == autoSchemaExport)
            {
                settings.IsAutoUpdateSchema = true;
            }
            else if (SchemaAutoAction.Create == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
            }
            else if (SchemaAutoAction.Recreate == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
                settings.IsAutoDropSchema   = true;
            }
            else if (SchemaAutoAction.Validate == autoSchemaExport)
            {
                settings.IsAutoValidateSchema = true;
            }

            string autoKeyWordsImport = PropertiesHelper.GetString(Environment.Hbm2ddlKeyWords, properties, "not-defined");
            autoKeyWordsImport = autoKeyWordsImport.ToLowerInvariant();
            if (autoKeyWordsImport == Hbm2DDLKeyWords.None)
            {
                settings.IsKeywordsImportEnabled = false;
                settings.IsAutoQuoteEnabled      = false;
            }
            else if (autoKeyWordsImport == Hbm2DDLKeyWords.Keywords)
            {
                settings.IsKeywordsImportEnabled = true;
            }
            else if (autoKeyWordsImport == Hbm2DDLKeyWords.AutoQuote)
            {
                settings.IsKeywordsImportEnabled = true;
                settings.IsAutoQuoteEnabled      = true;
            }
            else if (autoKeyWordsImport == "not-defined")
            {
                settings.IsKeywordsImportEnabled = true;
                settings.IsAutoQuoteEnabled      = false;
            }

            #endregion

            bool useSecondLevelCache = PropertiesHelper.GetBoolean(Environment.UseSecondLevelCache, properties, true);
            bool useQueryCache       = PropertiesHelper.GetBoolean(Environment.UseQueryCache, properties);

            if (useSecondLevelCache || useQueryCache)
            {
                // The cache provider is needed when we either have second-level cache enabled
                // or query cache enabled.  Note that useSecondLevelCache is enabled by default
                settings.CacheProvider = CreateCacheProvider(properties);
            }
            else
            {
                settings.CacheProvider = new NoCacheProvider();
            }

            string cacheRegionPrefix = PropertiesHelper.GetString(Environment.CacheRegionPrefix, properties, null);
            if (string.IsNullOrEmpty(cacheRegionPrefix))
            {
                cacheRegionPrefix = null;
            }
            if (cacheRegionPrefix != null)
            {
                log.Info("Cache region prefix: " + cacheRegionPrefix);
            }


            if (useQueryCache)
            {
                string queryCacheFactoryClassName = PropertiesHelper.GetString(Environment.QueryCacheFactory, properties,
                                                                               typeof(StandardQueryCacheFactory).FullName);
                log.Info("query cache factory: " + queryCacheFactoryClassName);
                try
                {
                    settings.QueryCacheFactory =
                        (IQueryCacheFactory)
                        Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(queryCacheFactoryClassName));
                }
                catch (Exception cnfe)
                {
                    throw new HibernateException("could not instantiate IQueryCacheFactory: " + queryCacheFactoryClassName, cnfe);
                }
            }

            string sessionFactoryName = PropertiesHelper.GetString(Environment.SessionFactoryName, properties, null);

            //ADO.NET and connection settings:

            settings.AdoBatchSize = PropertiesHelper.GetInt32(Environment.BatchSize, properties, 0);
            bool orderInserts = PropertiesHelper.GetBoolean(Environment.OrderInserts, properties, (settings.AdoBatchSize > 0));
            log.Info("Order SQL inserts for batching: " + EnabledDisabled(orderInserts));
            settings.IsOrderInsertsEnabled = orderInserts;

            bool orderUpdates = PropertiesHelper.GetBoolean(Environment.OrderUpdates, properties, false);
            log.Info("Order SQL updates for batching: " + EnabledDisabled(orderUpdates));
            settings.IsOrderUpdatesEnabled = orderUpdates;

            bool wrapResultSets = PropertiesHelper.GetBoolean(Environment.WrapResultSets, properties, false);
            log.Debug("Wrap result sets: " + EnabledDisabled(wrapResultSets));
            settings.IsWrapResultSetsEnabled = wrapResultSets;

            bool batchVersionedData = PropertiesHelper.GetBoolean(Environment.BatchVersionedData, properties, false);
            log.Debug("Batch versioned data: " + EnabledDisabled(batchVersionedData));
            settings.IsBatchVersionedDataEnabled = batchVersionedData;

            settings.BatcherFactory = CreateBatcherFactory(properties, settings.AdoBatchSize, connectionProvider);

            string         isolationString = PropertiesHelper.GetString(Environment.Isolation, properties, String.Empty);
            IsolationLevel isolation       = IsolationLevel.Unspecified;
            if (isolationString.Length > 0)
            {
                try
                {
                    isolation = (IsolationLevel)Enum.Parse(typeof(IsolationLevel), isolationString);
                    log.Info("Using Isolation Level: " + isolation);
                }
                catch (ArgumentException ae)
                {
                    log.Error("error configuring IsolationLevel " + isolationString, ae);
                    throw new HibernateException(
                              "The isolation level of " + isolationString + " is not a valid IsolationLevel.  Please "
                              + "use one of the Member Names from the IsolationLevel.", ae);
                }
            }

            //NH-3619
            FlushMode defaultFlushMode = (FlushMode)Enum.Parse(typeof(FlushMode), PropertiesHelper.GetString(Environment.DefaultFlushMode, properties, FlushMode.Auto.ToString()), false);
            log.Info("Default flush mode: " + defaultFlushMode);
            settings.DefaultFlushMode = defaultFlushMode;

#pragma warning disable CS0618 // Type or member is obsolete
            var defaultEntityMode = PropertiesHelper.GetString(Environment.DefaultEntityMode, properties, null);
            if (!string.IsNullOrEmpty(defaultEntityMode))
            {
                log.Warn("Default entity-mode setting is deprecated.");
            }
#pragma warning restore CS0618 // Type or member is obsolete

            bool namedQueryChecking = PropertiesHelper.GetBoolean(Environment.QueryStartupChecking, properties, true);
            log.Info("Named query checking : " + EnabledDisabled(namedQueryChecking));
            settings.IsNamedQueryStartupCheckingEnabled = namedQueryChecking;

            // Not ported - settings.StatementFetchSize = statementFetchSize;
            // Not ported - ScrollableResultSetsEnabled
            // Not ported - GetGeneratedKeysEnabled
            settings.SqlStatementLogger = new SqlStatementLogger(showSql, formatSql);

            settings.ConnectionProvider = connectionProvider;
            settings.QuerySubstitutions = querySubstitutions;
            settings.TransactionFactory = transactionFactory;
            // Not ported - TransactionManagerLookup
            settings.SessionFactoryName        = sessionFactoryName;
            settings.MaximumFetchDepth         = maxFetchDepth;
            settings.IsQueryCacheEnabled       = useQueryCache;
            settings.IsSecondLevelCacheEnabled = useSecondLevelCache;
            settings.CacheRegionPrefix         = cacheRegionPrefix;
            settings.IsMinimalPutsEnabled      = useMinimalPuts;
            // Not ported - JdbcBatchVersionedData

            settings.QueryModelRewriterFactory = CreateQueryModelRewriterFactory(properties);

            // NHibernate-specific:
            settings.IsolationLevel = isolation;

            return(settings);
        }
Esempio n. 2
0
        public void CompleteConfiguration()
        {
            // Here I'm configuring near all properties outside the scope of Configuration class
            // Using the Configuration class the user can add mappings and configure listeners
            var cfg = new Configuration();

            cfg.SessionFactory().Named("SomeName")
            .Caching
            .Through <HashtableCacheProvider>()
            .PrefixingRegionsWith("xyz")
            .Queries
            .Through <StandardQueryCache>()
            .UsingMinimalPuts()
            .WithDefaultExpiration(15)
            .GeneratingCollections
            .Through <DefaultCollectionTypeFactory>()
            .Proxy
            .DisableValidation()
            .Through <ProxyFactoryFactory>()
            .ParsingHqlThrough <ClassicQueryTranslatorFactory>()
            .Mapping
            .UsingDefaultCatalog("MyCatalog")
            .UsingDefaultSchema("MySche")
            .Integrate
            .Using <MsSql2000Dialect>()
            .AutoQuoteKeywords()
            .BatchingQueries
            .Through <SqlClientBatchingBatcherFactory>()
            .Each(15)
            .Connected
            .Through <DebugConnectionProvider>()
            .By <SqlClientDriver>()
            .Releasing(ConnectionReleaseMode.AfterTransaction)
            .With(IsolationLevel.ReadCommitted)
            .Using("The connection string")
            .CreateCommands
            .AutoCommentingSql()
            .ConvertingExceptionsThrough <SQLStateConverter>()
            .Preparing()
            .WithTimeout(10)
            .WithMaximumDepthOfOuterJoinFetching(11)
            .WithHqlToSqlSubstitutions("true 1, false 0, yes 'Y', no 'N'")
            .Schema
            .Validating()
            ;

            Assert.That(cfg.Properties[Environment.SessionFactoryName], Is.EqualTo("SomeName"));
            Assert.That(cfg.Properties[Environment.CacheProvider],
                        Is.EqualTo(typeof(HashtableCacheProvider).AssemblyQualifiedName));
            Assert.That(cfg.Properties[Environment.CacheRegionPrefix], Is.EqualTo("xyz"));
            Assert.That(cfg.Properties[Environment.QueryCacheFactory],
                        Is.EqualTo(typeof(StandardQueryCache).AssemblyQualifiedName));
            Assert.That(cfg.Properties[Environment.UseMinimalPuts], Is.EqualTo("true"));
            Assert.That(cfg.Properties[Environment.CacheDefaultExpiration], Is.EqualTo("15"));
            Assert.That(cfg.Properties[Environment.CollectionTypeFactoryClass],
                        Is.EqualTo(typeof(DefaultCollectionTypeFactory).AssemblyQualifiedName));
            Assert.That(cfg.Properties[Environment.UseProxyValidator], Is.EqualTo("false"));
            Assert.That(cfg.Properties[Environment.ProxyFactoryFactoryClass],
                        Is.EqualTo(typeof(ProxyFactoryFactory).AssemblyQualifiedName));
            Assert.That(cfg.Properties[Environment.QueryTranslator],
                        Is.EqualTo(typeof(ClassicQueryTranslatorFactory).AssemblyQualifiedName));
            Assert.That(cfg.Properties[Environment.DefaultCatalog], Is.EqualTo("MyCatalog"));
            Assert.That(cfg.Properties[Environment.DefaultSchema], Is.EqualTo("MySche"));
            Assert.That(cfg.Properties[Environment.Dialect],
                        Is.EqualTo(typeof(MsSql2000Dialect).AssemblyQualifiedName));
            Assert.That(cfg.Properties[Environment.Hbm2ddlKeyWords], Is.EqualTo("auto-quote"));
            Assert.That(cfg.Properties[Environment.BatchStrategy],
                        Is.EqualTo(typeof(SqlClientBatchingBatcherFactory).AssemblyQualifiedName));
            Assert.That(cfg.Properties[Environment.BatchSize], Is.EqualTo("15"));
            Assert.That(cfg.Properties[Environment.ConnectionProvider],
                        Is.EqualTo(typeof(DebugConnectionProvider).AssemblyQualifiedName));
            Assert.That(cfg.Properties[Environment.ConnectionDriver],
                        Is.EqualTo(typeof(SqlClientDriver).AssemblyQualifiedName));
            Assert.That(cfg.Properties[Environment.ReleaseConnections],
                        Is.EqualTo(ConnectionReleaseModeParser.ToString(ConnectionReleaseMode.AfterTransaction)));
            Assert.That(cfg.Properties[Environment.Isolation], Is.EqualTo("ReadCommitted"));
            Assert.That(cfg.Properties[Environment.ConnectionString], Is.EqualTo("The connection string"));
            Assert.That(cfg.Properties[Environment.UseSqlComments], Is.EqualTo("true"));
            Assert.That(cfg.Properties[Environment.SqlExceptionConverter],
                        Is.EqualTo(typeof(SQLStateConverter).AssemblyQualifiedName));
            Assert.That(cfg.Properties[Environment.PrepareSql], Is.EqualTo("true"));
            Assert.That(cfg.Properties[Environment.CommandTimeout], Is.EqualTo("10"));
            Assert.That(cfg.Properties[Environment.MaxFetchDepth], Is.EqualTo("11"));
            Assert.That(cfg.Properties[Environment.QuerySubstitutions], Is.EqualTo("true 1, false 0, yes 'Y', no 'N'"));
            Assert.That(cfg.Properties[Environment.Hbm2ddlAuto], Is.EqualTo("validate"));
        }
 public IConnectionConfiguration Releasing(ConnectionReleaseMode releaseMode)
 {
     dbc.Configuration.SetProperty(Environment.ReleaseConnections, ConnectionReleaseModeParser.ToString(releaseMode));
     return(this);
 }
        public void FullConfiguration()
        {
            var configure = new Configuration();

            configure.SessionFactoryName("SomeName");
            configure.Cache(c =>
            {
                c.UseMinimalPuts    = true;
                c.DefaultExpiration = 15;
                c.RegionsPrefix     = "xyz";
                c.Provider <HashtableCacheProvider>();
                c.QueryCache <StandardQueryCache>();
            });
            configure.CollectionTypeFactory <DefaultCollectionTypeFactory>();
            configure.HqlQueryTranslator <ASTQueryTranslatorFactory>();
            configure.LinqToHqlGeneratorsRegistry <DefaultLinqToHqlGeneratorsRegistry>();
            configure.Proxy(p =>
            {
                p.Validation = false;
                p.ProxyFactoryFactory <DefaultProxyFactoryFactory>();
            });
            configure.Mappings(m =>
            {
                m.DefaultCatalog = "MyCatalog";
                m.DefaultSchema  = "MySche";
            });
            configure.DataBaseIntegration(db =>
            {
                db.Dialect <MsSql2000Dialect>();
                db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
                db.Batcher <SqlClientBatchingBatcherFactory>();
                db.BatchSize = 15;
                db.ConnectionProvider <DebugConnectionProvider>();
                db.Driver <SqlClientDriver>();
                db.ConnectionReleaseMode = ConnectionReleaseMode.AfterTransaction;
                db.IsolationLevel        = IsolationLevel.ReadCommitted;
                db.ConnectionString      = "The connection string";
                db.AutoCommentSql        = true;
                db.ExceptionConverter <SQLStateConverter>();
                db.PrepareCommands = true;
                db.Timeout         = 10;
                db.MaximumDepthOfOuterJoinFetching = 11;
                db.HqlToSqlSubstitutions           = "true 1, false 0, yes 'Y', no 'N'";
                db.SchemaAction = SchemaAutoAction.Validate;
            });

            Assert.That(configure.Properties[Environment.SessionFactoryName], Is.EqualTo("SomeName"));
            Assert.That(configure.Properties[Environment.CacheProvider],
                        Is.EqualTo(typeof(HashtableCacheProvider).AssemblyQualifiedName));
            Assert.That(configure.Properties[Environment.CacheRegionPrefix], Is.EqualTo("xyz"));
            Assert.That(configure.Properties[Environment.QueryCacheFactory],
                        Is.EqualTo(typeof(StandardQueryCache).AssemblyQualifiedName));
            Assert.That(configure.Properties[Environment.UseMinimalPuts], Is.EqualTo("true"));
            Assert.That(configure.Properties[Environment.CacheDefaultExpiration], Is.EqualTo("15"));
            Assert.That(configure.Properties[Environment.CollectionTypeFactoryClass],
                        Is.EqualTo(typeof(DefaultCollectionTypeFactory).AssemblyQualifiedName));
            Assert.That(configure.Properties[Environment.UseProxyValidator], Is.EqualTo("false"));
            Assert.That(configure.Properties[Environment.ProxyFactoryFactoryClass],
                        Is.EqualTo(typeof(DefaultProxyFactoryFactory).AssemblyQualifiedName));
            Assert.That(configure.Properties[Environment.QueryTranslator],
                        Is.EqualTo(typeof(ASTQueryTranslatorFactory).AssemblyQualifiedName));
            Assert.That(configure.Properties[Environment.DefaultCatalog], Is.EqualTo("MyCatalog"));
            Assert.That(configure.Properties[Environment.DefaultSchema], Is.EqualTo("MySche"));
            Assert.That(configure.Properties[Environment.Dialect],
                        Is.EqualTo(typeof(MsSql2000Dialect).AssemblyQualifiedName));
            Assert.That(configure.Properties[Environment.Hbm2ddlKeyWords], Is.EqualTo("auto-quote"));
            Assert.That(configure.Properties[Environment.BatchStrategy],
                        Is.EqualTo(typeof(SqlClientBatchingBatcherFactory).AssemblyQualifiedName));
            Assert.That(configure.Properties[Environment.BatchSize], Is.EqualTo("15"));
            Assert.That(configure.Properties[Environment.ConnectionProvider],
                        Is.EqualTo(typeof(DebugConnectionProvider).AssemblyQualifiedName));
            Assert.That(configure.Properties[Environment.ConnectionDriver],
                        Is.EqualTo(typeof(SqlClientDriver).AssemblyQualifiedName));
            Assert.That(configure.Properties[Environment.ReleaseConnections],
                        Is.EqualTo(ConnectionReleaseModeParser.ToString(ConnectionReleaseMode.AfterTransaction)));
            Assert.That(configure.Properties[Environment.Isolation], Is.EqualTo("ReadCommitted"));
            Assert.That(configure.Properties[Environment.ConnectionString], Is.EqualTo("The connection string"));
            Assert.That(configure.Properties[Environment.UseSqlComments], Is.EqualTo("true"));
            Assert.That(configure.Properties[Environment.SqlExceptionConverter],
                        Is.EqualTo(typeof(SQLStateConverter).AssemblyQualifiedName));
            Assert.That(configure.Properties[Environment.PrepareSql], Is.EqualTo("true"));
            Assert.That(configure.Properties[Environment.CommandTimeout], Is.EqualTo("10"));
            Assert.That(configure.Properties[Environment.MaxFetchDepth], Is.EqualTo("11"));
            Assert.That(configure.Properties[Environment.QuerySubstitutions], Is.EqualTo("true 1, false 0, yes 'Y', no 'N'"));
            Assert.That(configure.Properties[Environment.Hbm2ddlAuto], Is.EqualTo("validate"));
            Assert.That(configure.Properties[Environment.LinqToHqlGeneratorsRegistry], Is.EqualTo(typeof(DefaultLinqToHqlGeneratorsRegistry).AssemblyQualifiedName));
        }