Exemple #1
0
        /// <summary>
        /// Ensures the database integrity.
        /// </summary>
        /// <param name="systemId">The system id.</param>
        /// <param name="descriptor">The descriptor.</param>
        /// <param name="mode">The mode.</param>
        /// <exception cref="UnexpectedNHibernateConfigurationException">
        /// Unexpected dialect.
        /// or
        /// Unexpected connection driver.
        /// </exception>
        /// <exception cref="InvalidConfigurationException">
        /// Unable to find connection information in NHibernate Descriptor settings.
        /// or
        /// Unable to find data source in connection string.
        /// </exception>
        /// <exception cref="DatabaseVerificationErrorException"></exception>
        public virtual void EnsureDatabaseIntegrity(long systemId, Dictionary<string, string> descriptor, SchemaFactoryModeEnum mode)
        {
            if (descriptor == null)
            {
                ThrowHelper.ThrowArgumentNullException("descriptor");
            }

            if (descriptor.ContainsKey(DIALECT))
            {
                string dialect = descriptor[DIALECT];
                if (!dialect.StartsWith(DIALECT_EXPECTED_VALUE_BUILTIN) && !dialect.StartsWith(DIALECT_EXPECTED_VALUE_CUSTOM))
                {
                    throw new UnexpectedNHibernateConfigurationException("Unexpected dialect.");
                }
            }

            if (descriptor.ContainsKey(CONNECTION_DRIVER))
            {
                if (!CONNECTION_DRIVER_EXPECTED_VALUE.Equals(descriptor[CONNECTION_DRIVER]))
                {
                    throw new UnexpectedNHibernateConfigurationException("Unexpected connection driver.");
                }
            }

            string databaseFile = string.Empty;
            string connectionString = string.Empty;

            if (descriptor.ContainsKey(CONNECTION_STRING))
            {
                connectionString = descriptor[CONNECTION_STRING];
                databaseFile = GetDatabaseFile(connectionString);
            }
            else if (descriptor.ContainsKey(CONNECTION_STRING_NAME))
            {
                connectionString = ConfigurationManager.ConnectionStrings[descriptor[CONNECTION_STRING_NAME]].ConnectionString;
                databaseFile = GetDatabaseFile(connectionString);
            }
            else
            {
                throw new InvalidConfigurationException("Unable to find connection information in NHibernate Descriptor settings.");
            }

            if (string.IsNullOrEmpty(databaseFile))
            {
                throw new InvalidConfigurationException("Unable to find data source in connection string.");
            }

            using (SqlCeEngine en = new SqlCeEngine(connectionString))
            {
                FileInfo dbFileInfo = new FileInfo(databaseFile);
                if (!dbFileInfo.Exists)
                {
                    en.CreateDatabase();
                }
                else
                {
                    if (mode == SchemaFactoryModeEnum.Create || mode == SchemaFactoryModeEnum.Create_And_Drop)
                    {
                        dbFileInfo.Delete();
                        en.CreateDatabase();
                    }
                    else
                    {
                        if (!en.Verify(VerifyOption.Enhanced))
                        {
                            throw new DatabaseVerificationErrorException();
                        }
                    }
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Ensures the database integrity.
        /// </summary>
        /// <param name="systemId">The system id.</param>
        /// <param name="descriptor">The descriptor.</param>
        /// <param name="mode">The mode.</param>
        /// <exception cref="UnexpectedNHibernateConfigurationException">Unexpected dialect.
        /// or
        /// Unexpected connection driver.</exception>
        /// <exception cref="InvalidConfigurationException">
        /// Unable to connection information in NHibernate Descriptor settings.
        /// or
        /// Unable to find data source in connection string.
        /// </exception>
        /// <exception cref="Forge.Configuration.Shared.InvalidConfigurationException">Unable to connection information in NHibernate Descriptor settings.
        /// or
        /// Unable to find data source in connection string.</exception>
        public virtual void EnsureDatabaseIntegrity(long systemId, Dictionary<string, string> descriptor, SchemaFactoryModeEnum mode)
        {
            if (descriptor == null)
            {
                ThrowHelper.ThrowArgumentNullException("descriptor");
            }

            if (descriptor.ContainsKey(DIALECT))
            {
                if (!DIALECT_EXPECTED_VALUE.Equals(descriptor[DIALECT]))
                {
                    throw new UnexpectedNHibernateConfigurationException("Unexpected dialect.");
                }
            }

            if (descriptor.ContainsKey(CONNECTION_DRIVER))
            {
                if (!CONNECTION_DRIVER_EXPECTED_VALUE.Equals(descriptor[CONNECTION_DRIVER]))
                {
                    throw new UnexpectedNHibernateConfigurationException("Unexpected connection driver.");
                }
            }

            string databaseFile = string.Empty;
            string connectionString = string.Empty;

            if (descriptor.ContainsKey(CONNECTION_STRING))
            {
                connectionString = descriptor[CONNECTION_STRING];
                databaseFile = GetDatabaseFile(connectionString);
            }
            else if (descriptor.ContainsKey(CONNECTION_STRING_NAME))
            {
                connectionString = ConfigurationManager.ConnectionStrings[descriptor[CONNECTION_STRING_NAME]].ConnectionString;
                databaseFile = GetDatabaseFile(connectionString);
            }
            else
            {
                throw new InvalidConfigurationException("Unable to connection information in NHibernate Descriptor settings.");
            }

            if (string.IsNullOrEmpty(databaseFile))
            {
                throw new InvalidConfigurationException("Unable to find data source in connection string.");
            }

            using (SQLiteFactory factory = new SQLiteFactory())
            {
                FileInfo dbFileInfo = new FileInfo(databaseFile);
                if (!dbFileInfo.Exists)
                {
                    using (DbConnection connection = factory.CreateConnection())
                    {
                        connection.ConnectionString = connectionString;
                        connection.Open();
                    }
                }
                else
                {
                    if (mode == SchemaFactoryModeEnum.Create || mode == SchemaFactoryModeEnum.Create_And_Drop)
                    {
                        dbFileInfo.Delete();
                        using (DbConnection connection = factory.CreateConnection())
                        {
                            connection.ConnectionString = connectionString;
                            connection.Open();
                        }
                    }
                }
            }
        }
Exemple #3
0
        /// <summary>
        /// Ensures the database integrity.
        /// </summary>
        /// <param name="systemId">The system id.</param>
        /// <param name="descriptor">The descriptor.</param>
        /// <param name="mode">The mode.</param>
        /// <exception cref="InitializationException">MsSql2008 Manager has not been initialized.</exception>
        /// <exception cref="InvalidConfigurationException">Unable to connection information in NHibernate Descriptor settings.</exception>
        /// <exception cref="InvalidConfigurationValueException">Connection string is empty.
        /// or
        /// Connection string does not contains DATABASE nor DATA SOURCE definition.
        /// or
        /// Connection string does not contains PASSWORD definition.
        /// or
        /// Connection string does not contains information about the database name.</exception>
        public void EnsureDatabaseIntegrity(long systemId, Dictionary <string, string> descriptor, SchemaFactoryModeEnum mode)
        {
            if (!this.IsInitialized)
            {
                throw new InitializationException("MsSql2008 Manager has not been initialized.");
            }
            if (descriptor == null)
            {
                ThrowHelper.ThrowArgumentNullException("descriptor");
            }

            string connectionString = string.Empty;

            if (descriptor.ContainsKey(CONNECTION_STRING))
            {
                connectionString = descriptor[CONNECTION_STRING];
            }
            else if (descriptor.ContainsKey(CONNECTION_STRING_NAME))
            {
                connectionString = ConfigurationManager.ConnectionStrings[descriptor[CONNECTION_STRING_NAME]].ConnectionString;
            }
            else
            {
                throw new InvalidConfigurationException("Unable to connection information in NHibernate Descriptor settings.");
            }

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new InvalidConfigurationValueException("Connection string is empty.");
            }

            Dictionary <string, string> data = ParseConnectionString(connectionString);

            if (!data.ContainsKey(INITIAL_CATALOG) && !data.ContainsKey(DATABASE))
            {
                throw new InvalidConfigurationValueException("Connection string does not contains DATABASE nor DATA SOURCE definition.");
            }

            string collation = string.Empty;
            string database  = string.Empty;
            string password  = string.Empty;
            string userId    = string.Empty;

            if (data.ContainsKey(USER_ID))
            {
                userId = data[USER_ID];
                if (data.ContainsKey(PASSWORD))
                {
                    password = data[PASSWORD];
                }
                else
                {
                    throw new InvalidConfigurationValueException("Connection string does not contains PASSWORD definition.");
                }
            }
            else
            {
                // add current windows principal
                userId = string.Format(@"{0}\{1}", Environment.UserDomainName, Environment.UserName);
            }

            if (data.ContainsKey(DATABASE))
            {
                database = data[DATABASE];
            }
            else if (data.ContainsKey(INITIAL_CATALOG))
            {
                database = data[INITIAL_CATALOG];
            }
            else
            {
                throw new InvalidConfigurationValueException("Connection string does not contains information about the database name.");
            }

            if (descriptor.ContainsKey(DATABASE_COLLATION))
            {
                collation = descriptor[DATABASE_COLLATION];
            }

            using (SqlConnection connection = new SqlConnection(mConnectionStringForAdmin))
            {
                connection.Open();
                SqlCommand command = null;

                bool isExist = false;

                if (!string.IsNullOrEmpty(password))
                {
                    using (command = new SqlCommand(Resources.CheckLogin, connection))
                    {
                        command.CommandTimeout = mDefaultCommandTimeout;
                        command.Parameters.Add(new SqlParameter("@P0", System.Data.SqlDbType.VarChar)
                        {
                            Value = userId
                        });
                        isExist = (int)command.ExecuteScalar() > 0;
                    }

                    if (!isExist)
                    {
                        // CREATE LOGIN {0} WITH PASSWORD = '******', CHECK_EXPIRATION = OFF, CHECK_POLICY = OFF;
                        using (command = new SqlCommand(string.Format(Resources.CreateLogin, userId, password), connection))
                        {
                            command.CommandTimeout = mDefaultCommandTimeout;
                            command.ExecuteNonQuery();
                        }
                    }
                }

                // SELECT COUNT(*) FROM master.dbo.sysdatabases db WHERE db.name = @P0
                using (command = new SqlCommand(string.Format(Resources.DatabaseCheck, database), connection))
                {
                    command.CommandTimeout = mDefaultCommandTimeout;
                    command.Parameters.Add(new SqlParameter("@P0", System.Data.SqlDbType.VarChar)
                    {
                        Value = database
                    });
                    isExist = (int)command.ExecuteScalar() > 0;
                }

                if (!isExist)
                {
                    // CREATE DATABASE {0} [COLLATE collation_name]
                    string commandText = string.IsNullOrEmpty(collation) ? string.Format(Resources.CreateDatabase, database) : (string.Format("{0} COLLATE {1}", string.Format(Resources.CreateDatabase, database), collation));
                    using (command = new SqlCommand(commandText, connection))
                    {
                        command.CommandTimeout = mDefaultCommandTimeout;
                        command.ExecuteNonQuery();
                    }
                }
                else if (!string.IsNullOrEmpty(collation))
                {
                    // SELECT DATABASEPROPERTYEX('{0}', 'Collation') SQLCollation
                    bool isEqual = false;
                    using (command = new SqlCommand(string.Format(Resources.GetDatabaseCollation, database), connection))
                    {
                        command.CommandTimeout = mDefaultCommandTimeout;
                        isEqual = collation.Equals(command.ExecuteScalar());
                    }
                    if (!isEqual)
                    {
                        // ALTER DATABASE [{0}] COLLATE {1}
                        using (command = new SqlCommand(string.Format(Resources.AlterDatabaseCollation, database, collation), connection))
                        {
                            try
                            {
                                LOGGER.Info(string.Format("MSSQL2008MANAGER, trying to alter database '{0}' collation. If this transaction freeze, please other services and transaction which are possible keep lock on this database object.", database));
                                command.CommandTimeout = mDefaultCommandTimeout;
                                command.ExecuteNonQuery();
                                LOGGER.Info(string.Format("MSSQL2008MANAGER, database '{0}' collation successfully modified.", database));
                            }
                            catch (Exception ex)
                            {
                                LOGGER.Error(string.Format("MSSQL2008MANAGER, failed to alter database '{0}' collation to '{1}'.", database, collation), ex);
                            }
                        }
                    }
                }

                // ALTER AUTHORIZATION ON DATABASE::{0} TO [{1}]
                using (command = new SqlCommand(string.Format(Resources.SetDatabaseOwner, database, userId), connection))
                {
                    command.CommandTimeout = mDefaultCommandTimeout;
                    command.ExecuteNonQuery();
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Ensures the database integrity.
        /// </summary>
        /// <param name="systemId">The system id.</param>
        /// <param name="descriptor">The descriptor.</param>
        /// <param name="mode">The mode.</param>
        /// <exception cref="UnexpectedNHibernateConfigurationException">Unexpected dialect.
        /// or
        /// Unexpected connection driver.</exception>
        /// <exception cref="InvalidConfigurationException">
        /// Unable to connection information in NHibernate Descriptor settings.
        /// or
        /// Unable to find data source in connection string.
        /// </exception>
        /// <exception cref="Forge.Configuration.Shared.InvalidConfigurationException">Unable to connection information in NHibernate Descriptor settings.
        /// or
        /// Unable to find data source in connection string.</exception>
        public virtual void EnsureDatabaseIntegrity(long systemId, Dictionary <string, string> descriptor, SchemaFactoryModeEnum mode)
        {
            if (descriptor == null)
            {
                ThrowHelper.ThrowArgumentNullException("descriptor");
            }

            if (descriptor.ContainsKey(DIALECT))
            {
                if (!DIALECT_EXPECTED_VALUE.Equals(descriptor[DIALECT]))
                {
                    throw new UnexpectedNHibernateConfigurationException("Unexpected dialect.");
                }
            }

            if (descriptor.ContainsKey(CONNECTION_DRIVER))
            {
                if (!CONNECTION_DRIVER_EXPECTED_VALUE.Equals(descriptor[CONNECTION_DRIVER]))
                {
                    throw new UnexpectedNHibernateConfigurationException("Unexpected connection driver.");
                }
            }

            string databaseFile     = string.Empty;
            string connectionString = string.Empty;

            if (descriptor.ContainsKey(CONNECTION_STRING))
            {
                connectionString = descriptor[CONNECTION_STRING];
                databaseFile     = GetDatabaseFile(connectionString);
            }
            else if (descriptor.ContainsKey(CONNECTION_STRING_NAME))
            {
                connectionString = ConfigurationManager.ConnectionStrings[descriptor[CONNECTION_STRING_NAME]].ConnectionString;
                databaseFile     = GetDatabaseFile(connectionString);
            }
            else
            {
                throw new InvalidConfigurationException("Unable to connection information in NHibernate Descriptor settings.");
            }

            if (string.IsNullOrEmpty(databaseFile))
            {
                throw new InvalidConfigurationException("Unable to find data source in connection string.");
            }

            using (SQLiteFactory factory = new SQLiteFactory())
            {
                FileInfo dbFileInfo = new FileInfo(databaseFile);
                if (!dbFileInfo.Exists)
                {
                    using (DbConnection connection = factory.CreateConnection())
                    {
                        connection.ConnectionString = connectionString;
                        connection.Open();
                    }
                }
                else
                {
                    if (mode == SchemaFactoryModeEnum.Create || mode == SchemaFactoryModeEnum.Create_And_Drop)
                    {
                        dbFileInfo.Delete();
                        using (DbConnection connection = factory.CreateConnection())
                        {
                            connection.ConnectionString = connectionString;
                            connection.Open();
                        }
                    }
                }
            }
        }
Exemple #5
0
        /// <summary>
        /// Ensures the database integrity.
        /// </summary>
        /// <param name="systemId">The system id.</param>
        /// <param name="descriptor">The descriptor.</param>
        /// <param name="mode">The mode.</param>
        /// <exception cref="InitializationException">MsSql2008 Manager has not been initialized.</exception>
        /// <exception cref="InvalidConfigurationException">Unable to connection information in NHibernate Descriptor settings.</exception>
        /// <exception cref="InvalidConfigurationValueException">Connection string is empty.
        /// or
        /// Connection string does not contains DATABASE nor DATA SOURCE definition.
        /// or
        /// Connection string does not contains PASSWORD definition.
        /// or
        /// Connection string does not contains information about the database name.</exception>
        public void EnsureDatabaseIntegrity(long systemId, Dictionary<string, string> descriptor, SchemaFactoryModeEnum mode)
        {
            if (!this.IsInitialized)
            {
                throw new InitializationException("MsSql2008 Manager has not been initialized.");
            }
            if (descriptor == null)
            {
                ThrowHelper.ThrowArgumentNullException("descriptor");
            }

            string connectionString = string.Empty;

            if (descriptor.ContainsKey(CONNECTION_STRING))
            {
                connectionString = descriptor[CONNECTION_STRING];
            }
            else if (descriptor.ContainsKey(CONNECTION_STRING_NAME))
            {
                connectionString = ConfigurationManager.ConnectionStrings[descriptor[CONNECTION_STRING_NAME]].ConnectionString;
            }
            else
            {
                throw new InvalidConfigurationException("Unable to connection information in NHibernate Descriptor settings.");
            }

            if (string.IsNullOrEmpty(connectionString))
            {
                throw new InvalidConfigurationValueException("Connection string is empty.");
            }

            Dictionary<string, string> data = ParseConnectionString(connectionString);
            if (!data.ContainsKey(INITIAL_CATALOG) && !data.ContainsKey(DATABASE))
            {
                throw new InvalidConfigurationValueException("Connection string does not contains DATABASE nor DATA SOURCE definition.");
            }

            string collation = string.Empty;
            string database = string.Empty;
            string password = string.Empty;
            string userId = string.Empty;
            if (data.ContainsKey(USER_ID))
            {
                userId = data[USER_ID];
                if (data.ContainsKey(PASSWORD))
                {
                    password = data[PASSWORD];
                }
                else
                {
                    throw new InvalidConfigurationValueException("Connection string does not contains PASSWORD definition.");
                }
            }
            else
            {
                // add current windows principal
                userId = string.Format(@"{0}\{1}", Environment.UserDomainName, Environment.UserName);
            }

            if (data.ContainsKey(DATABASE))
            {
                database = data[DATABASE];
            }
            else if (data.ContainsKey(INITIAL_CATALOG))
            {
                database = data[INITIAL_CATALOG];
            }
            else
            {
                throw new InvalidConfigurationValueException("Connection string does not contains information about the database name.");
            }

            if (descriptor.ContainsKey(DATABASE_COLLATION))
            {
                collation = descriptor[DATABASE_COLLATION];
            }

            using (SqlConnection connection = new SqlConnection(mConnectionStringForAdmin))
            {
                connection.Open();
                SqlCommand command = null;

                bool isExist = false;

                if (!string.IsNullOrEmpty(password))
                {
                    using (command = new SqlCommand(Resources.CheckLogin, connection))
                    {
                        command.CommandTimeout = mDefaultCommandTimeout;
                        command.Parameters.Add(new SqlParameter("@P0", System.Data.SqlDbType.VarChar) { Value = userId });
                        isExist = (int)command.ExecuteScalar() > 0;
                    }

                    if (!isExist)
                    {
                        // CREATE LOGIN {0} WITH PASSWORD = '******', CHECK_EXPIRATION = OFF, CHECK_POLICY = OFF;
                        using (command = new SqlCommand(string.Format(Resources.CreateLogin, userId, password), connection))
                        {
                            command.CommandTimeout = mDefaultCommandTimeout;
                            command.ExecuteNonQuery();
                        }
                    }
                }

                // SELECT COUNT(*) FROM master.dbo.sysdatabases db WHERE db.name = @P0
                using (command = new SqlCommand(string.Format(Resources.DatabaseCheck, database), connection))
                {
                    command.CommandTimeout = mDefaultCommandTimeout;
                    command.Parameters.Add(new SqlParameter("@P0", System.Data.SqlDbType.VarChar) { Value = database });
                    isExist = (int)command.ExecuteScalar() > 0;
                }

                if (!isExist)
                {
                    // CREATE DATABASE {0} [COLLATE collation_name]
                    string commandText = string.IsNullOrEmpty(collation) ? string.Format(Resources.CreateDatabase, database) : (string.Format("{0} COLLATE {1}", string.Format(Resources.CreateDatabase, database), collation));
                    using (command = new SqlCommand(commandText, connection))
                    {
                        command.CommandTimeout = mDefaultCommandTimeout;
                        command.ExecuteNonQuery();
                    }
                }
                else if (!string.IsNullOrEmpty(collation))
                {
                    // SELECT DATABASEPROPERTYEX('{0}', 'Collation') SQLCollation
                    bool isEqual = false;
                    using (command = new SqlCommand(string.Format(Resources.GetDatabaseCollation, database), connection))
                    {
                        command.CommandTimeout = mDefaultCommandTimeout;
                        isEqual = collation.Equals(command.ExecuteScalar());
                    }
                    if (!isEqual)
                    {
                        // ALTER DATABASE [{0}] COLLATE {1}
                        using (command = new SqlCommand(string.Format(Resources.AlterDatabaseCollation, database, collation), connection))
                        {
                            try
                            {
                                LOGGER.Info(string.Format("MSSQL2008MANAGER, trying to alter database '{0}' collation. If this transaction freeze, please other services and transaction which are possible keep lock on this database object.", database));
                                command.CommandTimeout = mDefaultCommandTimeout;
                                command.ExecuteNonQuery();
                                LOGGER.Info(string.Format("MSSQL2008MANAGER, database '{0}' collation successfully modified.", database));
                            }
                            catch (Exception ex)
                            {
                                LOGGER.Error(string.Format("MSSQL2008MANAGER, failed to alter database '{0}' collation to '{1}'.", database, collation), ex);
                            }
                        }
                    }
                }

                // ALTER AUTHORIZATION ON DATABASE::{0} TO [{1}]
                using (command = new SqlCommand(string.Format(Resources.SetDatabaseOwner, database, userId), connection))
                {
                    command.CommandTimeout = mDefaultCommandTimeout;
                    command.ExecuteNonQuery();
                }
            }
        }
        private static ISessionFactory CreateEntityManagerFactory(SchemaFactoryModeEnum mode, CategoryPropertyItem configItem)
        {
            CategoryPropertyItem item = ConfigurationAccessHelper.GetCategoryPropertyByPath(configItem.PropertyItems, "DatabaseManager");

            if (item != null && !string.IsNullOrEmpty(item.EntryValue))
            {
                Type databaseManagerType = null;
                try
                {
                    databaseManagerType = TypeHelper.GetTypeFromString(item.EntryValue);
                }
                catch (Exception ex)
                {
                    throw new InvalidConfigurationValueException(ex.Message, ex);
                }

                if (databaseManagerType != null)
                {
                    using (IDatabaseManager manager = (IDatabaseManager)databaseManagerType.GetConstructor(Type.EmptyTypes).Invoke(null))
                    {
                        manager.Initialize(item);
                        Dictionary <string, string> settings = new Dictionary <string, string>();
                        foreach (CategoryPropertyItem pi in ConfigurationAccessHelper.GetCategoryPropertyByPath(configItem.PropertyItems, "NHibernateSettings"))
                        {
                            settings[pi.Id] = pi.EntryValue;
                        }
                        manager.EnsureDatabaseIntegrity(SYSTEM_ID, settings, mode);
                    }
                }
            }

            string hbm2ddl = "hbm2ddl.auto";

            NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
            cfg.Properties.Clear();

            foreach (CategoryPropertyItem pi in ConfigurationAccessHelper.GetCategoryPropertyByPath(configItem.PropertyItems, "NHibernateSettings"))
            {
                if (!hbm2ddl.Equals(pi.Id.ToLower()))
                {
                    cfg.Properties[pi.Id] = pi.EntryValue;
                }
            }

            if (mode == SchemaFactoryModeEnum.Create)
            {
                cfg.Properties[hbm2ddl] = "create";
            }
            else if (mode == SchemaFactoryModeEnum.Create_And_Drop)
            {
                cfg.Properties[hbm2ddl] = "create-drop";
            }

            HbmSerializer serializer = new HbmSerializer();

            serializer.HbmAssembly      = typeof(PersistentStorageItem).Assembly.GetName().FullName;
            serializer.HbmAutoImport    = true;
            serializer.Validate         = true;
            serializer.WriteDateComment = false;
            serializer.HbmDefaultAccess = "field";

            cfg.AddInputStream(serializer.Serialize(typeof(PersistentStorageItem).Assembly));
            //cfg.Configure();

            if (mode == SchemaFactoryModeEnum.Validate)
            {
                SchemaValidator schemaValidator = new SchemaValidator(cfg);
                schemaValidator.Validate(); // validate the database schema
            }
            else if (mode == SchemaFactoryModeEnum.Update)
            {
                SchemaUpdate schemaUpdater = new SchemaUpdate(cfg); // try to update schema
                schemaUpdater.Execute(false, true);
                if (schemaUpdater.Exceptions.Count > 0)
                {
                    throw new Exception("FAILED TO UPDATE SCHEMA");
                }
            }

            return(cfg.BuildSessionFactory());
        }
Exemple #7
0
        /// <summary>
        /// Ensures the database integrity.
        /// </summary>
        /// <param name="systemId">The system id.</param>
        /// <param name="descriptor">The descriptor.</param>
        /// <param name="mode">The mode.</param>
        /// <exception cref="UnexpectedNHibernateConfigurationException">
        /// Unexpected dialect.
        /// or
        /// Unexpected connection driver.
        /// </exception>
        /// <exception cref="InvalidConfigurationException">
        /// Unable to find connection information in NHibernate Descriptor settings.
        /// or
        /// Unable to find data source in connection string.
        /// </exception>
        /// <exception cref="DatabaseVerificationErrorException"></exception>
        public virtual void EnsureDatabaseIntegrity(long systemId, Dictionary<string, string> descriptor, SchemaFactoryModeEnum mode)
        {
            if (descriptor == null)
            {
                ThrowHelper.ThrowArgumentNullException("descriptor");
            }

            if (descriptor.ContainsKey(DIALECT))
            {
                string dialect = descriptor[DIALECT];
                if (!dialect.StartsWith(DIALECT_EXPECTED_VALUE_BUILTIN) && !dialect.StartsWith(DIALECT_EXPECTED_VALUE_CUSTOM))
                {
                    throw new UnexpectedNHibernateConfigurationException("Unexpected dialect.");
                }
            }

            if (descriptor.ContainsKey(CONNECTION_DRIVER))
            {
                if (!CONNECTION_DRIVER_EXPECTED_VALUE.Equals(descriptor[CONNECTION_DRIVER]))
                {
                    throw new UnexpectedNHibernateConfigurationException("Unexpected connection driver.");
                }
            }

            FileInfo databaseFile = null;
            string connectionString = string.Empty;

            if (descriptor.ContainsKey(CONNECTION_STRING))
            {
                connectionString = descriptor[CONNECTION_STRING];
                databaseFile = GetDatabaseFile(connectionString);
            }
            else if (descriptor.ContainsKey(CONNECTION_STRING_NAME))
            {
                connectionString = ConfigurationManager.ConnectionStrings[descriptor[CONNECTION_STRING_NAME]].ConnectionString;
                databaseFile = GetDatabaseFile(connectionString);
            }
            else
            {
                throw new InvalidConfigurationException("Unable to find connection information in NHibernate Descriptor settings.");
            }

            if (databaseFile == null)
            {
                throw new InvalidConfigurationException("Unable to find data source or database file name in connection string.");
            }

            using (SqlCeEngine en = new SqlCeEngine(connectionString))
            {
                if (!databaseFile.Exists)
                {
                    en.CreateDatabase();
                }
                else
                {
                    if (mode == SchemaFactoryModeEnum.Create || mode == SchemaFactoryModeEnum.Create_And_Drop)
                    {
                        databaseFile.Delete();
                        en.CreateDatabase();
                    }
                    else
                    {
                        if (!en.Verify(VerifyOption.Enhanced))
                        {
                            throw new DatabaseVerificationErrorException();
                        }
                    }
                }
            }

        }