Пример #1
0
        /// <summary>
        /// 创建StatelessDbSession对象
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="dbDialectProvider">数据库特性对象提供程序</param>
        /// <param name="mappingXml">实体关系映射配置Xml文本</param>
        /// <returns>返回StatelessDbSession对象</returns>
        public virtual StatelessDbSession CreateStatelessDbSession(string connectionString, IDbDialectProvider dbDialectProvider, string mappingXml)
        {
            ISessionFactory sf = null;
            while (!sessionFactories.TryGetValue(connectionString, out sf))
            {
                IDictionary<string, string> dbSetting = new Dictionary<string, string>
                {
                    ["dialect"] = dbDialectProvider.DialectName,
                    ["connection.connection_string"] = connectionString,
                };
                CustomizeNHSessionFactory(dbSetting);
                var x = new NHibernate.Cfg.Configuration();
                x = x.AddProperties(dbSetting);
                //允许采用配置文件修改NHibernate配置
                var hc = ConfigurationManager.GetSection(CfgXmlHelper.CfgSectionName) as NHibernate.Cfg.IHibernateConfiguration;
                if ((hc != null && hc.SessionFactory != null) || File.Exists(GetDefaultConfigurationFilePath()))
                {
                    x = x.Configure();
                }
                if (System.Transactions.Transaction.Current != null)
                {
                    //如果在分布式事务范围内,就将连接释放模式更改为on_close模式,防止auto模式下,重新获取连接,导致分布式事务升级
                    x.AddProperties(new Dictionary<string, string> {["connection.release_mode"] = "on_close" });
                }
                //添加实体关系映射
                if (!string.IsNullOrWhiteSpace(mappingXml))
                {
                    x.AddXml(mappingXml);
                }

                sf = x.BuildSessionFactory();
                sessionFactories.TryAdd(connectionString, sf);
            }
            return new StatelessDbSession(sf, connectionString);
        }
        public static void Configure()
        {
            // Configure log4net
            XmlConfigurator.Configure();

            // Configure container
            CurrentContainer.Container = new WindsorObjectBuilder();
            CurrentContainer.Container.RegisterSingleton <IContainer>(CurrentContainer.Container);
            CurrentContainer.Container.Configure <ContainerControllerFactory>(ComponentInstanciationPolicy.Singleton);
            // add repositories to container
            foreach (Type rep in from t in typeof(Student).Assembly.GetTypes()
                     where t.ImplementsGenericDefinition(typeof(NHibernateRepository <>))
                     select t)
            {
                CurrentContainer.Container.Configure(rep, ComponentInstanciationPolicy.Singleton);
            }
            // add controllers to container
            foreach (Type ctl in from t in Assembly.GetExecutingAssembly().GetTypes()
                     where typeof(IController).IsAssignableFrom(t)
                     select t)
            {
                CurrentContainer.Container.Configure(ctl, ComponentInstanciationPolicy.NewInstance);
            }

            // Configure NHibernate
            var nhibernateCfg = new NHibernate.Cfg.Configuration();

            nhibernateCfg.AddProperties(new Dictionary <string, string>()
            {
                { NHibernate.Cfg.Environment.Dialect, "NHibernate.Dialect.MsSql2005Dialect" },
                { NHibernate.Cfg.Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider" },
                { NHibernate.Cfg.Environment.ConnectionDriver, "NHibernate.Driver.SqlClientDriver" },
                { NHibernate.Cfg.Environment.ConnectionString, "Data Source=localhost\\SQLEXPRESS;Database=DDDPart1;Integrated Security=SSPI;" },
                { NHibernate.Cfg.Environment.QueryTranslator, "NHibernate.Hql.Classic.ClassicQueryTranslatorFactory" },
                { NHibernate.Cfg.Environment.Isolation, "ReadCommitted" },
                { NHibernate.Cfg.Environment.DefaultSchema, "dbo" },
                { NHibernate.Cfg.Environment.ProxyFactoryFactoryClass, "NHibernate.ByteCode.Spring.ProxyFactoryFactory, NHibernate.ByteCode.Spring" },
                { NHibernate.Cfg.Environment.CurrentSessionContextClass, "NHibernate.Context.WebSessionContext" },
            });
            nhibernateCfg.AddAssembly("Domain");
            nhibernateCfg.AddAssembly("Infrastructure.Impl");

            CreateSchema(nhibernateCfg);

            var sessionFactory     = nhibernateCfg.BuildSessionFactory();
            var persistenceManager = new NHibernatePersistenceManager(sessionFactory);

            CurrentContainer.Container.RegisterSingleton <NHibernatePersistenceManager>(persistenceManager);

            // Configure ASP.Net MVC controller factory
            ControllerBuilder.Current.SetControllerFactory(CurrentContainer.Container.Build <ContainerControllerFactory>());
        }
Пример #3
0
        /// <summary>
        /// Static constructor
        /// Inintializes default settings
        /// </summary>
        static Settings()
        {
            _connectionString = "";
            _isDebug = false;

            Configuration cfg = new Configuration();
            IDictionary section = ConfigurationManager.GetSection(NhibernateSectionName) as IDictionary;
            if (section == null)
            {
                throw new NHibernateSectionLoadException();
            }
            cfg.AddProperties(section);
            cfg.AddAssembly(typeof(Settings).Assembly);

            _sessionFactory = cfg.BuildSessionFactory();
        }
Пример #4
0
        public static ISessionFactory GetSessionFactory()
        {
            if (sessionFactorySingleton == null)
            {
                var connectionString = GetConnectionString(ConfigurationManager.AppSettings["Import.ConnectionString"]);

                var properties = new Dictionary <string, string>
                {
                    { "connection.driver_class", "NHibernate.Driver.SqlClientDriver" },
                    { "dialect", "NHibernate.Dialect.MsSql2005Dialect" },
                    { "connection.provider", "NHibernate.Connection.DriverConnectionProvider" },
                    { "connection.connection_string", connectionString },
                };

                var configuration = new NHibernate.Cfg.Configuration();
                configuration.AddProperties(properties);
                configuration.AddAssembly(Assembly.GetExecutingAssembly());

                sessionFactorySingleton = configuration.BuildSessionFactory();
            }

            return(sessionFactorySingleton);
        }
Пример #5
0
        public static ISessionFactory GetSessionFactory()
        {
            if (sessionFactorySingleton == null)
            {
                var connectionString = GetConnectionString(ConfigurationManager.AppSettings["Import.ConnectionString"]);

                var properties = new Dictionary<string, string>
                {
                    { "connection.driver_class", "NHibernate.Driver.SqlClientDriver" },
                    { "dialect", "NHibernate.Dialect.MsSql2005Dialect" },
                    { "connection.provider", "NHibernate.Connection.DriverConnectionProvider" },
                    { "connection.connection_string", connectionString },
                };

                var configuration = new NHibernate.Cfg.Configuration();
                configuration.AddProperties(properties);
                configuration.AddAssembly(Assembly.GetExecutingAssembly());

                sessionFactorySingleton = configuration.BuildSessionFactory();
            }

            return sessionFactorySingleton;
        }
        public static void Configure()
        {
            // Configure log4net
            XmlConfigurator.Configure();

            // Configure container
            CurrentContainer.Container = new WindsorObjectBuilder();
            CurrentContainer.Container.RegisterSingleton<IContainer>(CurrentContainer.Container);
            CurrentContainer.Container.Configure<ContainerControllerFactory>(ComponentInstanciationPolicy.Singleton);
            CurrentContainer.Container.Configure<ContainerCommandBus>(ComponentInstanciationPolicy.Singleton);
            CurrentContainer.Container.Configure<ContainerEventBus>(ComponentInstanciationPolicy.Singleton);
            CurrentContainer.Container.Configure<WebContext>(ComponentInstanciationPolicy.Singleton);
            // add repositories to container for each type of aggregate roots
            foreach (Type agg in from t in typeof(Student).Assembly.GetTypes()
                                 where typeof(IAggregateRoot).IsAssignableFrom(t)
                                 select t)
            {
                var rep = typeof(NHibernateRepository<>).MakeGenericType(agg);
                CurrentContainer.Container.Configure(rep, ComponentInstanciationPolicy.Singleton);
            }
            // add DTO queries
            foreach (Type queries in from t in typeof(StudentDTO).Assembly.GetTypes()
                                     where typeof(DTOQueries).IsAssignableFrom(t)
                                     select t)
            {
                CurrentContainer.Container.Configure(queries, ComponentInstanciationPolicy.Singleton);
            }
            // add command handlers
            foreach (Type handlers in from t in typeof(CreateClassCommandHandler).Assembly.GetTypes()
                                      where t.ImplementsGenericDefinition(typeof(IHandleCommand<>))
                                      select t)
            {
                CurrentContainer.Container.Configure(handlers, ComponentInstanciationPolicy.Singleton);
            }
            // add event handlers
            foreach (Type handlers in from t in typeof(ClassCreatedEventHandler).Assembly.GetTypes()
                                      where t.ImplementsGenericDefinition(typeof(IHandleEvent<>))
                                      select t)
            {
                CurrentContainer.Container.Configure(handlers, ComponentInstanciationPolicy.Singleton);
            }
            // add controllers to container
            foreach (Type ctl in from t in Assembly.GetExecutingAssembly().GetTypes()
                                 where typeof(IController).IsAssignableFrom(t)
                                 select t)
            {
                CurrentContainer.Container.Configure(ctl, ComponentInstanciationPolicy.NewInstance);
            }

            // Configure aggregate roots
            AggregateRoot.CreateDelegatesForAggregatesIn(typeof(Student).Assembly);

            // Configure NHibernate
            var nhibernateCfg = new NHibernate.Cfg.Configuration();
            nhibernateCfg.AddProperties(new Dictionary<string, string>()
            {
                {NHibernate.Cfg.Environment.Dialect, "NHibernate.Dialect.MsSql2005Dialect"},
                {NHibernate.Cfg.Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider"},
                {NHibernate.Cfg.Environment.ConnectionDriver, "NHibernate.Driver.SqlClientDriver"},
                {NHibernate.Cfg.Environment.ConnectionString, "Data Source=localhost\\SQLEXPRESS;Database=DDDPart5;Integrated Security=SSPI;"},
                {NHibernate.Cfg.Environment.QueryTranslator, "NHibernate.Hql.Classic.ClassicQueryTranslatorFactory"},
                {NHibernate.Cfg.Environment.Isolation, "ReadCommitted"},
                {NHibernate.Cfg.Environment.DefaultSchema, "dbo"},
                {NHibernate.Cfg.Environment.ProxyFactoryFactoryClass, "NHibernate.ByteCode.Spring.ProxyFactoryFactory, NHibernate.ByteCode.Spring"},
                {NHibernate.Cfg.Environment.CurrentSessionContextClass, "NHibernate.Context.WebSessionContext"},
                {NHibernate.Cfg.Environment.UseProxyValidator, "false"},
            });
            nhibernateCfg.AddAssembly("Domain");
            nhibernateCfg.AddAssembly("Infrastructure.Impl");

            if (ConfigurationManager.AppSettings["ReCreateSchemaAtStartup"] == "true")
            {
                ReCreateSchema(nhibernateCfg);
            }

            var sessionFactory = nhibernateCfg.BuildSessionFactory();
            var persistenceManager = new NHibernatePersistenceManager(sessionFactory,
                CurrentContainer.Container.Build<IContext>(),
                CurrentContainer.Container.Build<IEventBus>());
            CurrentContainer.Container.RegisterSingleton<NHibernatePersistenceManager>(persistenceManager);

            // Configure ASP.Net MVC controller factory
            ControllerBuilder.Current.SetControllerFactory(CurrentContainer.Container.Build<ContainerControllerFactory>());
        }
        public NHibernate.Cfg.Configuration GetConfigurationFrom(string configName, string connectionString)
        {
            if (string.IsNullOrEmpty(configName))
            {
                throw new ArgumentNullException("参数:配置名称不能为空");
            }

            NHibernate.Cfg.Configuration retValue = null;

            retValue = CheckConfiguration(configName, connectionString);

            if (null == retValue)
            {
                lock (m_locker)
                {
                    retValue = CheckConfiguration(configName, connectionString);

                    if (null == retValue)
                    {
                        string fileFullPath = GetSafeFilePath(configName);
                        retValue = new NHibernate.Cfg.Configuration();
                        retValue.Configure(fileFullPath);

                        if (!string.IsNullOrEmpty(connectionString))
                        {
                            if (!retValue.Properties.ContainsKey("connection.connection_string"))
                            {
                                retValue.AddProperties(
                                    new Dictionary<string, string>() { { "connection.connection_string", connectionString } });
                            }
                            else
                            {
                                retValue.Properties["connection.connection_string"] = connectionString;
                            }

                            m_Configurations.Add(configName + ":" + connectionString, retValue);
                        }
                        else
                        {
                            m_Configurations.Add(configName, retValue);
                        }
                    }
                }
            }

            return retValue;
        }
Пример #8
0
        public DatabaseDictionary GetDatabaseSchema(string connString, string dbProvider)
        {
            dbProvider = dbProvider.ToUpper();
            string parsedConnStr = ParseConnectionString(connString, dbProvider);

            DatabaseDictionary          dbDictionary = new DatabaseDictionary();
            Dictionary <string, string> properties   = new Dictionary <string, string>();
            string metadataQuery = string.Empty;

            dbDictionary.connectionString = parsedConnStr;
            dbDictionary.tables           = new System.Collections.Generic.List <Table>();

            properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
            properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
            properties.Add("connection.connection_string", parsedConnStr);

            if (dbProvider.Contains("MSSQL"))
            {
                metadataQuery =
                    "select t1.table_name, t1.column_name, t1.data_type, t2.max_length, t2.is_identity, t2.is_nullable, t5.constraint_type " +
                    "from information_schema.columns t1 " +
                    "inner join sys.columns t2 on t2.name = t1.column_name " +
                    "inner join sys.tables t3 on t3.name = t1.table_name and t3.object_id = t2.object_id " +
                    "left join information_schema.key_column_usage t4 on t4.table_name = t1.table_name and t4.column_name = t1.column_name " +
                    "left join information_schema.table_constraints t5 on t5.constraint_name = t4.constraint_name " +
                    "order by t1.table_name, t5.constraint_type, t1.column_name";
                properties.Add("connection.driver_class", "NHibernate.Driver.SqlClientDriver");

                switch (dbProvider)
                {
                case "MSSQL2008":
                    dbDictionary.provider = Provider.MsSql2008;
                    properties.Add("dialect", "NHibernate.Dialect.MsSql2008Dialect");
                    break;

                case "MSSQL2005":
                    dbDictionary.provider = Provider.MsSql2005;
                    properties.Add("dialect", "NHibernate.Dialect.MsSql2005Dialect");
                    break;

                case "MSSQL2000":
                    dbDictionary.provider = Provider.MsSql2000;
                    properties.Add("dialect", "NHibernate.Dialect.MsSql2000Dialect");
                    break;

                default:
                    throw new Exception("Database provider not supported.");
                }
            }
            else if (dbProvider.Contains("ORACLE"))
            {
                metadataQuery =
                    "select t1.object_name, t2.column_name, t2.data_type, t2.data_length, 0 as is_sequence, t2.nullable, t4.constraint_type " +
                    "from user_objects t1 " +
                    "inner join all_tab_cols t2 on t2.table_name = t1.object_name " +
                    "left join all_cons_columns t3 on t3.table_name = t2.table_name and t3.column_name = t2.column_name " +
                    "left join all_constraints t4 on t4.constraint_name = t3.constraint_name and (t4.constraint_type = 'P' or t4.constraint_type = 'R') " +
                    "where t1.object_type = 'TABLE' order by t1.object_name, t4.constraint_type, t2.column_name";
                properties.Add("connection.driver_class", "NHibernate.Driver.OracleClientDriver");

                switch (dbProvider)
                {
                case "ORACLE10G":
                    dbDictionary.provider = Provider.Oracle10g;
                    properties.Add("dialect", "NHibernate.Dialect.Oracle10gDialect");
                    break;

                case "ORACLE9I":
                    dbDictionary.provider = Provider.Oracle9i;
                    properties.Add("dialect", "NHibernate.Dialect.Oracle9iDialect");
                    break;

                case "ORACLE8I":
                    dbDictionary.provider = Provider.Oracle8i;
                    properties.Add("dialect", "NHibernate.Dialect.Oracle8iDialect");
                    break;

                case "ORACLELITE":
                    dbDictionary.provider = Provider.OracleLite;
                    properties.Add("dialect", "NHibernate.Dialect.OracleLiteDialect");
                    break;

                default:
                    throw new Exception("Database provider not supported.");
                }
            }
            else if (dbProvider.Contains("MYSQL"))
            {
                metadataQuery = "SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE,CHARACTER_MAXIMUM_LENGTH, COLUMN_KEY, IS_NULLABLE " +
                                "FROM INFORMATION_SCHEMA.COLUMNS " +
                                string.Format("WHERE TABLE_SCHEMA = '{0}'", connString.Split(';')[1].Split('=')[1]);
                properties.Add("connection.driver_class", "NHibernate.Driver.MySqlDataDriver");

                switch (dbProvider)
                {
                case "MYSQL3":
                    dbDictionary.provider = Provider.MySql3;
                    properties.Add("dialect", "NHibernate.Dialect.MySQLDialect");
                    break;

                case "MYSQL4":
                    dbDictionary.provider = Provider.MySql4;
                    properties.Add("dialect", "NHibernate.Dialect.MySQLDialect");
                    break;

                case "MYSQL5":
                    dbDictionary.provider = Provider.MySql5;
                    properties.Add("dialect", "NHibernate.Dialect.MySQL5Dialect");
                    break;
                }
            }


            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.AddProperties(properties);

            ISessionFactory  sessionFactory = config.BuildSessionFactory();
            ISession         session        = sessionFactory.OpenSession();
            ISQLQuery        query          = session.CreateSQLQuery(metadataQuery);
            IList <object[]> metadataList   = query.List <object[]>();

            session.Close();

            Table  table         = null;
            string prevTableName = String.Empty;

            foreach (object[] metadata in metadataList)
            {
                string tableName  = Convert.ToString(metadata[0]);
                string columnName = Convert.ToString(metadata[1]);
                string dataType   = Utility.SqlTypeToCSharpType(Convert.ToString(metadata[2]));
                int    dataLength = Convert.ToInt32(metadata[3]);
                bool   isIdentity = Convert.ToBoolean(metadata[4]);
                string nullable   = Convert.ToString(metadata[5]).ToUpper();
                bool   isNullable = (nullable == "Y" || nullable == "TRUE");
                string constraint = Convert.ToString(metadata[6]);

                if (tableName != prevTableName)
                {
                    table = new Table()
                    {
                        tableName    = tableName,
                        columns      = new List <Column>(),
                        keys         = new List <Key>(),
                        associations = new List <Association>(), // to be supported in the future
                        entityName   = Utility.NameSafe(tableName)
                    };

                    dbDictionary.tables.Add(table);
                    prevTableName = tableName;
                }

                if (String.IsNullOrEmpty(constraint)) // process columns
                {
                    Column column = new Column()
                    {
                        columnName = columnName,
                        columnType = (ColumnType)Enum.Parse(typeof(ColumnType), dataType),
                        // dataType = (DataType)Enum.Parse(typeof(DataType), dataType),
                        dataLength   = dataLength,
                        isNullable   = isNullable,
                        propertyName = Utility.NameSafe(columnName)
                    };

                    table.columns.Add(column);
                }
                else // process keys
                {
                    KeyType keyType = KeyType.assigned;

                    if (isIdentity)
                    {
                        keyType = KeyType.identity;
                    }
                    else if (constraint.ToUpper() == "FOREIGN KEY" || constraint.ToUpper() == "R")
                    {
                        keyType = KeyType.foreign;
                    }

                    Key key = new Key()
                    {
                        columnName = columnName,
                        columnType = (ColumnType)Enum.Parse(typeof(ColumnType), dataType),
                        //   dataType = (DataType)Enum.Parse(typeof(DataType), dataType),
                        dataLength   = dataLength,
                        isNullable   = isNullable,
                        keyType      = keyType,
                        propertyName = Utility.NameSafe(columnName),
                    };

                    table.keys.Add(key);
                }
            }
            return(dbDictionary);
        }
Пример #9
0
        static void DoCreate(string connStr, string dbProvider, string dbDictionaryFilePath)
        {
            Console.WriteLine("Creating database dictionary...");

            dbProvider = dbProvider.ToUpper();
            string parsedConnStr = ParseConnectionString(connStr, dbProvider);

            DatabaseDictionary dbDictionary = new DatabaseDictionary();

            dbDictionary.connectionString = parsedConnStr;
            dbDictionary.dataObjects      = new List <DataObject>();

            string metadataQuery = String.Empty;
            Dictionary <string, string> properties = new Dictionary <string, string>();

            properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
            properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
            properties.Add("connection.connection_string", parsedConnStr);

            if (dbProvider.Contains("MSSQL"))
            {
                metadataQuery =
                    "select t1.table_name, t1.column_name, t1.data_type, t2.max_length, t2.is_identity, t2.is_nullable, t5.constraint_type " +
                    "from information_schema.columns t1 " +
                    "inner join sys.columns t2 on t2.name = t1.column_name " +
                    "inner join sys.tables t3 on t3.name = t1.table_name and t3.object_id = t2.object_id " +
                    "left join information_schema.key_column_usage t4 on t4.table_name = t1.table_name and t4.column_name = t1.column_name " +
                    "left join information_schema.table_constraints t5 on t5.constraint_name = t4.constraint_name " +
                    "order by t1.table_name, t5.constraint_type, t1.column_name";
                properties.Add("connection.driver_class", "NHibernate.Driver.SqlClientDriver");

                switch (dbProvider)
                {
                case "MSSQL2008":
                    dbDictionary.provider = Provider.MsSql2008;
                    properties.Add("dialect", "NHibernate.Dialect.MsSql2008Dialect");
                    break;

                case "MSSQL2005":
                    dbDictionary.provider = Provider.MsSql2005;
                    properties.Add("dialect", "NHibernate.Dialect.MsSql2005Dialect");
                    break;

                case "MSSQL2000":
                    dbDictionary.provider = Provider.MsSql2000;
                    properties.Add("dialect", "NHibernate.Dialect.MsSql2000Dialect");
                    break;

                default:
                    throw new Exception("Database provider not supported.");
                }
            }
            else if (dbProvider.Contains("ORACLE"))
            {
                metadataQuery =
                    "select t1.object_name, t2.column_name, t2.data_type, t2.data_length, 0 as is_sequence, t2.nullable, t4.constraint_type " +
                    "from user_objects t1 " +
                    "inner join all_tab_cols t2 on t2.table_name = t1.object_name " +
                    "left join all_cons_columns t3 on t3.table_name = t2.table_name and t3.column_name = t2.column_name " +
                    "left join all_constraints t4 on t4.constraint_name = t3.constraint_name and (t4.constraint_type = 'P' or t4.constraint_type = 'R') " +
                    "where t1.object_type = 'TABLE' order by t1.object_name, t4.constraint_type, t2.column_name";
                properties.Add("connection.driver_class", "NHibernate.Driver.OracleClientDriver");

                switch (dbProvider)
                {
                case "ORACLE10G":
                    dbDictionary.provider = Provider.Oracle10g;
                    properties.Add("dialect", "NHibernate.Dialect.Oracle10gDialect");
                    break;

                case "ORACLE9I":
                    dbDictionary.provider = Provider.Oracle9i;
                    properties.Add("dialect", "NHibernate.Dialect.Oracle9iDialect");
                    break;

                case "ORACLE8I":
                    dbDictionary.provider = Provider.Oracle8i;
                    properties.Add("dialect", "NHibernate.Dialect.Oracle8iDialect");
                    break;

                case "ORACLELITE":
                    dbDictionary.provider = Provider.OracleLite;
                    properties.Add("dialect", "NHibernate.Dialect.OracleLiteDialect");
                    break;

                default:
                    throw new Exception("Database provider not supported.");
                }
            }

            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.AddProperties(properties);

            ISessionFactory  sessionFactory = config.BuildSessionFactory();
            ISession         session        = sessionFactory.OpenSession();
            ISQLQuery        query          = session.CreateSQLQuery(metadataQuery);
            IList <object[]> metadataList   = query.List <object[]>();

            session.Close();

            DataObject dataObject    = null;
            string     prevTableName = String.Empty;

            foreach (object[] metadata in metadataList)
            {
                string tableName  = Convert.ToString(metadata[0]);
                string columnName = Convert.ToString(metadata[1]);
                string dataType   = Utility.SqlTypeToCSharpType(Convert.ToString(metadata[2]));
                int    dataLength = Convert.ToInt32(metadata[3]);
                bool   isIdentity = Convert.ToBoolean(metadata[4]);
                string nullable   = Convert.ToString(metadata[5]).ToUpper();
                bool   isNullable = (nullable == "Y" || nullable == "TRUE");
                string constraint = Convert.ToString(metadata[6]);

                if (tableName != prevTableName)
                {
                    dataObject = new DataObject()
                    {
                        tableName         = tableName,
                        objectName        = Utility.NameSafe(tableName),
                        keyProperties     = new List <KeyProperty>(),
                        dataProperties    = new List <DataProperty>(),
                        dataRelationships = new List <DataRelationship>(),
                    };

                    dbDictionary.dataObjects.Add(dataObject);
                    prevTableName = tableName;
                }

                if (String.IsNullOrEmpty(constraint)) // process columns
                {
                    DataProperty dataProperty = new DataProperty()
                    {
                        columnName   = columnName,
                        propertyName = Utility.NameSafe(columnName),
                        dataType     = (DataType)Enum.Parse(typeof(DataType), dataType),
                        dataLength   = dataLength,
                        isNullable   = isNullable,
                    };

                    dataObject.dataProperties.Add(dataProperty);
                }
                else // process keys
                {
                    KeyType keyType = KeyType.assigned;

                    if (isIdentity)
                    {
                        keyType = KeyType.identity;
                    }
                    else if (constraint.ToUpper() == "FOREIGN KEY" || constraint.ToUpper() == "R")
                    {
                        keyType = KeyType.foreign;
                    }

                    DataProperty keyProperty = new DataProperty()
                    {
                        columnName   = columnName,
                        propertyName = Utility.NameSafe(columnName),
                        dataType     = (DataType)Enum.Parse(typeof(DataType), dataType),
                        dataLength   = dataLength,
                        isNullable   = isNullable,
                        keyType      = keyType,
                    };

                    dataObject.addKeyProperty(keyProperty);
                }
            }

            Utility.Write <DatabaseDictionary>(dbDictionary, dbDictionaryFilePath);
            Console.WriteLine("Database dictionary created successfully.");
            Console.WriteLine("See result file at \"" + dbDictionaryFilePath + "\"");
        }
Пример #10
0
        public void Init(string connectionStringName = "local", bool debug = false, string database = "")
        {
            //ilmerge
            //если сборки объединены то логика определения системы протоколирование не работает
            //нужно вручную настроить ее
            LoggerProvider.SetLoggersFactory(new Log4NetLoggerFactory());

            var mappingDialect       = new MySQL5Dialect();
            var mapper               = new ConventionModelMapper();
            var baseInspector        = new SimpleModelInspector();
            var simpleModelInspector = ((SimpleModelInspector)mapper.ModelInspector);

            simpleModelInspector.IsPersistentProperty((m, declared) => {
                return(((IModelInspector)baseInspector).IsPersistentProperty(m) &&
                       m.GetCustomAttributes(typeof(IgnoreAttribute), false).Length == 0);
            });
            simpleModelInspector.IsRootEntity((type, declared) => {
                var modelInspector = ((IModelInspector)simpleModelInspector);
                return(declared || (type.IsClass && type.BaseType != null
                                    //если наследуемся от класса который не маплен то это простое наследование
                                    && (typeof(object) == type.BaseType || !modelInspector.IsEntity(type.BaseType)) ||
                                    type.BaseType == typeof(BaseStatelessObject)) &&
                       modelInspector.IsEntity(type));
            });

            Index <Waybill>(w => w.WriteTime);
            Index <WaybillLine>(w => w.ProductId);
            Index <WaybillLine>(w => w.ProducerId);
            Index <WaybillLine>(w => w.Product);
            Index <WaybillLine>(w => w.SerialNumber);
            Index <WaybillLine>(w => w.RejectId);
            Index <WaybillLine>(w => w.EAN13);
            Index <Reject>(w => w.ProductId);
            Index <Reject>(w => w.ProducerId);
            Index <Reject>(w => w.Product);
            Index <Reject>(w => w.Series);
            Index <Offer>(o => o.ProductId);
            Index <Offer>(o => o.CatalogId);
            //индекс для восстановления заявок
            Index <Offer>(o => o.ProductSynonymId);
            Index <Offer>(o => o.PriceId);
            Index <Offer>(o => o.Id.RegionId);
            Index <SentOrder>(o => o.SentOn);
            Index <SentOrder>(o => o.ServerId);
            Index <DeletedOrder>(o => o.DeletedOn);
            Index <DeletedOrder>(o => o.ServerId);
            Index <MinCost>(r => r.Diff);
            Index <Catalog>(r => r.Name);
            Index <Drug>(r => r.EAN);
            Index <BarCode>(r => r.Value);
            Index <BarcodeProducts>(x => x.Barcode);

            mapper.Class <Drug>(x => x.Id(y => y.DrugId));
            mapper.Class <Settings>(m => {
                m.Bag(o => o.Markups, c => {
                    c.Inverse(true);
                    c.Cascade(Cascade.DeleteOrphans | Cascade.All);
                });
                m.Bag(o => o.PriceTags, c => {
                    c.Inverse(true);
                    c.Cascade(Cascade.DeleteOrphans | Cascade.All);
                });
                m.Bag(o => o.Waybills, c => c.Cascade(Cascade.DeleteOrphans | Cascade.All));
                m.Property(x => x.ClientTokenV2, c => c.Length(10000));
            });
            mapper.Class <MarkupConfig>(m => {
                m.Property(o => o.Begin, om => om.Access(Accessor.Field));
                m.Property(o => o.End, om => om.Access(Accessor.Field));
            });
            mapper.Class <PriceTagSettings>(o => {
                o.Id(r => r.Id);
            });
            mapper.Class <PriceTag>(m => {
                m.Bag(o => o.Items, c => {
                    c.Inverse(true);
                    c.Cascade(Cascade.DeleteOrphans | Cascade.All);
                });
            });
            mapper.Class <PriceTagItem>(o => {
                o.Id(r => r.Id);
            });
            mapper.Class <MinOrderSumRule>(m => {
                m.ComposedId(c => {
                    c.ManyToOne(p => p.Address);
                    c.ManyToOne(p => p.Price, t => t.Columns(cm => cm.Name("PriceId"), cm => cm.Name("RegionId")));
                });
                m.Property(p => p.MinOrderSum);
            });
            mapper.Class <Limit>(m => {
                m.ComposedId(c => {
                    c.ManyToOne(p => p.Address);
                    c.ManyToOne(p => p.Price, t => t.Columns(cm => cm.Name("PriceId"), cm => cm.Name("RegionId")));
                });
                m.Property(p => p.Value);
            });
            mapper.Class <WaybillOrder>(m => {
                m.ComposedId(c => {
                    c.Property(p => p.OrderLineId);
                    c.Property(p => p.DocumentLineId);
                });
            });

            mapper.Class <Promotion>(m => {
                m.Bag(o => o.Catalogs, c => {
                    c.Table("PromotionCatalogs");
                    c.Key(km => km.Column("PromotionId"));
                }, cm => {
                    cm.ManyToMany(km => km.Column("CatalogId"));
                });
            });

            mapper.Class <ProducerPromotion>(m => {
                m.Bag(o => o.Catalogs, c => {
                    c.Table("ProducerPromotionCatalogs");
                    c.Key(km => km.Column("PromotionId"));
                }, cm => {
                    cm.ManyToMany(km => km.Column("CatalogId"));
                });
            });

            mapper.Class <ProducerPromotion>(m => {
                m.Bag(o => o.Suppliers, c => {
                    c.Table("ProducerPromotionSuppliers");
                    c.Key(km => km.Column("PromotionId"));
                }, cm => {
                    cm.ManyToMany(km => km.Column("SupplierId"));
                });
            });

            mapper.Class <Price>(m => {
                m.ComponentAsId(c => c.Id);
                m.Property(p => p.ContactInfo, c => c.Length(10000));
                m.Property(p => p.OperativeInfo, c => c.Length(10000));
                m.Property(p => p.RegionId, c => c.Insert(false));
                m.Version(p => p.Timestamp, c => {
                    c.Type(new TimestampType());
                    c.Column(cc => cc.Default("'0001-01-01 00:00:00'"));
                });
            });
            mapper.Class <Check>(m => {
                m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq"));
            });

            mapper.Class <Mail>(m => {
                m.Property(p => p.Subject, c => c.Length(10000));
                m.Property(p => p.Body, c => c.Length(10000));
            });

            mapper.Class <Order>(m => {
                m.Property(o => o.Frozen, om => om.Access(Accessor.Field));
                m.ManyToOne(o => o.MinOrderSum, c => {
                    c.Columns(cm => cm.Name("AddressId"), cm => cm.Name("PriceId"), cm => cm.Name("RegionId"));
                    c.Insert(false);
                    c.Update(false);
                });
                m.ManyToOne(o => o.Limit, c => {
                    c.Columns(cm => cm.Name("AddressId"), cm => cm.Name("PriceId"), cm => cm.Name("RegionId"));
                    c.Insert(false);
                    c.Update(false);
                });
                m.Bag(o => o.Lines, c => {
                    c.Cascade(Cascade.DeleteOrphans | Cascade.All);
                    c.Inverse(true);
                });
            });
            mapper.Class <Waybill>(m => {
                //при миграции могут если поставщик отсутствует nhibernate будет перезаписывать
                m.ManyToOne(x => x.Address, x => x.Update(false));
                m.ManyToOne(x => x.Supplier, x => x.Update(false));
                m.Bag(o => o.Lines, c => {
                    c.Cascade(Cascade.DeleteOrphans | Cascade.All);
                    c.Inverse(true);
                });
            });
            mapper.Class <WaybillLine>(m => {
                m.Property(l => l.RetailCost, p => p.Access(Accessor.Field));
                m.Property(l => l.RetailMarkup, p => p.Access(Accessor.Field));
                m.Property(l => l.RealRetailMarkup, p => p.Access(Accessor.Field));
                m.Property(l => l.MaxRetailMarkup, p => p.Access(Accessor.Field));
                m.Bag(l => l.CertificateFiles, c => {
                    c.Cascade(Cascade.DeleteOrphans | Cascade.All);
                });
            });
            mapper.Class <Address>(m => m.Bag(o => o.Orders, c => {
                c.Cascade(Cascade.All | Cascade.DeleteOrphans);
                c.Inverse(true);
            }));
            mapper.Class <InventoryDoc>(m => {
                m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq"));
                m.Bag(o => o.Lines, c => {
                    c.Cascade(Cascade.All | Cascade.DeleteOrphans);
                });
            });
            mapper.Class <InventoryLine>(m => {
                m.ManyToOne(x => x.Stock, p => p.Cascade(Cascade.Refresh));
            });
            mapper.Class <UnpackingDoc>(m => {
                m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq"));
                //m.Bag(o => o.Lines, c => {
                //c.Cascade(Cascade.All | Cascade.DeleteOrphans);
                //});
            });
            mapper.Class <UnpackingLine>(m => {
                m.ManyToOne(x => x.DstStock, p => p.Cascade(Cascade.All));
                m.ManyToOne(x => x.SrcStock, p => p.Cascade(Cascade.All));
            });

            mapper.Class <WriteoffDoc>(m => {
                m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq"));
                m.Bag(o => o.Lines, c => {
                    c.Cascade(Cascade.All | Cascade.DeleteOrphans);
                });
            });
            mapper.Class <ReturnDoc>(m => {
                m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq"));
                m.Bag(o => o.Lines, c => {
                    c.Cascade(Cascade.All | Cascade.DeleteOrphans);
                });
            });
            mapper.Class <DisplacementDoc>(m => {
                m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq"));
                m.Bag(o => o.Lines, c => {
                    c.Cascade(Cascade.All | Cascade.DeleteOrphans);
                });
            });
            mapper.Class <DisplacementLine>(m => {
                m.ManyToOne(x => x.SrcStock, p => p.Cascade(Cascade.Refresh));
                m.ManyToOne(x => x.DstStock, p => p.Cascade(Cascade.All));
            });
            mapper.Class <ReassessmentDoc>(m => {
                m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq"));
                m.Bag(o => o.Lines, c => {
                    c.Cascade(Cascade.All | Cascade.DeleteOrphans);
                });
            });
            mapper.Class <ReassessmentLine>(m => m.ManyToOne(x => x.DstStock, p => p.Cascade(Cascade.All)));

            mapper.Class <Offer>(m => {
                m.ManyToOne(o => o.Price, c => {
                    c.Insert(false);
                    c.Update(false);
                });
                m.ManyToOne(o => o.LeaderPrice,
                            c => c.Columns(cm => cm.Name("LeaderPriceId"),
                                           cm => cm.Name("LeaderRegionId")));
            });
            mapper.Class <OrderLine>(m => {
                m.Property(l => l.RetailMarkup, p => p.Access(Accessor.Field));
                m.Property(l => l.RetailCost, p => p.Access(Accessor.Field));
            });
            mapper.Class <SentOrder>(m => {
                m.Bag(o => o.Lines, c => {
                    c.Key(k => k.Column("OrderId"));
                    c.Cascade(Cascade.DeleteOrphans | Cascade.All);
                    c.Inverse(true);
                });
            });
            mapper.Class <DeletedOrder>(m => {
                m.Bag(o => o.Lines, c => {
                    c.Key(k => k.Column("OrderId"));
                    c.Cascade(Cascade.DeleteOrphans | Cascade.All);
                    c.Inverse(true);
                });
            });
            mapper.Class <Mail>(m => {
                m.Bag(o => o.Attachments, c => {
                    c.Cascade(Cascade.DeleteOrphans | Cascade.All);
                });
            });
            mapper.Class <BatchLine>(m => {
                m.Property(l => l.Comment, c => c.Length(10000));
                m.Property(l => l.ServiceFields, c => c.Length(10000));
            });
            mapper.Class <AwaitedItem>(i => {
                i.ManyToOne(l => l.Catalog, c => c.Index("Catalog"));
                i.ManyToOne(l => l.Producer, c => c.Index("Producer"));
            });

            mapper.Class <Stock>(m => {
                m.Property(x => x.ServerId, p => p.UniqueKey("ServerIdUniq"));
                m.Property(x => x.RetailCost, p => p.Access(Accessor.Field));
                m.Property(x => x.RetailMarkup, p => p.Access(Accessor.Field));
            });

            mapper.BeforeMapClass += (inspector, type, customizer) => {
                customizer.Id(m => m.Generator(Generators.Native));
                if (type == typeof(RegulatorRegistry))
                {
                    customizer.Table("RegulatorRegistry");
                }
            };
            mapper.BeforeMapProperty += (inspector, member, customizer) => {
                var propertyInfo = ((PropertyInfo)member.LocalMember);
                var propertyType = propertyInfo.PropertyType;
                if (member.GetContainerEntity(inspector) == typeof(ProductDescription))
                {
                    if (propertyType == typeof(string))
                    {
                        customizer.Length(10000);
                    }
                }

                if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
                {
                    customizer.Type <UtcToLocalDateTimeType>();
                }

                if (propertyType.IsValueType && !propertyType.IsNullable())
                {
                    customizer.Column(c => c.Default(GetDefaultValue(propertyInfo, mappingDialect)));
                    customizer.NotNullable(true);
                }

                if (indexes.Any(m => m.MetadataToken == propertyInfo.MetadataToken && m.Module == propertyInfo.Module))
                {
                    customizer.Index(propertyInfo.Name);
                }
            };
            mapper.BeforeMapManyToMany += (inspector, member, customizer) => {
                //myisam не поддерживает внешние ключи
                customizer.ForeignKey("none");
            };
            mapper.BeforeMapBag += (inspector, member, customizer) => {
                customizer.Key(k => {
                    k.Column(member.GetContainerEntity(inspector).Name + "Id");
                    //myisam не поддерживает внешние ключи
                    k.ForeignKey("none");
                });
            };
            mapper.BeforeMapManyToOne += (inspector, member, customizer) => {
                var propertyInfo = ((PropertyInfo)member.LocalMember);
                if (propertyInfo.PropertyType == typeof(Price))
                {
                    customizer.Columns(cm => cm.Name("PriceId"), cm => cm.Name("RegionId"));
                }
                else
                {
                    customizer.Column(member.LocalMember.Name + "Id");
                    if (indexes.Contains(propertyInfo))
                    {
                        customizer.Column(m => m.Index(member.LocalMember.Name + "Id"));
                    }
                }
                customizer.NotFound(NotFoundMode.Ignore);
                //myisam не поддерживает внешние ключи
                customizer.ForeignKey("none");
            };
            var assembly = typeof(Offer).Assembly;
            var types    = assembly.GetTypes()
                           .Where(t => t.Namespace != null && t.Namespace.StartsWith("AnalitF.Net.Client.Models"))
                           .Where(t => !t.IsAbstract && !t.IsInterface && t.GetProperty("Id") != null ||
                                  t == typeof(MinOrderSumRule) ||
                                  t == typeof(WaybillOrder) ||
                                  t == typeof(Limit) ||
                                  t == typeof(Drug));
            var mapping = mapper.CompileMappingFor(types);

            PatchComponentColumnName(mapping);

            MappingHash = mapping.AsString().GetHashCode();

            if (debug)
            {
                Console.WriteLine("MappingHash = {0}", MappingHash);
                Console.WriteLine(mapping.AsString());
            }

            var connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
            var driver           = "NHibernate.Driver.MySqlDataDriver";
            var dialect          = typeof(DevartMySqlDialect).AssemblyQualifiedName;

            if (connectionString.Contains("Embedded=True"))
            {
                connectionString = FixRelativePaths(connectionString, database);
                driver           = typeof(DevartDriver).AssemblyQualifiedName;
            }

            Configuration = new Configuration();
            Configuration.AddProperties(new Dictionary <string, string> {
                { Environment.Dialect, dialect },
                { Environment.ConnectionDriver, driver },
                { Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider" },
                { Environment.ConnectionString, connectionString },
                { Environment.Hbm2ddlKeyWords, "none" },
#if DEBUG
                //если нужно отладить запросы хибера
                //для запросов в AddAwaited падает
                //{Environment.FormatSql, "true"},
#endif
                { Environment.ProxyFactoryFactoryClass, typeof(ProxyFactoryFactory).AssemblyQualifiedName },
            });
            Configuration.SetNamingStrategy(new PluralizeNamingStrategy());
            Configuration.AddDeserializedMapping(mapping, assembly.GetName().Name);
            Factory = Configuration.BuildSessionFactory();
        }
 public NHibernate.Cfg.Configuration ConfigureProperties(NHibernate.Cfg.Configuration nhibernateConfig)
 {
     nhibernateConfig.AddProperties(_databaseSettings.GetProperties());
     return(nhibernateConfig);
 }
Пример #12
0
        private ISession GetNHSession(string dbProvider, string dbServer, string dbInstance, string dbName, string dbSchema,
                                      string dbUserName, string dbPassword, string portNumber, string serName)
        {
            string connStr, defaultConnStr = "";

            if (portNumber == "")
            {
                if (dbProvider.ToUpper().Contains("ORACLE"))
                {
                    portNumber = "1521";
                }
                else if (dbProvider.ToUpper().Contains("MYSQL"))
                {
                    portNumber = "3306";
                }
            }

            if (dbProvider.ToUpper().Contains("MSSQL"))
            {
                if (dbInstance == "default" || dbInstance == "")
                {
                    string mssqlInstanceName = getMssqlInstanceName();
                    connStr = String.Format("Data Source={0};Initial Catalog={2};User ID={3};Password={4}",
                                            dbServer, dbInstance, dbName, dbUserName, dbPassword);
                    defaultConnStr = String.Format("Data Source={0}\\{1};Initial Catalog={2};User ID={3};Password={4}",
                                                   dbServer, mssqlInstanceName, dbName, dbUserName, dbPassword);
                }
                else
                {
                    connStr = String.Format("Data Source={0}\\{1};Initial Catalog={2};User ID={3};Password={4}",
                                            dbServer, dbInstance, dbName, dbUserName, dbPassword);
                }
            }
            else
            {
                connStr = String.Format("Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST={0})(PORT={1})))(CONNECT_DATA=(SERVER=DEDICATED)({2}={3})));User ID={4};Password={5}",
                                        dbServer, portNumber, serName, dbInstance, dbUserName, dbPassword);
            }

            Dictionary <string, string> properties = new Dictionary <string, string>();

            properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
            properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
            properties.Add("connection.connection_string", connStr);
            properties.Add("connection.driver_class", GetConnectionDriver(dbProvider));
            properties.Add("dialect", GetDatabaseDialect(dbProvider));
            NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
            config.AddProperties(properties);
            ISessionFactory sessionFactory;

            try
            {
                sessionFactory = config.BuildSessionFactory();
            }
            catch (Exception e)
            {
                if (defaultConnStr != "")
                {
                    config.Properties["connection.connection_string"] = defaultConnStr;
                    sessionFactory = config.BuildSessionFactory();
                }
                else
                {
                    throw e;
                }
            }
            return(sessionFactory.OpenSession());
        }
Пример #13
0
        public DataObject GetSchemaObjectSchema(string projectName, string applicationName, string schemaObjectName)
        {
            List <string>      tableNames   = new List <string>();
            DatabaseDictionary dbDictionary = new DatabaseDictionary();
            string             connStrProp  = "connection.connection_string";

            DataObject dataObject = new DataObject
            {
                tableName         = schemaObjectName,
                dataProperties    = new List <DataProperty>(),
                keyProperties     = new List <KeyProperty>(),
                dataRelationships = new List <DataRelationship>(),
                objectNamespace   = String.Format("org.iringtools.adapter.datalayer.proj_{0}.{1}", projectName, applicationName),
                objectName        = Utility.ToSafeName(schemaObjectName)
            };

            try
            {
                InitializeScope(projectName, applicationName);

                string keyFile = string.Format("{0}{1}.{2}.key",
                                               _settings["AppDataPath"], _settings["ProjectName"], _settings["ApplicationName"]);

                if (File.Exists(_settings["DBDictionaryPath"]))
                {
                    dbDictionary = NHibernateUtility.LoadDatabaseDictionary(_settings["DBDictionaryPath"], keyFile);
                }

                string connString    = dbDictionary.ConnectionString;
                string dbProvider    = dbDictionary.Provider.ToString().ToUpper();
                string schemaName    = dbDictionary.SchemaName;
                string parsedConnStr = ParseConnectionString(connString, dbProvider);

                Dictionary <string, string> properties = new Dictionary <string, string>();

                dbDictionary.ConnectionString = parsedConnStr;
                dbDictionary.dataObjects      = new System.Collections.Generic.List <DataObject>();

                properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
                properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
                properties.Add(connStrProp, parsedConnStr);
                properties.Add("connection.driver_class", GetConnectionDriver(dbProvider));
                properties.Add("dialect", GetDatabaseDialect(dbProvider));

                NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();
                config.AddProperties(properties);
                ISessionFactory sessionFactory = null;

                try
                {
                    sessionFactory = config.BuildSessionFactory();
                }
                catch (Exception e)
                {
                    if (dbProvider.ToLower().Contains("mssql"))
                    {
                        config.Properties[connStrProp] = getProcessedConnectionString(parsedConnStr);
                        sessionFactory = config.BuildSessionFactory();
                    }
                    else
                    {
                        throw e;
                    }
                }

                ISession         session      = sessionFactory.OpenSession();
                ISQLQuery        query        = session.CreateSQLQuery(GetTableMetaQuery(dbProvider, schemaName, schemaObjectName));
                IList <object[]> metadataList = query.List <object[]>();
                session.Close();

                foreach (object[] metadata in metadataList)
                {
                    bool   isIdentity = Convert.ToBoolean(metadata[3]);
                    string constraint = Convert.ToString(metadata[5]);
                    if (String.IsNullOrEmpty(constraint)) // process columns
                    {
                        DataProperty column = NewColumnInformation(metadata);
                        dataObject.dataProperties.Add(column);
                    }
                    else
                    {
                        KeyType keyType = KeyType.assigned;

                        if (isIdentity)
                        {
                            keyType = KeyType.identity;
                        }
                        else if (constraint.ToUpper() == "FOREIGN KEY" || constraint.ToUpper() == "R")
                        {
                            keyType = KeyType.foreign;
                        }
                        DataProperty key = new DataProperty();
                        key         = NewColumnInformation(metadata);
                        key.keyType = keyType;
                        dataObject.addKeyProperty(key);
                    }
                }
                return(dataObject);
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Error in GetSchemaObjectSchema: {0}", ex));
                return(dataObject);
            }
        }
Пример #14
0
        public DataObjects GetSchemaObjects(string projectName, string applicationName)
        {
            DataObjects        tableNames     = new DataObjects();
            DatabaseDictionary dbDictionary   = new DatabaseDictionary();
            ISessionFactory    sessionFactory = null;

            try
            {
                _logger.Debug(String.Format("In GetSchemaObjects({0}, {1})", projectName, applicationName));

                InitializeScope(projectName, applicationName);

                string keyFile = string.Format("{0}{1}.{2}.key",
                                               _settings["AppDataPath"], _settings["ProjectName"], _settings["ApplicationName"]);

                if (File.Exists(_settings["DBDictionaryPath"]))
                {
                    dbDictionary = NHibernateUtility.LoadDatabaseDictionary(_settings["DBDictionaryPath"], keyFile);
                }
                else
                {
                    return(tableNames);
                }

                string connString    = dbDictionary.ConnectionString;
                string dbProvider    = dbDictionary.Provider.ToString().ToUpper();
                string schemaName    = dbDictionary.SchemaName;
                string parsedConnStr = ParseConnectionString(connString, dbProvider);
                string connStrProp   = "connection.connection_string";

                _logger.DebugFormat("ConnectString: {0} \r\n Provider: {1} \r\n SchemaName: {2} \r\n Parsed: {3}",
                                    connString,
                                    dbProvider,
                                    schemaName,
                                    parsedConnStr);

                Dictionary <string, string> properties = new Dictionary <string, string>();

                dbDictionary.ConnectionString = parsedConnStr;
                dbDictionary.dataObjects      = new System.Collections.Generic.List <DataObject>();

                properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
                properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
                properties.Add(connStrProp, parsedConnStr);

                string connDriver = GetConnectionDriver(dbProvider);

                _logger.DebugFormat("connection.driver_class: {0}", connDriver);

                properties.Add("connection.driver_class", connDriver);

                string databaseDialect = GetConnectionDriver(dbProvider);

                _logger.DebugFormat("dialect: {0}", databaseDialect);

                properties.Add("dialect", databaseDialect);

                NHibernate.Cfg.Configuration config = new NHibernate.Cfg.Configuration();

                _logger.Debug("Adding Properties to Config");

                config.AddProperties(properties);

                _logger.Debug("Building Session Factory");

                try
                {
                    sessionFactory = config.BuildSessionFactory();
                }
                catch (Exception e)
                {
                    if (dbProvider.ToLower().Contains("mssql"))
                    {
                        config.Properties[connStrProp] = getProcessedConnectionString(parsedConnStr);
                        sessionFactory = config.BuildSessionFactory();
                    }
                    else
                    {
                        throw e;
                    }
                }

                _logger.Debug("About to Open Session");

                ISession session = sessionFactory.OpenSession();

                _logger.Debug("Session Open");

                string sql = GetDatabaseMetaquery(dbProvider, parsedConnStr.Split(';')[1].Split('=')[1], schemaName);

                _logger.DebugFormat("SQL: {0}",
                                    sql);

                ISQLQuery query = session.CreateSQLQuery(sql);

                DataObjects metadataList = new DataObjects();
                foreach (string tableName in query.List <string>())
                {
                    metadataList.Add(tableName);
                }
                session.Close();

                tableNames = metadataList;
                return(tableNames);
            }
            catch (Exception ex)
            {
                _logger.ErrorFormat("Error while Getting Schema Objects from database. {0}",
                                    ex.ToString());

                return(tableNames);
            }
        }
Пример #15
0
        public static void Configure()
        {
            // Configure log4net
            XmlConfigurator.Configure();

            // Configure container
            CurrentContainer.Container = new WindsorObjectBuilder();
            CurrentContainer.Container.RegisterSingleton <IContainer>(CurrentContainer.Container);
            CurrentContainer.Container.Configure <ContainerControllerFactory>(ComponentInstanciationPolicy.Singleton);
            CurrentContainer.Container.Configure <ContainerCommandBus>(ComponentInstanciationPolicy.Singleton);
            CurrentContainer.Container.Configure <ContainerEventBus>(ComponentInstanciationPolicy.Singleton);
            CurrentContainer.Container.Configure <WebContext>(ComponentInstanciationPolicy.Singleton);
            // add repositories to container for each type of aggregate roots
            foreach (Type agg in from t in typeof(Student).Assembly.GetTypes()
                     where typeof(IAggregateRoot).IsAssignableFrom(t)
                     select t)
            {
                var rep = typeof(NHibernateRepository <>).MakeGenericType(agg);
                CurrentContainer.Container.Configure(rep, ComponentInstanciationPolicy.Singleton);
            }
            // add DTO queries
            foreach (Type queries in from t in typeof(StudentDTO).Assembly.GetTypes()
                     where typeof(DTOQueries).IsAssignableFrom(t)
                     select t)
            {
                CurrentContainer.Container.Configure(queries, ComponentInstanciationPolicy.Singleton);
            }
            // add command handlers
            foreach (Type handlers in from t in typeof(CreateClassCommandHandler).Assembly.GetTypes()
                     where t.ImplementsGenericDefinition(typeof(IHandleCommand <>))
                     select t)
            {
                CurrentContainer.Container.Configure(handlers, ComponentInstanciationPolicy.Singleton);
            }
            // add event handlers
            foreach (Type handlers in from t in typeof(ClassCreatedEventHandler).Assembly.GetTypes()
                     where t.ImplementsGenericDefinition(typeof(IHandleEvent <>))
                     select t)
            {
                CurrentContainer.Container.Configure(handlers, ComponentInstanciationPolicy.Singleton);
            }
            // add controllers to container
            foreach (Type ctl in from t in Assembly.GetExecutingAssembly().GetTypes()
                     where typeof(IController).IsAssignableFrom(t)
                     select t)
            {
                CurrentContainer.Container.Configure(ctl, ComponentInstanciationPolicy.NewInstance);
            }

            // Configure aggregate roots
            AggregateRoot.CreateDelegatesForAggregatesIn(typeof(Student).Assembly);

            // Configure NHibernate
            var nhibernateCfg = new NHibernate.Cfg.Configuration();

            nhibernateCfg.AddProperties(new Dictionary <string, string>()
            {
                { NHibernate.Cfg.Environment.Dialect, "NHibernate.Dialect.MsSql2005Dialect" },
                { NHibernate.Cfg.Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider" },
                { NHibernate.Cfg.Environment.ConnectionDriver, "NHibernate.Driver.SqlClientDriver" },
                { NHibernate.Cfg.Environment.ConnectionString, "Data Source=localhost\\SQLEXPRESS;Database=DDDPart5;Integrated Security=SSPI;" },
                { NHibernate.Cfg.Environment.QueryTranslator, "NHibernate.Hql.Classic.ClassicQueryTranslatorFactory" },
                { NHibernate.Cfg.Environment.Isolation, "ReadCommitted" },
                { NHibernate.Cfg.Environment.DefaultSchema, "dbo" },
                { NHibernate.Cfg.Environment.ProxyFactoryFactoryClass, "NHibernate.ByteCode.Spring.ProxyFactoryFactory, NHibernate.ByteCode.Spring" },
                { NHibernate.Cfg.Environment.CurrentSessionContextClass, "NHibernate.Context.WebSessionContext" },
                { NHibernate.Cfg.Environment.UseProxyValidator, "false" },
            });
            nhibernateCfg.AddAssembly("Domain");
            nhibernateCfg.AddAssembly("Infrastructure.Impl");

            if (ConfigurationManager.AppSettings["ReCreateSchemaAtStartup"] == "true")
            {
                ReCreateSchema(nhibernateCfg);
            }

            var sessionFactory     = nhibernateCfg.BuildSessionFactory();
            var persistenceManager = new NHibernatePersistenceManager(sessionFactory,
                                                                      CurrentContainer.Container.Build <IContext>(),
                                                                      CurrentContainer.Container.Build <IEventBus>());

            CurrentContainer.Container.RegisterSingleton <NHibernatePersistenceManager>(persistenceManager);

            // Configure ASP.Net MVC controller factory
            ControllerBuilder.Current.SetControllerFactory(CurrentContainer.Container.Build <ContainerControllerFactory>());
        }