Example #1
0
        public bool Validar(string usr, string pass)
        {
            /*PROTECTED REGION ID(RetappGenNHibernate.CEN.Retapp_Admin_Validar) ENABLED START*/
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure();
            string ConnectionString          = cfg.GetProperty(NHibernate.Cfg.Environment.ConnectionString);

            bool esAdmin = false;

            try
            {
                SqlConnection c = new SqlConnection(ConnectionString);
                c.Open();
                SqlCommand    com = new SqlCommand("Select * from Usuario where [Gaccount] like '" + usr + "' and [Password] like '" + pass + "';", c);
                SqlDataReader dr  = com.ExecuteReader();
                if (dr.Read())
                {
                    esAdmin = true;
                }
                dr.Close();
                c.Close();
            }

            catch (Exception ex)
            {
                Console.WriteLine("Se ha producido una excepción al validar el Admin: " + ex);
            }

            return(esAdmin);

            /*PROTECTED REGION END*/
        }
Example #2
0
        internal DatabaseSessionFactory(NHibernate.Cfg.Configuration nhibernateConfig, bool reBuildSessionFactory = false)
        {
            string sessionFactoryKey = nhibernateConfig.GetProperty("session_factory_name");

            if (sessionFactoryDict.ContainsKey(sessionFactoryKey) && !reBuildSessionFactory)
            {
                sessionFactory = sessionFactoryDict[sessionFactoryKey];
            }
            else
            {
                //TODO:调试用的
                //HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();

                sessionFactory = nhibernateConfig.BuildSessionFactory();

                if (BuildedSessionFactory != null)
                {
                    BuildedSessionFactory(sessionFactory);
                }

                lock (helpLock)
                {
                    if (sessionFactoryDict.ContainsKey(sessionFactoryKey))
                    {
                        sessionFactoryDict[sessionFactoryKey] = sessionFactory;
                    }
                    else
                    {
                        sessionFactoryDict.Add(sessionFactoryKey, sessionFactory);
                    }
                }
            }
            this.FactoryName = sessionFactoryKey;
        }
        public static ISearchMapping CreateMapping(Configuration cfg)
        {
            System.Type mappingClass = GetMappingClass(cfg.GetProperty(Environment.MappingClass));

            object instance;
            try
            {
                instance = Activator.CreateInstance(mappingClass);
            }
            catch (Exception ex)
            {
                throw new SearchException(
                    "Could not create search mapping class '" + mappingClass.FullName + "'.", ex
                );
            }

            if (!(instance is ISearchMapping))
            {
                throw new SearchException(string.Format(
                    "Search mapping class '{0}' does not implement '{1}'.",
                    mappingClass.FullName, typeof(ISearchMapping).FullName
                ));
            }

            return (ISearchMapping)instance;
        }
Example #4
0
		/// <summary>
		/// Constructor.
		/// </summary>
		/// <param name="config"></param>
        protected Renderer(Configuration config)
		{
            _config = config;
			_dialect = Dialect.GetDialect(config.Properties);
            _defaultSchema = config.GetProperty(NHibernate.Cfg.Environment.DefaultSchema);

		}
Example #5
0
        public System.Collections.Generic.IList <RetappGenNHibernate.EN.Retapp.RetoEN> ReadRetos(int concurso)
        {
            /*PROTECTED REGION ID(RetappGenNHibernate.CEN.Retapp_Concurso_ReadRetos) ENABLED START*/

            // Write here your custom code...
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure();
            string ConnectionString          = cfg.GetProperty(NHibernate.Cfg.Environment.ConnectionString);

            List <RetoEN> lista = new List <RetoEN>();

            try
            {
                SqlConnection c = new SqlConnection(ConnectionString);
                c.Open();
                SqlCommand    com    = new SqlCommand("Select id from Reto where FK_idConcurso_idConcurso = " + concurso + " ; ", c);
                SqlDataReader dr     = com.ExecuteReader();
                RetoCEN       retcen = new RetoCEN();
                while (dr.Read())
                {
                    RetoEN ret = retcen.ReadOID(dr.GetInt32(0));
                    lista.Add(ret);
                }
                dr.Close();
                c.Close();
            }

            catch (Exception ex)
            {
                Console.WriteLine("Se ha producido una excepcion al leer los retos de un concurso: " + ex);
            }

            return(lista);

            /*PROTECTED REGION END*/
        }
Example #6
0
        public String Ranking(string usr)
        {
            /*PROTECTED REGION ID(RetappGenNHibernate.CEN.Retapp_Participacion_Ranking) ENABLED START*/

            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure();
            string ConnectionString          = cfg.GetProperty(NHibernate.Cfg.Environment.ConnectionString);

            // Write here your custom code...
            String ranking = "";

            try
            {
                SqlConnection c   = new SqlConnection(ConnectionString);
                SqlCommand    com = new SqlCommand("dbo.Ranking", c);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@user", usr);
                c.Open();
                SqlDataReader dr = com.ExecuteReader();
                while (dr.Read())
                {
                    ranking = ranking + dr.GetString(1) + "   |   " + dr.GetInt32(0) + "#";
                }
            }
            catch (Exception ex) { Console.WriteLine("Se ha producido una excepci�n al introducir la crear el ranking del usuario: " + ex); }
            return(ranking);

            /*PROTECTED REGION END*/
        }
        /// <summary>
        /// Configure the defaults for PostgreSQL support, but only if not already set, such as from another
        /// configuration activity or from the xml config
        /// </summary>
        /// <param name="configuration">The NHibernate <see cref="Configuration"/> instance to be manipulated.</param>
        public void Execute(NHibernate.Cfg.Configuration configuration)
        {
            var configuredDialect = configuration.GetProperty(Environment.Dialect);
            var configuredDriver  = configuration.GetProperty(Environment.ConnectionDriver);

            configuration.DataBaseIntegration(c =>
            {
                if (string.IsNullOrWhiteSpace(configuredDialect))
                {
                    c.Dialect <MsSql2012Dialect>();
                }

                if (string.IsNullOrWhiteSpace(configuredDriver))
                {
                    c.Driver <EdFiSql2008ClientDriver>();
                }
            });
        }
Example #8
0
		protected override void Configure(Configuration configuration)
		{
			base.Configure(configuration);

			// Ugly hack.
			_OrignalDialectIsMsSql2005Dialect = Regex.IsMatch(configuration.GetProperty("dialect"), "MsSql200(5|8)Dialect");

			configuration.SetProperty("dialect", "NHibernate.Test.NHSpecificTest.NH1849.CustomDialect, NHibernate.Test");
		}
Example #9
0
		public string[] GenerateCreateScripts(Configuration config)
		{
			var defaultSchema = config.GetProperty(NHibernate.Cfg.Environment.DefaultSchema);
			var tableName = !string.IsNullOrEmpty(defaultSchema) ? defaultSchema + "." + _tableName : _tableName;

			return new[]
				{
					string.Format("create table {0} ( {1} {2} );", tableName, _columnName, DdlScriptGenerator.GetDialect(config).GetTypeName( NHibernate.SqlTypes.SqlTypeFactory.Int64 )),
					string.Format("insert into {0} values ( {1} )", tableName, _initialValue)
				};
		}
Example #10
0
        protected SessionFactoryProvider(IConfiguration configuration, string nick, IInterceptor interceptor)
        {
            connectionInfo = configuration.GetSection("db")
                             .Get <ConnectionInfo[]>()
                             .SingleOrDefault(ci => ci.Nick == nick && ci.DbServerType == ServerType);
            if (connectionInfo == null)
            {
                throw new InvalidOperationException($"Connection with name {nick} is not found");
            }

            nhConfig = new NhConfiguration();
            nhConfig.CurrentSessionContext <ThreadLocalSessionContext>();
            nhConfig.SetProperty(Environment.SessionFactoryName, nick);
            nhConfig.Interceptor = interceptor ?? new EmptyInterceptor();
            nhConfig.SetProperty(Environment.UseSecondLevelCache, "false");
            Logger.LogDebug("NHibernate configuration: " + $"DbNick: {nhConfig.GetProperty(Environment.SessionFactoryName)}, "
                            + $"UseSecondLevelCache: {nhConfig.GetProperty(Environment.UseSecondLevelCache)}, "
                            + $"CacheDefaultExpiration: {nhConfig.GetProperty(Environment.CacheDefaultExpiration)}");

            Nick = nick;
            IsSkipHealthCheckEntity = connectionInfo.IsSkipHealthCheckEntity;
        }
Example #11
0
        /// <summary>
        /// Integrate ActsAsVersioned with NHibernate.
        /// </summary>
        /// <param name="configuration">The NHibernate configuration.</param>
        /// <returns>The NHibernate configuration.</returns>
        /// <remarks>
        /// WARNING: Be sure to call this method after set all configuration properties, after have added all your mappings
        /// and after integrate NHibernate with all others packages as NHibernate.Validator, NHibernate.Search, NHibernate.Spatial.
        /// </remarks>
        public static Configuration IntegrateWithActsAsVersioned(this Configuration configuration)
        {
            const string integratedKey = "ActsAsVersioned_Integrated";

            if (configuration.GetProperty(integratedKey) != null)
            {
                Logger.Warn($"{nameof(IntegrateWithActsAsVersioned)} has already been called for this configuration");
                return(configuration);
            }

            var versionedClasses = new List <VersionedClass>();

            foreach (var pc in configuration.ClassMappings)
            {
                if (!VersionedClass.IsActsAsVersioned(pc))
                {
                    continue;
                }

                versionedClasses.Add(new VersionedClass(pc));
            }

            if (versionedClasses.Count == 0)
            {
                // nothing to do
                return(configuration);
            }

            var mapping = configuration.BuildMapping();

            foreach (var vc in versionedClasses)
            {
                vc.UpdateConfiguration(configuration, mapping);
            }

            var listeners = new[] { new VersionedEventListener(versionedClasses) };

            // ReSharper disable CoVariantArrayConversion
            configuration.AppendListeners(ListenerType.PostInsert, listeners);
            configuration.AppendListeners(ListenerType.PostUpdate, listeners);
            configuration.AppendListeners(ListenerType.PostDelete, listeners);
            // ReSharper restore CoVariantArrayConversion

            configuration.SetProperty(integratedKey, "1");
            return(configuration);
        }
        public void Initialize(Configuration cfg)
        {
            searchFactory = SearchFactoryImpl.GetSearchFactory(cfg);
            string indexingStrategy = cfg.GetProperty(Environment.IndexingStrategy) ?? "event";

            if ("event".Equals(indexingStrategy))
            {
                used = searchFactory.DocumentBuilders.Count != 0;
            }
            else if ("manual".Equals(indexingStrategy))
            {
                used = false;
            }
            else
            {
                throw new SearchException(Environment.IndexBase + " unknown: " + indexingStrategy);
            }
        }
Example #13
0
        /// <summary>
        /// Initialisieren der Session mit den Datenbanknamen.
        /// </summary>
        private void InitSession()
        {
            // KO-Kriterien zum Initialisieren ausschliessen
            if (!System.IO.File.Exists(_database)) throw new System.IO.FileNotFoundException("Datenbank existiert nicht");

            // Session initialisieren (Configuration, SessionFactory, Session)
            Configuration cfg = new NHibernate.Cfg.Configuration();
            cfg.Configure();
            // ConnectionString parsen und %dbname% ersetzen
            String connectionString = cfg.GetProperty("hibernate.connection.connection_string");
            connectionString = connectionString.Replace("%dbname%", _database);
            cfg.SetProperty("hibernate.connection.connection_string", connectionString);
            cfg.AddAssembly(System.Reflection.Assembly.GetExecutingAssembly());

            ISessionFactory factory = cfg.BuildSessionFactory();

            _session = factory.OpenSession();
            _session.FlushMode = FlushMode.Commit;
        }
Example #14
0
        public bool IsFor(Configuration cfg) {
            var name = cfg.GetProperty(Environment.SessionFactoryName);
            using(var connection = myapp.ioc.get<IConnectionsSource>().Get(name).CreateConnection()) {
                try {
                    Console.WriteLine("try connection "+name+" for MAS");
                    connection.WellOpen();
                    var objid = connection.ExecuteScalar<int>("select object_id('mas.process')", (IParametersProvider)null);

                    var result = 0 != objid;
                    Console.WriteLine("connection " + name + "is for MAS: "+result);
                    return result;

                }catch(Exception ex) {
                    Console.WriteLine("connection " + name + "error: " + ex.Message);
                    return false;
                }
            }

        }
Example #15
0
        /// <summary>
        /// Runs the database upgrader
        /// </summary>
        /// <param name="scriptAssembly">The assembly containing the upgrade scripts</param>
        /// <param name="nhConfiguration">The NHibernate Configuration. The connection string must use a dbo user</param>
        public static int EnsureCurrentVersion(Assembly scriptAssembly, Configuration nhConfiguration)
        {
            var connectionString = nhConfiguration.GetProperty("connection.connection_string");

            var upgrader = new Upgrader(new ConnectionFactory(connectionString), new UpdateProvider(scriptAssembly), new DataInsertProvider(scriptAssembly));

            var oldVersion = upgrader.GetCurrentVersion();

            if (!oldVersion.HasValue)
            {
                upgrader.WipeDatabase();
                upgrader.CreateSchema(nhConfiguration);
                upgrader.RunInserts();
                return upgrader.SetLatestVersion();
            }
            else
            {
                return upgrader.RunUpdates(oldVersion.Value);
            }
        }
Example #16
0
        public System.Collections.Generic.IList <RetappGenNHibernate.EN.Retapp.VictoriaEN> Victorias_usr(string usr)
        {
            /*PROTECTED REGION ID(RetappGenNHibernate.CEN.Retapp_Victoria_Victorias_usr) ENABLED START*/

            // Write here your custom code...

            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration().Configure();
            string ConnectionString          = cfg.GetProperty(NHibernate.Cfg.Environment.ConnectionString);

            List <VictoriaEN> lista = new List <VictoriaEN>();

            try
            {
                SqlConnection c = new SqlConnection(ConnectionString);
                c.Open();
                SqlCommand    com   = new SqlCommand("Select idParticipacion from Participacion where FK_idUsuario_idUsuario_0 = " + usr + " ; ", c);
                SqlDataReader dr    = com.ExecuteReader();
                VictoriaCEN   vicen = new VictoriaCEN();
                while (dr.Read())
                {
                    VictoriaEN vit = vicen._IVictoriaCAD.ReadOID(dr.GetInt32(0));
                    lista.Add(vit);
                }
                dr.Close();
                c.Close();
            }

            catch (Exception ex)
            {
                Console.WriteLine("Se ha producido una excepcion al leer las victorias de un usuario: " + ex);
            }

            return(lista);

            /*PROTECTED REGION END*/
        }
Example #17
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;
        }
Example #18
0
        /// <summary>
        ///     Returns the NHibernate configuration for the specified connection alias.
        /// </summary>
        /// <param name="connectionAlias">The connection alias.</param>
        /// <returns>
        ///     NHibernate configuration
        /// </returns>
        public Configuration GetConfiguration(string connectionAlias)
        {
            var asm = GetAssemblyForResourceAssemblyName();
            var resourceName = GetResourceName();
            var cfg = new Configuration();
            cfg.Configure(asm, resourceName);
            if (string.Equals(cfg.GetProperty(Environment.SqlExceptionConverter),
                typeof (NHibernateSessionFactory).AssemblyQualifiedName))
            {
                cfg.SetProperty(
                    Environment.SqlExceptionConverter,
                    typeof (NHibernateSessionFactory).AssemblyQualifiedName);
            }

            SerializeDomainObjects(cfg);
            return cfg;
        }
Example #19
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;
        }
        public void SetConnectionString()
        {
            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            string shortConnectionString = @"%AppData%\Test\Test.data", expandedConnectionString = Environment.ExpandEnvironmentVariables(shortConnectionString);
            cfg.SetProperty(TestDataUtil.HibernateConnectionString, shortConnectionString);

            IDataBaseSetupImpl dataBaseSetup = new ProjectsRepository.DataBaseSetup(cfg);
            dataBaseSetup.ExpandEnvironmentVariablesInConnectionString();
            Assert.AreEqual(expandedConnectionString, cfg.GetProperty(TestDataUtil.HibernateConnectionString), "SetConnectionString doesn't expend environment variables properly.");
        }
        private static Analyzer InitAnalyzer(Configuration cfg)
        {
            System.Type analyzerClass;

            String analyzerClassName = cfg.GetProperty(Environment.AnalyzerClass);
            if (analyzerClassName != null)
                try
                {
                    analyzerClass = ReflectHelper.ClassForName(analyzerClassName);
                }
                catch (Exception e)
                {
                    throw new SearchException(
                        string.Format("Lucene analyzer class '{0}' defined in property '{1}' could not be found.",
                                      analyzerClassName, Environment.AnalyzerClass), e);
                }
            else
                analyzerClass = typeof(StandardAnalyzer);
            // Initialize analyzer
            Analyzer defaultAnalyzer;
            try
            {
                defaultAnalyzer = (Analyzer) Activator.CreateInstance(analyzerClass);
            }
            catch (InvalidCastException)
            {
                throw new SearchException(
                    string.Format("Lucene analyzer does not implement {0}: {1}", typeof(Analyzer).FullName,
                                  analyzerClassName)
                    );
            }
            catch (Exception)
            {
                throw new SearchException("Failed to instantiate lucene analyzer with type " + analyzerClassName);
            }
            return defaultAnalyzer;
        }