Esempio n. 1
0
 protected override bool AppliesTo(Dialect.Dialect dialect)
 {
     return(dialect.SupportsVariableLimit &&
            !(Dialect is Dialect.MsSql2000Dialect &&                 // don't know why, but these tests don't work on SQL Server using ODBC
              typeof(OdbcDriver).IsAssignableFrom(ReflectHelper.ClassForName(cfg.GetProperty(Environment.ConnectionDriver)))));
 }
Esempio n. 2
0
        public static void Main(string[] args)
        {
            try
            {
                var cfg = new Configuration();

                //string propFile = null;

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].StartsWith("--"))
                    {
                        //if (args[i].StartsWith("--properties="))
                        //{
                        //  propFile = args[i].Substring(13);
                        //}
                        //else
                        if (args[i].StartsWith("--config="))
                        {
                            cfg.Configure(args[i].Substring(9));
                        }
                        else if (args[i].StartsWith("--naming="))
                        {
                            cfg.SetNamingStrategy(
                                (INamingStrategy)
                                Cfg.Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(args[i].Substring(9))));
                        }
                    }
                    else
                    {
                        cfg.AddFile(args[i]);
                    }
                }

                /* NH: No props file for .NET
                 * if ( propFile != null ) {
                 *      Properties props = new Properties();
                 *      props.putAll( cfg.getProperties() );
                 *      props.load( new FileInputStream( propFile ) );
                 *      cfg.setProperties( props );
                 * }
                 */
                new SchemaValidator(cfg).Validate();
            }
            catch (Exception e)
            {
                log.Error("Error running schema update", e);
                Console.WriteLine(e);
            }
        }
Esempio n. 3
0
 public void SystemTypes()
 {
     System.Type int32 = ReflectHelper.ClassForName("System.Int32");
     Assert.AreEqual(typeof(Int32), int32);
 }
        public static System.Type GetSystemType(string key, IDictionary <string, string> properties, System.Type defaultValue)
        {
            var typeName = GetString(key, properties, null);

            return(typeName == null ? defaultValue : ReflectHelper.ClassForName(typeName));
        }
Esempio n. 5
0
        /// <summary>
        /// Uses heuristics to deduce a NHibernate type given a string naming the type.
        /// </summary>
        /// <param name="typeName">the type name</param>
        /// <param name="parameters">parameters for the type</param>
        /// <param name="length">optionally, the size of the type</param>
        /// <returns></returns>
        public static IType HeuristicType(string typeName, IDictionary <string, string> parameters, int?length)
        {
            IType type = Basic(typeName, parameters);

            if (type != null)
            {
                return(type);
            }

            string[]           parsedTypeName;
            TypeClassification typeClassification = GetTypeClassification(typeName);

            if (typeClassification == TypeClassification.LengthOrScale)
            {
                parsedTypeName = typeName.Split(LengthSplit);
            }
            else
            {
                parsedTypeName = typeClassification == TypeClassification.PrecisionScale ? typeName.Split(PrecisionScaleSplit) : new[] { typeName }
            };


            System.Type typeClass;
            try
            {
                typeClass = ReflectHelper.ClassForName(parsedTypeName[0]);                 //typeName);
            }
            catch (Exception)
            {
                typeClass = null;
            }

            if (typeClass == null)
            {
                return(null);
            }

            if (typeof(IType).IsAssignableFrom(typeClass))
            {
                try
                {
                    type = (IType)Environment.ObjectsFactory.CreateInstance(typeClass);
                }
                catch (Exception e)
                {
                    throw new MappingException("Could not instantiate IType " + typeClass.Name + ": " + e, e);
                }
                InjectParameters(type, parameters);

                var obsolete = typeClass.GetCustomAttribute <ObsoleteAttribute>(false);
                if (obsolete != null)
                {
                    _log.Warn("{0} is obsolete. {1}", typeName, obsolete.Message);
                }
                return(type);
            }
            if (typeof(ICompositeUserType).IsAssignableFrom(typeClass))
            {
                return(new CompositeCustomType(typeClass, parameters));
            }
            if (typeof(IUserType).IsAssignableFrom(typeClass))
            {
                return(new CustomType(typeClass, parameters));
            }
            if (typeof(ILifecycle).IsAssignableFrom(typeClass))
            {
                return(NHibernateUtil.Entity(typeClass));
            }

            var unwrapped = typeClass.UnwrapIfNullable();

            if (unwrapped.IsEnum)
            {
                return((IType)Activator.CreateInstance(typeof(EnumType <>).MakeGenericType(unwrapped)));
            }

            if (!typeClass.IsSerializable)
            {
                return(null);
            }

            if (typeClassification == TypeClassification.LengthOrScale)
            {
                return(GetSerializableType(typeClass, Int32.Parse(parsedTypeName[1])));
            }

            if (length.HasValue)
            {
                return(GetSerializableType(typeClass, length.Value));
            }

            return(GetSerializableType(typeClass));
        }
Esempio n. 6
0
        /// <summary>
        /// Uses heuristics to deduce a NHibernate type given a string naming the
        /// type.
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns>An instance of <c>NHibernate.Type.IType</c></returns>
        /// <remarks>
        /// When looking for the NHibernate type it will look in the cache of the Basic types first.
        /// If it doesn't find it in the cache then it uses the typeName to get a reference to the
        /// Class (Type in .NET).  Once we get the reference to the .NET class we check to see if it
        /// implements IType, ICompositeUserType, IUserType, ILifecycle (Association), or
        /// IPersistentEnum.  If none of those are implemented then we will serialize the Type to the
        /// database using NHibernate.Type.SerializableType(typeName)
        /// </remarks>
        public static IType HeuristicType(string typeName)
        {
            IType type = TypeFactory.Basic(typeName);

            if (type == null)
            {
                string[]           parsedTypeName;
                TypeClassification typeClassification = GetTypeClassification(typeName);
                if (typeClassification == TypeClassification.Length)
                {
                    parsedTypeName = typeName.Split(lengthSplit);
                }
                else if (typeClassification == TypeClassification.PrecisionScale)
                {
                    parsedTypeName = typeName.Split(precisionScaleSplit);
                }
                else
                {
                    parsedTypeName = new string[] { typeName };
                }


                System.Type typeClass;
                try
                {
                    typeClass = ReflectHelper.ClassForName(parsedTypeName[0]);                         //typeName);
                }
                catch (Exception)
                {
                    typeClass = null;
                }

                if (typeClass != null)
                {
                    if (typeof(IType).IsAssignableFrom(typeClass))
                    {
                        try
                        {
                            type = ( IType )Activator.CreateInstance(typeClass);
                        }
                        catch (Exception e)
                        {
                            throw new MappingException("Could not instantiate IType " + typeClass.Name + ": " + e, e);
                        }
                    }
                    else if (typeof(ICompositeUserType).IsAssignableFrom(typeClass))
                    {
                        type = new CompositeCustomType(typeClass);
                    }
                    else if (typeof(IUserType).IsAssignableFrom(typeClass))
                    {
                        type = new CustomType(typeClass);
                    }
                    else if (typeof(ILifecycle).IsAssignableFrom(typeClass))
                    {
                        type = NHibernateUtil.Entity(typeClass);
                    }
                    else if (typeClass.IsEnum)
                    {
                        type = NHibernateUtil.Enum(typeClass);
                    }
                    else if (typeClass.IsSerializable)
                    {
                        if (typeClassification == TypeClassification.Length)
                        {
                            type = GetSerializableType(typeClass, Int32.Parse(parsedTypeName[1]));
                        }
                        else
                        {
                            type = GetSerializableType(typeClass);
                        }
                    }
                }
            }
            return(type);
        }
        private void BuildFilterCachingStrategy(IDictionary <string, string> properties)
        {
            string impl = GetProperty(properties, Environment.FilterCachingStrategy);

            if (string.IsNullOrEmpty(impl) || impl.ToUpperInvariant().Equals("MRU"))
            {
                filterCachingStrategy = new MruFilterCachingStrategy();
            }
            else
            {
                try
                {
                    filterCachingStrategy = (IFilterCachingStrategy)Activator.CreateInstance(ReflectHelper.ClassForName(impl));
                }
                catch (InvalidCastException)
                {
                    throw new SearchException("Class does not implement IFilterCachingStrategy: " + impl);
                }
                catch (Exception ex)
                {
                    throw new SearchException("Failed to instantiate IFilterCachingStrategy with type " + impl, ex);
                }
            }

            filterCachingStrategy.Initialize(properties);
        }
        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:

            // TODO: Environment.BatchVersionedData
            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;
            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;

#pragma warning disable 618 // Disable warning for use of obsolete symbols.
            var interceptorsBeforeTransactionCompletionIgnoreExceptions = PropertiesHelper.GetBoolean(Environment.InterceptorsBeforeTransactionCompletionIgnoreExceptions, properties, false);
            log.Info("Ignoring exceptions in BeforeTransactionCompletion : " + EnabledDisabled(interceptorsBeforeTransactionCompletionIgnoreExceptions));
            settings.IsInterceptorsBeforeTransactionCompletionIgnoreExceptionsEnabled = interceptorsBeforeTransactionCompletionIgnoreExceptions;
#pragma warning restore 618

            // 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);
        }
        public static ILinqToHqlGeneratorsRegistry CreateGeneratorsRegistry(IDictionary <string, string> properties)
        {
            string registry;

            if (properties.TryGetValue(Environment.LinqToHqlGeneratorsRegistry, out registry))
            {
                try
                {
                    log.Info("Initializing LinqToHqlGeneratorsRegistry: {0}", registry);
                    return((ILinqToHqlGeneratorsRegistry)Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(registry)));
                }
                catch (Exception e)
                {
                    log.Fatal(e, "Could not instantiate LinqToHqlGeneratorsRegistry");
                    throw new HibernateException("Could not instantiate LinqToHqlGeneratorsRegistry: " + registry, e);
                }
            }
            return(new DefaultLinqToHqlGeneratorsRegistry());
        }
Esempio n. 10
0
        public static void Main(string[] args)
        {
            try
            {
                var cfg = new Configuration();

                bool script = true;
                // If true then execute db updates, otherwise just generate and display updates
                bool doUpdate = true;
                //String propFile = null;

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].StartsWith("--"))
                    {
                        if (args[i].Equals("--quiet"))
                        {
                            script = false;
                        }
                        else if (args[i].StartsWith("--properties="))
                        {
                            throw new NotSupportedException("No properties file for .NET, use app.config instead");
                            //propFile = args[i].Substring( 13 );
                        }
                        else if (args[i].StartsWith("--config="))
                        {
                            cfg.Configure(args[i].Substring(9));
                        }
                        else if (args[i].StartsWith("--text"))
                        {
                            doUpdate = false;
                        }
                        else if (args[i].StartsWith("--naming="))
                        {
                            cfg.SetNamingStrategy(
                                (INamingStrategy)
                                Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(args[i].Substring(9))));
                        }
                    }
                    else
                    {
                        cfg.AddFile(args[i]);
                    }
                }

                /* NH: No props file for .NET
                 * if ( propFile != null ) {
                 *      Hashtable props = new Hashtable();
                 *      props.putAll( cfg.Properties );
                 *      props.load( new FileInputStream( propFile ) );
                 *      cfg.SetProperties( props );
                 * }*/

                new SchemaUpdate(cfg).Execute(script, doUpdate);
            }
            catch (Exception e)
            {
                log.Error("Error running schema update", e);
                Console.WriteLine(e);
            }
        }
        public static async Task MainAsync(string[] args, CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();
            try
            {
                var cfg = new Configuration();

                //string propFile = null;

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i].StartsWith("--", StringComparison.Ordinal))
                    {
                        //if (args[i].StartsWith("--properties="))
                        //{
                        //  propFile = args[i].Substring(13);
                        //}
                        //else
                        if (args[i].StartsWith("--config=", StringComparison.Ordinal))
                        {
                            cfg.Configure(args[i].Substring(9));
                        }
                        else if (args[i].StartsWith("--naming=", StringComparison.Ordinal))
                        {
                            cfg.SetNamingStrategy(
                                (INamingStrategy)
                                Cfg.Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(args[i].Substring(9))));
                        }
                    }
                    else
                    {
                        cfg.AddFile(args[i]);
                    }
                }

                /* NH: No props file for .NET
                 * if ( propFile != null ) {
                 *      Properties props = new Properties();
                 *      props.putAll( cfg.getProperties() );
                 *      props.load( new FileInputStream( propFile ) );
                 *      cfg.setProperties( props );
                 * }
                 */
                await(new SchemaValidator(cfg).ValidateAsync(cancellationToken)).ConfigureAwait(false);
            }
            catch (OperationCanceledException) { throw; }
            catch (Exception e)
            {
                log.Error(e, "Error running schema update");
                Console.WriteLine(e);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Configures the driver for the ConnectionProvider.
        /// </summary>
        /// <param name="settings">An <see cref="IDictionary"/> that contains the settings for the Driver.</param>
        /// <exception cref="HibernateException">
        /// Thrown when the <see cref="Environment.ConnectionDriver"/> could not be
        /// found in the <c>settings</c> parameter or there is a problem with creating
        /// the <see cref="IDriver"/>.
        /// </exception>
        protected virtual void ConfigureDriver(IDictionary <string, string> settings)
        {
            string driverClass;

            if (!settings.TryGetValue(Environment.ConnectionDriver, out driverClass))
            {
                throw new HibernateException("The " + Environment.ConnectionDriver +
                                             " must be specified in the NHibernate configuration section.");
            }
            else
            {
                try
                {
                    driver =
                        (IDriver)Environment.BytecodeProvider.ObjectsFactory.CreateInstance(ReflectHelper.ClassForName(driverClass));
                    driver.Configure(settings);
                }
                catch (Exception e)
                {
                    throw new HibernateException("Could not create the driver from " + driverClass + ".", e);
                }
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Uses heuristics to deduce a NHibernate type given a string naming the type.
        /// </summary>
        /// <param name="typeName">the type name</param>
        /// <param name="parameters">parameters for the type</param>
        /// <param name="length">optionally, the size of the type</param>
        /// <returns></returns>
        public static IType HeuristicType(string typeName, IDictionary <string, string> parameters, int?length)
        {
            IType type = Basic(typeName);

            if (type == null)
            {
                string[]           parsedTypeName;
                TypeClassification typeClassification = GetTypeClassification(typeName);
                if (typeClassification == TypeClassification.Length)
                {
                    parsedTypeName = typeName.Split(LengthSplit);
                }
                else
                {
                    parsedTypeName = typeClassification == TypeClassification.PrecisionScale ? typeName.Split(PrecisionScaleSplit) : new[] { typeName }
                };


                System.Type typeClass;
                try
                {
                    typeClass = ReflectHelper.ClassForName(parsedTypeName[0]);                     //typeName);
                }
                catch (Exception)
                {
                    typeClass = null;
                }

                if (typeClass != null)
                {
                    if (typeof(IType).IsAssignableFrom(typeClass))
                    {
                        try
                        {
                            type = (IType)Cfg.Environment.BytecodeProvider.ObjectsFactory.CreateInstance(typeClass);
                        }
                        catch (Exception e)
                        {
                            throw new MappingException("Could not instantiate IType " + typeClass.Name + ": " + e, e);
                        }
                        InjectParameters(type, parameters);
                    }
                    else if (typeof(ICompositeUserType).IsAssignableFrom(typeClass))
                    {
                        type = new CompositeCustomType(typeClass, parameters);
                    }
                    else if (typeof(IUserType).IsAssignableFrom(typeClass))
                    {
                        type = new CustomType(typeClass, parameters);
                    }
                    else if (typeof(ILifecycle).IsAssignableFrom(typeClass))
                    {
                        type = NHibernateUtil.Entity(typeClass);
                    }
                    else if (typeClass.IsEnum)
                    {
                        try
                        {
                            type = (IType)Activator.CreateInstance(typeof(EnumType <>).MakeGenericType(typeClass));
                        }
                        catch (Exception e)
                        {
                            throw new MappingException("Can't instantiate enum " + typeClass.FullName + "; The enum can't be empty", e);
                        }
                    }
                    else if (IsNullableEnum(typeClass))
                    {
                        try
                        {
                            type = (IType)Activator.CreateInstance(typeof(EnumType <>).MakeGenericType(typeClass.GetGenericArguments()[0]));
                        }
                        catch (Exception e)
                        {
                            throw new MappingException("Can't instantiate enum " + typeClass.FullName + "; The enum can't be empty", e);
                        }
                    }
                    else if (typeClass.IsSerializable)
                    {
                        if (typeClassification == TypeClassification.Length)
                        {
                            type = GetSerializableType(typeClass, Int32.Parse(parsedTypeName[1]));
                        }
                        else if (length != null)
                        {
                            type = GetSerializableType(typeClass, length.Value);
                        }
                        else
                        {
                            type = GetSerializableType(typeClass);
                        }
                    }
                }
            }
            return(type);
        }
        public static Settings BuildSettings(IDictionary properties)
        {
            Settings settings = new Settings();

            Dialect.Dialect dialect = null;
            try
            {
                dialect = Dialect.Dialect.GetDialect(properties);
                IDictionary temp = new Hashtable();

                foreach (DictionaryEntry de in dialect.DefaultProperties)
                {
                    temp[de.Key] = de.Value;
                }
                foreach (DictionaryEntry 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();
            }

            // TODO: SQLExceptionConverter

            // TODO: should this be enabled?
//			int statementFetchSize = PropertiesHelper.GetInt32( Environment.StatementFetchSize, properties, -1 );
//			if( statementFetchSize != -1 )
//			{
//				log.Info( "JDBC result set fetch size: " + statementFetchSize );
//			}

            int maxFetchDepth = PropertiesHelper.GetInt32(Environment.MaxFetchDepth, properties, -1);

            if (maxFetchDepth != -1)
            {
                log.Info("Maximum outer join fetch depth: " + maxFetchDepth);
            }

            //deprecated:
            bool useOuterJoin = PropertiesHelper.GetBoolean(Environment.UseOuterJoin, properties, true);

            log.Info("use outer join fetching: " + useOuterJoin);

            IConnectionProvider connectionProvider = ConnectionProviderFactory.NewConnectionProvider(properties);
            ITransactionFactory transactionFactory = new TransactionFactory();             // = TransactionFactoryFactory.BuildTransactionFactory(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 defaultSchema = properties[Environment.DefaultSchema] as string;

            if (defaultSchema != null)
            {
                log.Info("Default schema set to: " + defaultSchema);
            }

            bool showSql = PropertiesHelper.GetBoolean(Environment.ShowSql, properties, false);

            if (showSql)
            {
                log.Info("echoing all SQL to stdout");
            }

            // queries:

            IDictionary querySubstitutions = PropertiesHelper.ToDictionary(Environment.QuerySubstitutions, " ,=;:\n\t\r\f", properties);

            if (log.IsInfoEnabled)
            {
                log.Info("Query language substitutions: " + CollectionPrinter.ToString(querySubstitutions));
            }

            string autoSchemaExport = properties[Environment.Hbm2ddlAuto] as string;

            if ("update" == autoSchemaExport)
            {
                settings.IsAutoUpdateSchema = true;
            }
            if ("create" == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
            }
            if ("create-drop" == autoSchemaExport)
            {
                settings.IsAutoCreateSchema = true;
                settings.IsAutoDropSchema   = true;
            }

            string cacheClassName = PropertiesHelper.GetString(Environment.CacheProvider, properties, "NHibernate.Cache.HashtableCacheProvider");

            log.Info("cache provider: " + cacheClassName);
            try
            {
                settings.CacheProvider = ( ICacheProvider )Activator.CreateInstance(ReflectHelper.ClassForName(cacheClassName));
            }
            catch (Exception e)
            {
                throw new HibernateException("could not instantiate CacheProvider: " + cacheClassName, e);
            }

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

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

            string sessionFactoryName = ( string )properties[Environment.SessionFactoryName];

            // TODO: Environment.BatchVersionedData
            // TODO: wrapResultSets/DataReaders

            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.ToString());
                }
                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);
                }
            }

            bool prepareSql = PropertiesHelper.GetBoolean(Environment.PrepareSql, properties, false);

            int cmdTimeout = PropertiesHelper.GetInt32(Environment.CommandTimeout, properties, 0);

            // Not ported - settings.StatementFetchSize = statementFetchSize;
            // Not ported - ScrollableResultSetsEnabled
            // Not ported - GetGeneratedKeysEnabled
            // Not ported - settings.BatchSize = batchSize;
            settings.DefaultSchemaName  = defaultSchema;
            settings.IsShowSqlEnabled   = showSql;
            settings.Dialect            = dialect;
            settings.ConnectionProvider = connectionProvider;
            settings.QuerySubstitutions = querySubstitutions;
            settings.TransactionFactory = transactionFactory;
            // Not ported - TransactionManagerLookup
            settings.SessionFactoryName      = sessionFactoryName;
            settings.IsOuterJoinFetchEnabled = useOuterJoin;
            settings.MaximumFetchDepth       = maxFetchDepth;
            settings.IsQueryCacheEnabled     = useQueryCache;
            settings.IsMinimalPutsEnabled    = useMinimalPuts;
            // Not ported - JdbcBatchVersionedData
            // TODO: SQLExceptionConverter
            // TODO: WrapResultSetsEnabled

            // NHibernate-specific:
            settings.IsolationLevel = isolation;
            settings.PrepareSql     = prepareSql;
            settings.CommandTimeout = cmdTimeout;

            return(settings);
        }
Esempio n. 15
0
        public void BindEntity()
        {
            persistentClass.IsAbstract = annotatedClass.IsAbstract;
            persistentClass.ClassName  = annotatedClass.Name;
            persistentClass.NodeName   = name;
            //TODO:review this
            //persistentClass.setDynamic(false); //no longer needed with the Entity name refactoring?
            persistentClass.EntityName = (annotatedClass.Name);
            BindDiscriminatorValue();

            persistentClass.IsLazy = lazy;
            if (proxyClass != null)
            {
                persistentClass.ProxyInterfaceName = proxyClass.Name;
            }
            persistentClass.DynamicInsert = dynamicInsert;
            persistentClass.DynamicUpdate = dynamicUpdate;

            if (persistentClass is RootClass)
            {
                RootClass rootClass = (RootClass)persistentClass;
                bool      mutable   = true;
                //priority on @Immutable, then @Entity.mutable()
                if (annotatedClass.IsAttributePresent <ImmutableAttribute>())
                {
                    mutable = false;
                }
                else
                {
                    var entityAnn = annotatedClass.GetAttribute <EntityAttribute>();
                    if (entityAnn != null)
                    {
                        mutable = entityAnn.IsMutable;
                    }
                }
                rootClass.IsMutable = mutable;
                rootClass.IsExplicitPolymorphism = ExplicitPolymorphismConverter.Convert(polymorphismType);
                if (StringHelper.IsNotEmpty(where))
                {
                    rootClass.Where = where;
                }

                if (cacheConcurrentStrategy != null)
                {
                    rootClass.CacheConcurrencyStrategy = cacheConcurrentStrategy;
                    rootClass.CacheRegionName          = cacheRegion;
                    //TODO: LazyPropertiesCacheable
                    //rootClass.LazyPropertiesCacheable =  cacheLazyProperty ;
                }
                rootClass.IsForceDiscriminator = annotatedClass.IsAttributePresent <ForceDiscriminatorAttribute>();
            }
            else
            {
                if (explicitHibernateEntityAnnotation)
                {
                    log.WarnFormat("[NHibernate.Annotations.Entity] used on a non root entity: ignored for {0}", annotatedClass.Name);
                }
                if (annotatedClass.IsAttributePresent <ImmutableAttribute>())
                {
                    log.WarnFormat("[Immutable] used on a non root entity: ignored for {0}", annotatedClass.Name);
                }
            }
            persistentClass.OptimisticLockMode = OptimisticLockModeConverter.Convert(optimisticLockType);
            persistentClass.SelectBeforeUpdate = selectBeforeUpdate;

            //set persister if needed
            //[Persister] has precedence over [Entity.persister]
            var persisterAnn = annotatedClass.GetAttribute <PersisterAttribute>();

            System.Type persister = null;
            if (persisterAnn != null)
            {
                persister = persisterAnn.Implementation;
            }
            else
            {
                var entityAnn = annotatedClass.GetAttribute <EntityAttribute>();
                if (entityAnn != null && !BinderHelper.IsDefault(entityAnn.Persister))
                {
                    try
                    {
                        persister = ReflectHelper.ClassForName(entityAnn.Persister);
                    }
                    catch (TypeLoadException tle)
                    {
                        throw new AnnotationException("Could not find persister class: " + persister, tle);
                    }
                }
            }
            if (persister != null)
            {
                persistentClass.EntityPersisterClass = persister;
            }
            persistentClass.BatchSize = batchSize;

            //SQL overriding
            var sqlInsert    = annotatedClass.GetAttribute <SQLInsertAttribute>();
            var sqlUpdate    = annotatedClass.GetAttribute <SQLUpdateAttribute>();
            var sqlDelete    = annotatedClass.GetAttribute <SQLDeleteAttribute>();
            var sqlDeleteAll = annotatedClass.GetAttribute <SQLDeleteAllAttribute>();
            var loader       = annotatedClass.GetAttribute <LoaderAttribute>();

            if (sqlInsert != null)
            {
                persistentClass.SetCustomSQLInsert(sqlInsert.Sql.Trim(), sqlInsert.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlInsert.Check));
            }
            if (sqlUpdate != null)
            {
                persistentClass.SetCustomSQLUpdate(sqlUpdate.Sql.Trim(), sqlUpdate.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlUpdate.Check));
            }
            if (sqlDelete != null)
            {
                persistentClass.SetCustomSQLDelete(sqlDelete.Sql, sqlDelete.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlDelete.Check));
            }
            if (sqlDeleteAll != null)
            {
                persistentClass.SetCustomSQLDelete(sqlDeleteAll.Sql, sqlDeleteAll.Callable,
                                                   ExecuteUpdateResultCheckStyleConverter.Convert(sqlDeleteAll.Check));
            }
            if (loader != null)
            {
                persistentClass.LoaderName = loader.NamedQuery;
            }

            //tuplizers
            if (annotatedClass.IsAttributePresent <TuplizerAttribute>())
            {
                foreach (TuplizerAttribute tuplizer in annotatedClass.GetAttributes <TuplizerAttribute>())
                {
                    var mode = EntityModeConverter.Convert(tuplizer.EntityMode);
                    persistentClass.AddTuplizer(mode, tuplizer.Implementation.Name);
                }
            }
            if (annotatedClass.IsAttributePresent <TuplizerAttribute>())
            {
                var tuplizer = annotatedClass.GetAttribute <TuplizerAttribute>();
                var mode     = EntityModeConverter.Convert(tuplizer.EntityMode);
                persistentClass.AddTuplizer(mode, tuplizer.Implementation.Name);
            }

            if (!inheritanceState.HasParents)
            {
                var iter = filters.GetEnumerator();
                while (iter.MoveNext())
                {
                    var    filter     = iter.Current;
                    String filterName = filter.Key;
                    String cond       = filter.Value;
                    if (BinderHelper.IsDefault(cond))
                    {
                        FilterDefinition definition = mappings.GetFilterDefinition(filterName);
                        cond = definition == null ? null : definition.DefaultFilterCondition;
                        if (StringHelper.IsEmpty(cond))
                        {
                            throw new AnnotationException("no filter condition found for filter " + filterName + " in " + name);
                        }
                    }
                    persistentClass.AddFilter(filterName, cond);
                }
            }
            else
            {
                if (filters.Count > 0)
                {
                    log.WarnFormat("@Filter not allowed on subclasses (ignored): {0}", persistentClass.EntityName);
                }
            }
            log.DebugFormat("Import with entity name {0}", name);

            try
            {
                mappings.AddImport(persistentClass.EntityName, name);
                String entityName = persistentClass.EntityName;
                if (!entityName.Equals(name))
                {
                    mappings.AddImport(entityName, entityName);
                }
            }
            catch (MappingException me)
            {
                throw new AnnotationException("Use of the same entity name twice: " + name, me);
            }
        }