Ejemplo n.º 1
0
        public ConnectionManager(IRootPathProvider rootPathProvider)
        {
            this.factory = DbProviderFactories.GetFactory("System.Data.SQLite");
            this.databaseName = Path.Combine(rootPathProvider.GetRootPath(), "data.db");

            CreateDatabase();
        }
Ejemplo n.º 2
0
        public AdoResponseCache(DbProviderFactory factory, string connectionString)
        {
            _factory = factory;
            _connectionString = connectionString;

            EnsureTableExists();
        }
Ejemplo n.º 3
0
        private int LastInsertedId()
        {
            string lib = GetProviderFactoryLib(providerName);

            System.Data.Common.DbProviderFactory provider = RegisterProvider(providerName);
            DbConnection con = provider.CreateConnection();

            con.ConnectionString = BuildConnectionString(providerName, this.dbName);
            DbCommand com = provider.CreateCommand();

            com.CommandTimeout = 30;
            com.Connection     = con;
            com.CommandText    = LastInsertIdCommand(providerName);
            com.CommandType    = CommandType.Text;
            int lastId = 0;

            try
            {
                con.Open();
                com.Prepare();
                lastId = Convert.ToInt32(com.ExecuteScalar());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            con.Close();
            return(lastId);
        }
Ejemplo n.º 4
0
 private System.Data.Common.DbProviderFactory RegisterProvider(string providerName)
 {
     System.Data.Common.DbProviderFactory f = null;
     if (this.providerName == ProviderFactoryType.MySql.ToString())
     {
         using (var dt = new DataTable())
         {
             dt.Columns.Add("Name");
             dt.Columns.Add("Description");
             dt.Columns.Add("InvariantName");
             dt.Columns.Add("AssemblyQualifiedName");
             dt.Rows.Add("ADO.Net driver for MySQL",
                         "mysql more",
                         "mysqlClient",
                         "MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.7.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d");
             f = DbProviderFactories.GetFactory(dt.Rows[0]);
         }
     }
     if (this.providerName == ProviderFactoryType.SQLServer.ToString())
     {
         using (var dt = new DataTable())
         {
             dt.Columns.Add("Name");
             dt.Columns.Add("Description");
             dt.Columns.Add("InvariantName");
             dt.Columns.Add("AssemblyQualifiedName");
             dt.Rows.Add("SqlClient Data Provider",
                         "SqlClient Data Provider",
                         "System.Data.SqlClient",
                         "System.Data.SqlClient.SqlClientFactory, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089");
             f = DbProviderFactories.GetFactory(dt.Rows[0]);
         }
     }
     return(f);
 }
Ejemplo n.º 5
0
		public static bool CheckMembershipSchemaVersion (DbProviderFactory factory, string connStr, string feature, string compatibleVersion)
		{
			using (DbConnection connection = CreateConnection (factory, connStr)) {
				DbCommand command = factory.CreateCommand ();
				command.Connection = connection;
				command.CommandText = @"aspnet_CheckSchemaVersion";
				command.CommandType = CommandType.StoredProcedure;

				AddParameter (factory, command, "@Feature", ParameterDirection.Input, feature);
				AddParameter (factory, command, "@CompatibleSchemaVersion", ParameterDirection.Input, compatibleVersion);
				DbParameter returnValue = AddParameter (factory, command, "@ReturnVal", ParameterDirection.ReturnValue, null);

				try {
					command.ExecuteNonQuery ();
				}
				catch (Exception) {
					throw new ProviderException ("ASP.NET Membership schema not installed.");
				}

				if ((int) (returnValue.Value ?? -1) == 0)
					return true;

				return false;
			}
		}
Ejemplo n.º 6
0
        internal static DbProviderServices GetProviderServices(DbProviderFactory factory)
        {
            EDesignUtil.CheckArgumentNull(factory, "factory");

            // Special case SQL client so that it will work with System.Data from .NET 4.0 even without
            // a binding redirect.
            if (factory is SqlClientFactory)
            {
                return SqlProviderServices.Instance;
            }

            IServiceProvider serviceProvider = factory as IServiceProvider;
            if (serviceProvider == null)
            {
                throw MetadataUtil.ProviderIncompatible(System.Data.Entity.Design.Strings.EntityClient_DoesNotImplementIServiceProvider(
                    factory.GetType().ToString()));
            }

            DbProviderServices providerServices = serviceProvider.GetService(typeof(DbProviderServices)) as DbProviderServices;
            if (providerServices == null)
            {
                throw MetadataUtil.ProviderIncompatible(
                    System.Data.Entity.Design.Strings.EntityClient_ReturnedNullOnProviderMethod(
                        "GetService",
                        factory.GetType().ToString()));
            }
            return providerServices;
        }
Ejemplo n.º 7
0
        private void Initialize(string connectionStringName)
        {
            connectionStringName = string.IsNullOrEmpty(connectionStringName) ? "default" : connectionStringName;

            ConnectionConfig info = SimpleDALConfig.GetConnectionConfig(connectionStringName);
            
            _ConnectionString = info.ConnectionString;

            _Schema = SimpleDALConfig.GetSchemaService(info.ProviderName);

            _IsCustomToken = info.IsCustomToken;

            _Factory = DbProviderFactories.GetFactory(info.ProviderName);

            _ParamToken = _Schema.ParameterToken;

            _Connection = CreateConnection();

            _DalLogger = SimpleDALConfig.GetLogService(info.LoggerName);

            _IsLoggable = info.IsDebug;

            _SessionID = Guid.NewGuid().ToString();

            Info("New Create SimpleDB");
            Debug("Connection Name is: " + connectionStringName);
            Debug("Provider is " + info.ProviderName);
        }
Ejemplo n.º 8
0
 public DataAccess(DbProviderFactory factory, string connectionString, string provider, int? commandTimeout)
 {
     _factory = factory;
     _provider = provider;
     _commandTimeout = commandTimeout;
     _connection = GetConnection(connectionString);
 }
Ejemplo n.º 9
0
 public DbBase(ConnObject co)
 {
     this.connObject = co;
     this.conn = co.Master.Conn;
     this.providerName = co.Master.ProviderName;
     dalType = co.Master.ConnDalType;
     _fac = GetFactory(providerName);
     _con = _fac.CreateConnection();
     _con.ConnectionString = DalCreate.FormatConn(dalType, conn);
     _com = _con.CreateCommand();
     if (_com != null)//Txt| Xml 时返回Null
     {
         _com.Connection = _con;
         _com.CommandTimeout = AppConfig.DB.CommandTimeout;
     }
     if (IsAllowRecordSql)//开启秒表计算
     {
         _watch = new Stopwatch();
     }
     //if (AppConfig.DB.LockOnDbExe && dalType == DalType.Access)
     //{
     //    string dbName = DataBase;
     //    if (!_dbOperator.ContainsKey(dbName))
     //    {
     //        try
     //        {
     //            _dbOperator.Add(dbName, false);
     //        }
     //        catch
     //        {
     //        }
     //    }
     //}
     //_com.CommandTimeout = 1;
 }
Ejemplo n.º 10
0
        internal static EntityCommandDefinition CreateCommandDefinition(DbProviderFactory storeProviderFactory, DbCommandTree commandTree)
        {
            DebugCheck.NotNull(storeProviderFactory);
            DebugCheck.NotNull(commandTree);

            return new EntityCommandDefinition(storeProviderFactory, commandTree);
        }
Ejemplo n.º 11
0
 private DbConfiguration(string providerName, string connectionString, DbProviderFactory dbProviderFactory)
 {
     this.providerName = providerName;
     this.connectionString = connectionString;
     this.dbProviderFactory = dbProviderFactory;
     this.dbDriver = currentDbDrivers[providerName];
 }
Ejemplo n.º 12
0
    public void SetConfiguration()
    {
        try
        {
            string ConnectionStringName = ConfigurationManager.ConnectionStrings["InmoCon"].ConnectionString;
            if (ConnectionStringName == "")
            {
                strProvider = "";
                strConnectionString = "";
            }
            else
            {
                strProvider = ConfigurationManager.ConnectionStrings["InmoCon"].ProviderName;
                strConnectionString = ConfigurationManager.ConnectionStrings["InmoCon"].ConnectionString;
            }
            if (dbFactory != null)
            {
                dbFactory = null;
            }
            if (strProvider != "")
            {
                dbFactory = DbProviderFactories.GetFactory(strProvider);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }

    }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DatabaseManager"/> class.
 /// </summary>
 /// <param name="connectionProvider">The connection provider.</param>
 /// <param name="providerName">Name of the provider.</param>
 public DatabaseManager(DbProvider provider, string connectionString)
 {
     string providerName = provider.GetEnumMemberValue();
     this.connectionProvider = DbProviderFactories.GetFactory(providerName);
     this.providerName = providerName;
     this.connectionString = connectionString;
 }
 // SchemaReader.ReadSchema
 public override Tables ReadSchema(DbConnection connection, DbProviderFactory factory)
 {
     var result=new Tables();	
     this._connection=connection;
     this._factory=factory;
     var cmd=this._factory.CreateCommand();        
     cmd.Connection=connection;
     cmd.CommandText=TABLE_SQL;
     //cmd.GetType().GetProperty("BindByName").SetValue(cmd, true, null);
     //pull the tables in a reader
     using(cmd)
     {
         using (var rdr=cmd.ExecuteReader())
         {
             while(rdr.Read())
             {
                 Table tbl=new Table();
                 tbl.Name=rdr["name"].ToString();
                 tbl.Schema = "";
                 tbl.IsView=String.Compare(rdr["type"].ToString(), "view", true)==0;
                 tbl.CleanName=CleanUp(tbl.Name);
                 tbl.ClassName=Inflector.MakeSingular(tbl.CleanName);
                 tbl.SQL = rdr["sql"].ToString();
                 result.Add(tbl);
             }
         }
     }
     foreach (var tbl in result)
     {
         tbl.Columns=this.LoadColumns(tbl);
         tbl.Indexes = this.LoadIndices(tbl.Name);
         tbl.ForeignKeys = this.LoadForeignKeys(tbl.Name);
     }
     return result;
 }
Ejemplo n.º 15
0
        /*
         * Method to get a database connection from the server or local embedded database.
         * built on generic ADO.Net
         */
        public static DbConnection GetUasAdoConnection()
        {
            DbConnection dbConn = null;

            try
            {
                System.Configuration.ConnectionStringSettings connectionString = new System.Configuration.ConnectionStringSettings();
                if (SessionHelper.IsVentureMode)
                {
                    connectionString = DataContext.getUASEntitiesAdoVenture();
                }
                else
                {
                    connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[DataContext.GetUasConnectionStringName()];
                }

                // Loads the factory
                System.Data.Common.DbProviderFactory factory = System.Data.Common.DbProviderFactories.GetFactory(connectionString.ProviderName);

                dbConn = factory.CreateConnection();
                dbConn.ConnectionString = connectionString.ConnectionString;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("* * *  GetUasAdoConnection: " + ex.Message);
                //  GetProviderFactoryClasses();
            }

            return(dbConn);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Create a dynamic model
        /// </summary>
        /// <param name="connectionStringName">the connection string name or the connection stirng itself</param>
        /// <param name="tableName">the table name</param>
        /// <param name="primaryKeyField">the primary key field name</param>
        public DynamicModel(string connectionStringName, string tableName = "", string primaryKeyField = "")
        {
            TableName = string.IsNullOrEmpty(tableName) ? GetType().Name : tableName;
            PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;

            try
            {
                _factory = DbProviderFactories.GetFactory(ProviderName);
            }
            catch (FileLoadException ex)
            {
                throw new MassiveException(string.Format("Could not load the specified provider: {0}. Have you added a reference to the correct assembly?", ProviderName), ex);
            }
            catch (ArgumentException e)
            {
                var foundClasses = "I did find these Factories:";
                var dt = DbProviderFactories.GetFactoryClasses();
                for (var i = 0; i < dt.Rows.Count; i++)
                    foundClasses += String.Format("|{0}|", dt.Rows[i][2]);

                throw new ArgumentException(String.Format("{0}{1}{2}", e.Message, Environment.NewLine, foundClasses));

            }

            var conString = ConfigurationManager.ConnectionStrings[connectionStringName];
            _connectionString = conString != null ? conString.ConnectionString : connectionStringName;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:DbProvider"/> class.
        /// </summary>
        /// <param name="connStr">The conn STR.</param>
        /// <param name="dbProviderFactory">The db provider factory.</param>
        protected DbProvider(string connStr, System.Data.Common.DbProviderFactory dbProviderFactory)
        {
            dbConnStrBuilder = new DbConnectionStringBuilder();
            dbConnStrBuilder.ConnectionString = connStr;

            this.dbProviderFactory = dbProviderFactory;
        }
 public IDbConnection GetConnection(string connectionString, string provider)
 {
     System.Data.Common.DbProviderFactory factory = System.Data.Common.DbProviderFactories.GetFactory(provider);
     System.Data.Common.DbConnection      conn    = factory.CreateConnection();
     conn.ConnectionString = connectionString;
     return(conn);
 }
Ejemplo n.º 19
0
Archivo: DAL.cs Proyecto: morimizu/repo
        private static SDC.DbCommand BuildCommand(string sproc, List <ParamStruct> list)
        {
            SDC.DbProviderFactory factory = SDC.DbProviderFactories.GetFactory(Properties.Settings.Default.provider);

            SDC.DbCommand comm = factory.CreateCommand();

            comm.CommandText = sproc;
            comm.CommandType = System.Data.CommandType.StoredProcedure;


            SDC.DbParameter param = factory.CreateParameter();


            foreach (ParamStruct item in list)
            {
                param.ParameterName = item.paramId;
                param.Value         = item.paramValue;
                param.DbType        = item.paramType;
                param.Size          = item.paramLength;
                param.Direction     = item.paramDirection;
                comm.Parameters.Add(param);
                param = factory.CreateParameter();
            }

            return(comm);
        }
 /// <summary>Instancia a DbFactory "setando a string de conexao"
 /// </summary>
 public DAOFactory(string connectionStringValue, string provider)
 {
     AppSettingsReader apps = new AppSettingsReader();
     objProvider = DbProviderFactories.GetFactory(provider);
     connectionString = connectionStringValue;
     objConn = objProvider.CreateConnection();
 }
Ejemplo n.º 21
0
        public int CreateDatabase(String queryString)
        {
            string lib = GetProviderFactoryLib(providerName);

            System.Data.Common.DbProviderFactory provider = RegisterProvider(providerName);
            DbConnection con = provider.CreateConnection();

            con.ConnectionString = BuildConnectionString(providerName, "");
            int rowsAffected = 0;

            try
            {
                con.Open();
                DbCommand com = provider.CreateCommand();
                com.CommandTimeout = 30;
                com.Connection     = con;
                com.CommandText    = queryString;
                com.CommandType    = CommandType.Text;
                object result = com.ExecuteNonQuery();
                if (result != null)
                {
                    rowsAffected = Convert.ToInt32(result);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            con.Close();
            return(rowsAffected);
        }
Ejemplo n.º 22
0
        private static async Task<IEnumerable<Fortune>> LoadRows(string connectionString, DbProviderFactory dbProviderFactory)
        {
            var result = new List<Fortune>();

            using (var db = dbProviderFactory.CreateConnection())
            using (var cmd = db.CreateCommand())
            {
                cmd.CommandText = "SELECT [Id], [Message] FROM [Fortune]";

                db.ConnectionString = connectionString;
                await db.OpenAsync();

                using (var rdr = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection))
                {
                    while (await rdr.ReadAsync())
                    {
                        result.Add(new Fortune
                        {
                            Id = rdr.GetInt32(0),
                            Message = rdr.GetString(1)
                        });
                    }
                }
            }

            result.Add(new Fortune { Message = "Additional fortune added at request time." });
            result.Sort();

            return result;
        }
Ejemplo n.º 23
0
        private static async Task<World> LoadRow(string connectionString, DbProviderFactory dbProviderFactory)
        {
            using (var db = dbProviderFactory.CreateConnection())
            using (var cmd = db.CreateCommand())
            {
                cmd.CommandText = "SELECT [Id], [RandomNumber] FROM [World] WHERE [Id] = @Id";
                var id = cmd.CreateParameter();
                id.ParameterName = "@Id";
                id.DbType = DbType.Int32;
                id.Value = _random.Next(1, 10001);
                cmd.Parameters.Add(id);

                db.ConnectionString = connectionString;
                await db.OpenAsync();

                using (var rdr = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection))
                {
                    await rdr.ReadAsync();

                    return new World
                    {
                        Id = rdr.GetInt32(0),
                        RandomNumber = rdr.GetInt32(1)
                    };
                }
            }
        }
Ejemplo n.º 24
0
 private FindByUserDatabase(IRepositoryContext context, DbProviderFactory providerFactory, string connectionString)
 {
     Context = context;
     ProviderFactory = providerFactory;
     ConnectionString = connectionString;
     Connection = GetConnection();
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Ham nay de mo ket noi den database
        /// </summary>
        /// <param name="ServerName"></param>
        /// <param name="DatabaseName"></param>
        /// <param name="UserId"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public static bool DB_OpenConnection(string ServerName, string DatabaseName, string UserId, string Password)
        {
            DbProviderFactory = System.Data.SqlClient.SqlClientFactory.Instance;
            DbConnectionStringBuilder DbConnectionStringBuilder = DbProviderFactory.CreateConnectionStringBuilder();

            DbConnectionStringBuilder.Add("Data Source", ServerName);
            DbConnectionStringBuilder.Add("User ID", UserId);
            DbConnectionStringBuilder.Add("Password", Password);
            DbConnectionStringBuilder.Add("Initial Catalog", DatabaseName);

            bool IsConnected;

            try
            {
                if (DbConnection == null)
                {
                    DbConnection = DbProviderFactory.CreateConnection();
                }
                if (DbConnection.State != ConnectionState.Open)
                {
                    DbConnection.ConnectionString = DbConnectionStringBuilder.ConnectionString;
                    DbConnection.Open();
                }
                IsConnected = true;
            }
            catch
            {
                IsConnected = false;
            }
            return(IsConnected);
        }
Ejemplo n.º 26
0
 /// <summary>
 /// 构造函数--重载方法二
 /// </summary>
 /// <param name="connectionstring">数据库链接</param>
 /// <param name="databasetype">数据库的类型</param>
 public DBHelper(string connectionstring, string databasetype)
 {
     MyFactory = DbProviderFactories.GetFactory(databasetype);
     MyConnection = MyFactory.CreateConnection();
     MyConnection.ConnectionString = (databasetype.ToString() == "System.Data.OleDb") ? ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + GetDataPath(connectionstring) + ";") : (connectionstring);
     MyCommand = MyConnection.CreateCommand();
 }
Ejemplo n.º 27
0
 internal StubDataMapper(DbProviderFactory dbfactory, DbCommand command, DbConnection connection, DbParameterCollection parameters)
     : base(dbfactory, "connection string") 
 {
     _command = command;
     _connection = connection;
     _parameters = parameters;
 }
Ejemplo n.º 28
0
        private DbCommand BuildInsertCommand(System.Data.Common.DbProviderFactory provider, DbConnection con)
        {
            DbCommand com = provider.CreateCommand();

            com.CommandType = CommandType.Text;
            com.Connection  = con;
            string fieldList = SetFieldList();

            if (providerName == ProviderFactoryType.MySql.ToString())
            {
                com.CommandText = String.Format("Insert Into {0} SET {1}", this.tableName, fieldList) + ";" + this.LastInsertIdCommand(providerName);
                foreach (DataRow row in this.tableStruct.Rows)
                {
                    MySqlParameter parameter = new MySqlParameter();
                    parameter.ParameterName = "?" + row["fieldName"];
                    parameter.MySqlDbType   = GetMySqlType(row["ValueType"].ToString());
                    parameter.SourceColumn  = row["fieldName"].ToString();
                    parameter.IsNullable    = true;
                    if (row["fieldName"].ToString() == this.identityColumn)
                    {
                        parameter.Direction = ParameterDirection.Output;
                    }
                    else
                    {
                        parameter.Direction = ParameterDirection.Input;
                    }
                    com.Parameters.Add(parameter);
                }
            }
            return(com);
        }
Ejemplo n.º 29
0
        public DynamicModel(ConnectionStringSettings settings, DbProviderFactory factory)
        {
            Errors = new List<string>();

            _dbProviderFactory = factory;
            _connectionString = settings.ConnectionString;
        }
Ejemplo n.º 30
0
 public ProxyDbConnection(DbConnection proxiedConnection, DbProviderFactory proxiedFactory)
 {
     ProxiedConnection = proxiedConnection;
     ProxiedFactory = proxiedFactory;
     Context = GetContext(this);
     Guid = System.Guid.NewGuid().ToString();
 }
Ejemplo n.º 31
0
        public DynamicModel(ConnectionStringSettings settings, string providerName = "System.Data.SqlClient")
        {
            Errors = new List<string>();

            _dbProviderFactory = DbProviderFactories.GetFactory(providerName);
            _connectionString = settings.ConnectionString;
        }
Ejemplo n.º 32
0
 public CachedFactory(DbProviderFactory factory, string factoryName, string factoryDescription, string factoryAssemblyQualifiedNameKey)
 {
     Factory = factory;
     FactoryName = factoryName;
     FactoryDescription = factoryDescription;
     FactoryAssemblyQualifiedNameKey = factoryAssemblyQualifiedNameKey;
 }
Ejemplo n.º 33
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DynamicModel"/> class.
        /// </summary>
        /// <param name="connectionStringName">Name of the connection string.</param>
        /// <param name="tableName">Name of the table.</param>
        /// <param name="primaryKeyField">The primary key field.</param>
        /// <remarks></remarks>
        public DynamicModel(string connectionStringName = "", string tableName = "", string primaryKeyField = "")
        {
            this.TableName = tableName == "" ? this.GetType().Name : tableName;
            this.PrimaryKeyField = string.IsNullOrEmpty(primaryKeyField) ? "ID" : primaryKeyField;

            if (connectionStringName == "")
            {
                connectionStringName = ConfigurationManager.ConnectionStrings[0].Name;
            }

            var providerName = "System.Data.SqlClient";
            if (ConfigurationManager.ConnectionStrings[connectionStringName] != null)
            {
                if (!string.IsNullOrEmpty(ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName))
                {
                    providerName = ConfigurationManager.ConnectionStrings[connectionStringName].ProviderName;
                }
            }
            else
            {
                throw new InvalidOperationException(string.Format("Can't find a connection string with the name '{0}'", connectionStringName));
            }

            this._factory = DbProviderFactories.GetFactory(providerName);
            this._connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
        }
Ejemplo n.º 34
0
        /// <summary>
        /// 通过name 、数据库连接串、提供者名称, 创建database实例
        /// </summary>
        /// <param name="name">DBDatabase名称,唯一,主键</param>
        /// <param name="connectionString">数据库连接串</param>
        /// <param name="providername">数据库提供者名称</param>
        /// <returns>database实例</returns>
        public static Database Create(string name, string connectionString, string strDBtype)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException("connectionString", String.Format(DbError.ConnstrNull));
            }

            if (string.IsNullOrEmpty(strDBtype))
            {
                throw new ArgumentNullException("providername", String.Format(DbError.ProviderNameNull));
            }
            string providername = getProviderName(strDBtype);

            System.Data.Common.DbProviderFactory fact = System.Data.Common.DbProviderFactories.GetFactory(providername);

            if (null == fact)
            {
                throw new ArgumentNullException("providername", String.Format(DbError.InvalidProviderNameForConn, providername));
            }

            DBProvider datafact = DBProvider.GetProvider(providername);

            if (null == datafact)
            {
                throw new ArgumentNullException("providername", String.Format(DbError.InvalidProviderNameForDBFactory, providername));
            }

            Database db = datafact.CreateDatabase(connectionString, providername, fact);

            //设置名字
            db.Name = name;

            //返回实例
            return(db);
        }
Ejemplo n.º 35
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="dbConnectString">链接字符串</param>
 /// <param name="dbProviderNamespace">数据提供者的命名空间,例如:"System.Data.SqlClient"</param>
 public DBHelper(string dbConnectString, string dbProviderNamespace)
 {
     dbProviderFactory = DbProviderFactories.GetFactory(dbProviderNamespace);
     dbConnection = dbProviderFactory.CreateConnection();
     dbConnection.ConnectionString = dbConnectString;
     dbCommand = dbConnection.CreateCommand();
 }
        internal static EntityCommandDefinition CreateCommandDefinition(DbProviderFactory storeProviderFactory, DbCommandTree commandTree)
        {
            //Contract.Requires(storeProviderFactory != null);
            //Contract.Requires(commandTree != null);

            return new EntityCommandDefinition(storeProviderFactory, commandTree);
        }
        private static object CreateObject(DbProviderFactory factory, ProviderSupportedClasses kindOfObject, string providerName)
        {
            switch (kindOfObject)
            {
                case ProviderSupportedClasses.DbConnection:
                    return factory.CreateConnection();

                case ProviderSupportedClasses.DbDataAdapter:
                    return factory.CreateDataAdapter();

                case ProviderSupportedClasses.DbParameter:
                    return factory.CreateParameter();

                case ProviderSupportedClasses.DbCommand:
                    return factory.CreateCommand();

                case ProviderSupportedClasses.DbCommandBuilder:
                    return factory.CreateCommandBuilder();

                case ProviderSupportedClasses.DbDataSourceEnumerator:
                    return factory.CreateDataSourceEnumerator();

                case ProviderSupportedClasses.CodeAccessPermission:
                    return factory.CreatePermission(PermissionState.None);
            }
            throw new InternalException(string.Format(CultureInfo.CurrentCulture, "Cannot create object of provider class identified by enum {0} for provider {1}", new object[] { Enum.GetName(typeof(ProviderSupportedClasses), kindOfObject), providerName }));
        }
 public SqlWriterCommonTest(SqlType sqlType, DatabaseTable table, DbProviderFactory factory, string connectionString)
 {
     _connectionString = connectionString;
     _factory = factory;
     _table = table;
     _sqlType = sqlType;
 }
Ejemplo n.º 39
0
        protected DbProvider(string connectionString, System.Data.Common.DbProviderFactory dbProviderFactory)
        {
            this.dbConnectionStringBuilder = new DbConnectionStringBuilder();
            this.dbConnectionStringBuilder.ConnectionString = connectionString;
            this.dbProviderFactory = dbProviderFactory;

        }
        public SQLQueryProvider(DbProviderFactory dbFactory, string dbConnStr, string tableName, SetterDelegate setter) {

            m_dbFactory = dbFactory;
            m_dbConnStr = dbConnStr;
            m_tableName = tableName;
            m_setter = setter;
        }
Ejemplo n.º 41
0
 protected DbProvider(string connectionString, System.Data.Common.DbProviderFactory dbFactory, char leftToken, char rightToken, char paramPrefixToken)
 {
     this.leftToken        = leftToken;
     this.rightToken       = rightToken;
     this.paramPrefixToken = paramPrefixToken;
     this.dbHelper         = new DbHelper(connectionString, dbFactory);
     this.Timeout          = -1;
 }
Ejemplo n.º 42
0
 public DbConnectionEx(DbConnection inner, IAopFilter appender, Guid connectionId, System.Data.Common.DbProviderFactory providerFactory)
 {
     this.inner           = inner;
     this.providerFactory = providerFactory;
     this.connectionId    = connectionId;
     this.appender        = appender;
     appender.ConnectionStarted(connectionId);
 }
Ejemplo n.º 43
0
 public SqlQueryFactory(char leftToken, char rightToken, char paramPrefixToken, char wildcharToken, char wildsinglecharToken, System.Data.Common.DbProviderFactory fac)
 {
     this.leftToken           = leftToken;
     this.rightToken          = rightToken;
     this.paramPrefixToken    = paramPrefixToken;
     this.wildcharToken       = wildcharToken;
     this.wildsinglecharToken = wildsinglecharToken;
     this.fac = fac;
 }
Ejemplo n.º 44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:DbProvider"/> class.
 /// </summary>
 /// <param name="connectionString">The conn STR.</param>
 /// <param name="dbProviderFactory">The db provider factory.</param>
 /// <param name="leftToken">leftToken</param>
 /// <param name="paramPrefixToken">paramPrefixToken</param>
 /// <param name="rightToken">rightToken</param>
 protected DbProvider(string connectionString, DbProviderFactory dbProviderFactory, char leftToken, char rightToken, char paramPrefixToken)
 {
     dbConnStrBuilder = new DbConnectionStringBuilder();
     dbConnStrBuilder.ConnectionString = connectionString;
     this.dbProviderFactory            = dbProviderFactory;
     this.leftToken        = leftToken;
     this.rightToken       = rightToken;
     this.paramPrefixToken = paramPrefixToken;
 }
Ejemplo n.º 45
0
        public DataTable RetrieveTableStructure(string tableName)
        {
            DataTable tableStruct = new DataTable();
            string    lib         = GetProviderFactoryLib(providerName);

            System.Data.Common.DbProviderFactory provider = RegisterProvider(providerName);
            DbConnection con = provider.CreateConnection();

            con.ConnectionString = BuildConnectionString(providerName, "");
            DbCommand com = provider.CreateCommand();

            com.CommandTimeout = 30;
            com.Connection     = con;
            string queryString = "";

            if (providerName == ProviderFactoryType.MySql.ToString())
            {
                queryString = string.Format(@" 
					SELECT 
						lower( Column_name) as FieldName, 
						Column_name as FieldCaption, 
						Data_type As ValueType, 
						0 As ColumnIsHide, 
						0 As FieldIsHide, 
						0 As IsFake, 
						0 As IsReadOnly, 
						0 As IsRequiered, 
						'' As FieldCategory,
						'' As UserHelp,
						Extra As Extra, 
						if( isnull( Character_Maximum_Length),Numeric_Precision, Character_Maximum_Length) As Length, 
						if( isnull(Numeric_Scale), 000, Numeric_Scale) As DecimalPosition 
					From information_schema.COLUMNS
					Where Table_Schema = '{0}'
						And LOWER(Table_Name) = '{1}'"                        , this.dbName, tableName.ToLower()).Replace("\r", "").Replace("\n", " ").Replace("\t", " ").Replace("  ", " ");
            }
            com.CommandText = queryString;
            com.CommandType = CommandType.Text;
            DataSet       ds = new DataSet();
            DbDataAdapter da = provider.CreateDataAdapter();

            da.SelectCommand = com;

            try
            {
                con.Open();
                da.Fill(ds);
                tableStruct = ds.Tables[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
            con.Close();

            return(tableStruct);
        }
Ejemplo n.º 46
0
 private void ClickSelectedIndexChanged(object sender, EventArgs e)
 {
     if (comboBoxProviders.SelectedItem != null)
     {
         factory      = DbProviderFactories.GetFactory(comboBoxProviders.SelectedItem.ToString());
         connection   = factory.CreateConnection();
         providerName = GetConnectionStringByProvider(comboBoxProviders.SelectedItem.ToString());
         textBoxConnectionString.Text = providerName;
     }
 }
Ejemplo n.º 47
0
        public static void PinFor()
        {
            string tblname = "RDBMS_Table_ADONET_RegressionTest_" + Guid.NewGuid().ToString().Replace("-", "");

            System.Data.Common.DbProviderFactory fact = DbProviderFactories.GetFactory("DSpace_DataProvider");

            DbConnection conn = fact.CreateConnection();

            conn.ConnectionString = "Data Source = localhost";
            conn.Open();

            DbCommand cmd = conn.CreateCommand();

            //Create table
            {
                cmd.CommandText = "CREATE TABLE " + tblname + " (num INT, str CHAR(40), num2 LONG, num3 DOUBLE)";
                int rows = cmd.ExecuteNonQuery();
            }

            //Select from table
            {
                cmd.CommandText = "SELECT PIN FOR 10 * FROM  " + tblname;
                DbDataReader reader = cmd.ExecuteReader();
                reader.Close();
            }

            //Drop table
            {
                cmd.CommandText = "DROP PIN FOR 20 TABLE " + tblname + "";
                cmd.ExecuteNonQuery();
            }

            //Select from table
            bool ok = false;

            {
                try
                {
                    cmd.CommandText = "SELECT PIN FOR 10 * FROM  " + tblname;
                    DbDataReader reader = cmd.ExecuteReader();
                    reader.Close();
                }
                catch
                {
                    ok = true;
                }
            }

            conn.Close();

            if (!ok)
            {
                throw new Exception("Table didn't get dropped.");
            }
        }
Ejemplo n.º 48
0
        public SqlQueryFactory(char leftToken, char rightToken, char paramPrefixToken, char wildcharToken, char wildsinglecharToken, System.Data.Common.DbProviderFactory fac)
        {
            Check.Require(fac != null, "fac could not be null!");

            this.leftToken           = leftToken;
            this.rightToken          = rightToken;
            this.paramPrefixToken    = paramPrefixToken;
            this.wildcharToken       = wildcharToken;
            this.wildsinglecharToken = wildsinglecharToken;
            this.fac = fac;
        }
Ejemplo n.º 49
0
        /// <summary>
        /// 数据库提供者工厂实例,取配置文件
        /// </summary>
        private static System.Data.Common.DbProviderFactory GetProviderFactory()
        {
            if (_mfactory == null)
            {
                DbConnection dbConnection = null;

                dbConnection = new SQLiteConnection(_msConnection);

                _mfactory = DbProviderFactories.GetFactory(dbConnection);
            }
            return(_mfactory);
        }
Ejemplo n.º 50
0
 public Database(string _connectionString, System.Data.Common.DbProviderFactory dbProviderFactory)
 {
     if (string.IsNullOrEmpty(_connectionString))
     {
         throw new ArgumentException("", "connectionString");
     }
     if (dbProviderFactory == null)
     {
         throw new ArgumentNullException("dbProviderFactory");
     }
     this.connectionString  = _connectionString;
     this.dbProviderFactory = dbProviderFactory;
 }
Ejemplo n.º 51
0
        public static void DbAggregators_DropTable(string tablename)
        {
            System.Data.Common.DbProviderFactory fact = DbProviderFactories.GetFactory("DSpace_DataProvider");
            DbConnection conn = fact.CreateConnection();

            conn.ConnectionString = "Data Source = localhost";
            conn.Open();
            DbCommand cmd = conn.CreateCommand();

            cmd.CommandText = "drop table " + tablename;
            cmd.ExecuteNonQuery();
            conn.Close();
        }
Ejemplo n.º 52
0
Archivo: DAL.cs Proyecto: morimizu/repo
        public static SDC.DbDataReader ReadData(string sproc, List <ParamStruct> paramList)
        {
            SDC.DbProviderFactory factory = SDC.DbProviderFactories.GetFactory(Properties.Settings.Default.provider);

            SDC.DbCommand comm = factory.CreateCommand();
            comm = BuildCommand(sproc, paramList);

            SDC.DbConnection conn = Connection(factory);
            comm.Connection = conn;

            conn.Open();
            SDC.DbDataReader dr = comm.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

            return(dr);
        }
Ejemplo n.º 53
0
 /// <summary>
 /// 获取TNS信息
 /// Columns:InstanceName,ServerName,ServiceName,Protocol,Port
 /// </summary>
 /// 需要安装ODP.NET
 /// <returns></returns>
 internal static DataTable GetTNSInstance()
 {
     try
     {
         System.Data.Common.DbProviderFactory factory =
             System.Data.Common.DbProviderFactories.GetFactory("Oracle.DataAccess.Client");
         if (factory.CanCreateDataSourceEnumerator)
         {
             System.Data.Common.DbDataSourceEnumerator dsenum = factory.CreateDataSourceEnumerator();
             return(dsenum.GetDataSources()); //InstanceName,ServerName,ServiceName,Protocol,Port
         }
     }
     catch { }
     return(null);
 }
Ejemplo n.º 54
0
        public static void ConnClose()
        {
            System.Data.Common.DbProviderFactory fact = DbProviderFactories.GetFactory("DSpace_DataProvider");

            DbConnection conn = fact.CreateConnection();

            conn.ConnectionString = "Data Source = localhost";
            conn.Open();
            conn.Close();

            if (conn.State != ConnectionState.Closed)
            {
                throw new Exception("FAILED: State = {0}" + conn.State.ToString());
            }
        }
Ejemplo n.º 55
0
        //{
        //{ProviderType.DB2,"IBM.Data.DB2.DB2Factory,IBM.Data.DB2, Culture=neutral,Version=9.7.7.4,PublicKeyToken=7c307b91aa13d208"},
        //{ProviderType.SQLite,"Devart.Data.SQLite.SQLiteProviderFactory, Devart.Data.SQLite, Culture=neutral, Version=5.2.244.0, PublicKeyToken=09af7300eec23701"},
        //{ProviderType.Oracle,"Oracle.DataAccess.Client.OracleClientFactory, Oracle.DataAccess, Culture=neutral, Version=4.121.2.0,PublicKeyToken=89b483f429c47342"},//Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342
        //{ProviderType.MySql,"MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data.MySqlClient, Culture=neutral, Version=5.1.7.0, PublicKeyToken=c5687fc88969c44d"},
        //{ProviderType.MsOracle,"System.Data.OracleClient.OracleClientFactory,System.Data.OracleClient, Culture=neutral,Version=4.0.0.0, PublicKeyToken=b77a5c561934e089"},
        //{ProviderType.OleDb,"System.Data.OleDb.OleDbFactory, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c"},
        //{ProviderType.SqlServer,"System.Data.SqlClient.SqlClientFactory, System.Data, Culture=neutral, Version=4.0.0.0, PublicKeyToken=b77a5c561934e089"},
        //{ProviderType.Odbc,"System.Data.Odbc.OdbcFactory, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"}
        //};

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="dbProviderType"></param>
        /// <param name="IsSingleton"></param>
        protected DbCommonBuilder(ProviderType dbProviderType,
                                  bool IsSingleton)
        {
            this.IsSingleton    = IsSingleton;
            this.DbProviderType = dbProviderType;

            string invariantName = GetInvariantName(dbProviderType);

            dbFactory = GetDbProviderFactory(invariantName);

            if (dbFactory == null)
            {
                throw new Exception("不提供支持该" + dbProviderType.ToString() + "类型的实例");
            }
        }
Ejemplo n.º 56
0
        private System.Data.Common.DbCommandBuilder getDbCommandBuilder(string providerName)
        {
            System.Data.Common.DbCommandBuilder returnValue = null;

            if (!String.IsNullOrEmpty(providerName))
            {
                System.Data.Common.DbProviderFactory factory = System.Data.Common.DbProviderFactories.GetFactory(providerName);

                if (factory != null)
                {
                    returnValue = factory.CreateCommandBuilder();
                }
            }

            return(returnValue);
        }
Ejemplo n.º 57
0
        public void RecordUpdate <T>(out int rowsAffected, T row)
        {
            rowsAffected = 0;
            readConectionSettings();
            string lib = GetProviderFactoryLib(providerName);

            provider             = RegisterProvider(providerName);
            con                  = provider.CreateConnection();
            con.ConnectionString = BuildConnectionString(providerName, dbName);

            tableStruct = RetrieveTableStructure(tableName);
            if (tableStruct.Columns.Count == 0)
            {
                return;
            }
            dataAdapter = provider.CreateDataAdapter();
            dataAdapter.UpdateCommand             = BuildUpdateCommand(provider, con);
            dataAdapter.AcceptChangesDuringFill   = true;
            dataAdapter.AcceptChangesDuringUpdate = true;
            dataAdapter.ContinueUpdateOnError     = false;

            DbCommand updCmd = dataAdapter.UpdateCommand;

            Console.WriteLine("Update cmd: " + updCmd.CommandText);
            try
            {
                updCmd.Connection.Open();

                foreach (DbParameter parameter in updCmd.Parameters)
                {
                    string fieldName = parameter.SourceColumn;
                    parameter.Value = row.GetType().GetProperty(fieldName).GetValue(row, null);
                    if (fieldName == identityColumn)
                    {
                        parameter.SourceVersion = DataRowVersion.Original;
                    }
                }
                object returnVal = updCmd.ExecuteNonQuery();
                rowsAffected = Convert.ToInt16(returnVal);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            { updCmd.Connection.Close(); }
        }
Ejemplo n.º 58
0
        /*
         * Method to test the database provider version (only use for testing)
         */
        public static string GetProviderVersion()
        {
            string versionInfo = String.Empty;

            try
            {
                // SELECT COUNT(*)
                // VistaDBConnection sqlConn = new VistaDBConnection("data source='|DataDirectory|\forms.vdb5';Password=aj80995");
                System.Configuration.ConnectionStringSettings connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["UASEntitiesVenture"];
                // Loads the factory
                System.Data.Common.DbProviderFactory factory = System.Data.Common.DbProviderFactories.GetFactory(connectionString.ProviderName);
                using (DbConnection connection = factory.CreateConnection())
                {
                    connection.ConnectionString = connectionString.ConnectionString;
                    connection.Open();
                    Debug.WriteLine("* * *  GetProviderVersion ServerVersion: " + connection.ServerVersion);
                    Debug.WriteLine("* * *  GetProviderVersion DataSource: " + connection.DataSource);

                    using (DbCommand command = connection.CreateCommand())
                    {
                        command.CommandText = "SELECT @@VERSION;";
                        command.CommandType = CommandType.Text;

                        using (DbDataReader reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                string result = reader.GetString(0);
                                if (!reader.IsDBNull(0))
                                {
                                    versionInfo = result;
                                    Debug.WriteLine("* * *  GetProviderVersion versionInfo: " + versionInfo);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                versionInfo = "Exception: " + ex.Message;
                Debug.WriteLine("* * *  AuthenticateLocalUser uas_User row count error: " + ex.Message);
            }

            return(versionInfo);
        }
Ejemplo n.º 59
0
        private DbCommand BuildSelectCommand(System.Data.Common.DbProviderFactory provider, DbConnection con, string queryString, params dynamic[] args)
        {
            DbCommand com = provider.CreateCommand();

            com.CommandTimeout = 30;
            com.Connection     = con;
            com.CommandText    = queryString;
            com.CommandType    = CommandType.Text;
            foreach (var param in args)
            {
                DbParameter par = provider.CreateParameter();
                par.Direction     = ParameterDirection.Input;
                par.ParameterName = param.Name;
                par.Value         = param.Value;
                com.Parameters.Add(par);
            }
            return(com);
        }
Ejemplo n.º 60
0
 private bool TestConnection(string cs, out string reason)
 {
     reason = "";
     try
     {
         System.Data.Common.DbProviderFactory fact = DbProviderFactories.GetFactory("Qizmt_DataProvider");
         DbConnection conn = fact.CreateConnection();
         conn.ConnectionString = txtConnStr.Text.Trim();
         conn.Open();
         conn.Close();
         return(true);
     }
     catch (Exception e)
     {
         reason = e.ToString();
         return(false);
     }
 }