示例#1
0
        private void SetThreadSafe()
        {
            var asm = _Factory?.GetType().Assembly;

            if (asm == null)
            {
                return;
            }

            var type = asm.GetTypes().FirstOrDefault(e => e.Name == "UnsafeNativeMethods");
            var mi   = type?.GetMethod("sqlite3_config_none", BindingFlags.Static | BindingFlags.NonPublic);

            if (mi == null)
            {
                return;
            }

            /*
             * SQLiteConfigOpsEnum
             *  SQLITE_CONFIG_SINGLETHREAD = 1,
             *  SQLITE_CONFIG_MULTITHREAD = 2,
             *  SQLITE_CONFIG_SERIALIZED = 3,
             */

            mi.Invoke(this, new Object[] { 2 });
        }
        public static DataProviderType GetProviderType(DbProviderFactory providerFactory)
        {
            string name = providerFactory.GetType().Name;
            List <DataProviderType> providers    = ((DataProviderType[])Enum.GetValues(typeof(DataProviderType))).ToList();
            DataProviderType        providerType = providers.SingleOrDefault(e =>
                                                                             e.GetAttributeValue <ProviderAttribute>(p => p.FactoryType).ToString()
                                                                             .Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)[0] == name);

            return(providerType);
        }
示例#3
0
        /// <summary>
        /// Creates an instance of a query runner for the specified database.
        /// </summary>
        /// <param name="factory">The factory.</param>
        /// <param name="connectionString">The connection string.</param>
        /// <param name="enableQueryBatching">The enable query batching.</param>
        /// <param name="commandTimeout">The command timeout.</param>
        /// <returns>
        /// A <see cref="QueryRunner"/> instance acording to the parameters.
        /// </returns>
        /// <remarks>
        ///     <example>
        /// var runner = QueryRunner.Create(DbProviderFactories.GetFactory("System.Data.SqlClient"), connStr, true);
        /// runner.ExecuteQuery("select * from Employees\r\nGO\r\nSelect * from Products");
        /// // runner.Batch.Queries.Count == 2 //
        /// </example>
        /// </remarks>
        public static QueryRunner Create(DbProviderFactory factory, string connectionString, bool enableQueryBatching, int commandTimeout)
        {
            if (factory.GetType().Name == "SqlClientFactory")
            {
                return(new SqlQueryRunner(factory, connectionString, enableQueryBatching, commandTimeout));
            }

            // otherwise ise the default
            return(new QueryRunner(factory, connectionString, enableQueryBatching, commandTimeout));
        }
示例#4
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="DbDriverGeneric" /> class.
 /// </summary>
 /// <param name="dbProviderFactory">The database provider factory.</param>
 /// <param name="isPositional">if set to <c>true</c> [is positional].</param>
 /// <param name="paramPrefix">The parameter prefix.</param>
 public DbDriverGeneric(
     DbProviderFactory dbProviderFactory,
     bool isPositional,
     string paramPrefix)
 {
     _dbProviderFactory     = dbProviderFactory;
     _dbProviderFactoryName = dbProviderFactory.GetType().FullName; // half-baked
     _isPositional          = isPositional;
     _paramPrefix           = paramPrefix;
 }
        /// <summary>
        /// 获取数据库类型
        /// </summary>
        /// <param name="dbProvider">数据库提供者</param>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <returns>数据库类型</returns>
        internal static DatabaseType InternalGetDatabaseType(DbProviderFactory dbProvider, String connectionString)
        {
            String       providerName = dbProvider.GetType().ToString().ToLowerInvariant();
            DatabaseType dataType     = DatabaseType.Unknown;

            foreach (KeyValuePair <String, DatabaseType> pair in _typeDict)
            {
                if (providerName.IndexOf(pair.Key) >= 0)
                {
                    dataType = pair.Value;
                    break;
                }
            }

            if (dataType != DatabaseType.Unknown)
            {
                return(dataType);
            }

            #region Access
            if (providerName.IndexOf("system.data.oledb") >= 0)
            {
                String   dataSource = "";
                String[] parameters = connectionString.Replace(" ", "").ToLowerInvariant().Split(';');

                if (parameters != null && parameters.Length > 0)
                {
                    Int32 dataSourcePos = -1;

                    for (Int32 i = 0; i < parameters.Length; i++)
                    {
                        dataSourcePos = parameters[i].IndexOf("datasource");

                        if (dataSourcePos > -1)
                        {
                            dataSource = parameters[i];
                            break;
                        }
                    }
                }

                if (dataSource.IndexOf(".mdb") > -1)
                {
                    return(DatabaseType.Access);
                }
                else if (dataSource.IndexOf(".accdb") > -1)
                {
                    return(DatabaseType.Access);
                }
            }
            #endregion

            return(DatabaseType.Unknown);
        }
        public static string GetProviderInvariantName(this DbProviderFactory factory)
        {
            DebugCheck.NotNull(factory);

            const int invariantNameIndex = 2;

            var dataRows = DbProviderFactories.GetFactoryClasses().Rows.OfType <DataRow>();

            var row = new ProviderRowFinder().FindRow(
                factory.GetType(),
                r => DbProviderFactories.GetFactory(r).GetType() == factory.GetType(),
                dataRows);

            if (row == null)
            {
                throw new NotSupportedException(Strings.ProviderNameNotFound(factory));
            }

            return((string)row[invariantNameIndex]);
        }
示例#7
0
        public static string GetProviderInvariantName(this DbProviderFactory factory)
        {
            IEnumerable <DataRow> dataRows = DbProviderFactories.GetFactoryClasses().Rows.OfType <DataRow>();
            DataRow row = new ProviderRowFinder().FindRow(factory.GetType(), (Func <DataRow, bool>)(r => DbProviderFactories.GetFactory(r).GetType() == factory.GetType()), dataRows);

            if (row == null)
            {
                throw new NotSupportedException(Strings.ProviderNameNotFound((object)factory));
            }
            return((string)row[2]);
        }
示例#8
0
        private void Init()
        {
            string dbtype = (_factory?.GetType() ?? GetConnection().GetType()).Name;

            DbType dbType = DbType.SqlServer;

            if (dbtype.StartsWith("MySql"))
            {
                dbType = DbType.MySql;
            }
            else if (dbtype.StartsWith("SqlCe"))
            {
                dbType = DbType.SqlServerCe;
            }
            else if (dbtype.StartsWith("Npgsql"))
            {
                dbType = DbType.PostgreSql;
            }
            else if (dbtype.StartsWith("Oracle"))
            {
                dbType = DbType.Oracle;
            }
            else if (dbtype.StartsWith("SQLite"))
            {
                dbType = DbType.SqLite;
            }
            else if (dbtype.StartsWith("System.Data.SqlClient."))
            {
                dbType = DbType.SqlServer;
            }
            // else try with provider name
            else if (providerTypeName.IndexOf("MySql", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                dbType = DbType.MySql;
            }
            else if (providerTypeName.IndexOf("SqlServerCe", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                dbType = DbType.SqlServerCe;
            }
            else if (providerTypeName.IndexOf("Npgsql", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                dbType = DbType.PostgreSql;
            }
            else if (providerTypeName.IndexOf("Oracle", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                dbType = DbType.Oracle;
            }
            else if (providerTypeName.IndexOf("SQLite", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                dbType = DbType.SqLite;
            }
            DbType = dbType;
        }
示例#9
0
        public void ProviderFactoryTest()
        {
            DbProviderFactoryConnection con      = new DbProviderFactoryConnection();
            PropertyInfo providerFactoryProperty = con.GetType().GetProperty("ProviderFactory", BindingFlags.NonPublic | BindingFlags.Instance);

            Assert.NotNull(providerFactoryProperty);
            DbProviderFactory factory = providerFactoryProperty.GetValue(con) as DbProviderFactory;

            Assert.NotNull(factory);
            Assert.Same(typeof(TestDbProviderFactory), factory.GetType());
            Assert.Same(TestDbProviderFactory.Instance, factory);
        }
示例#10
0
        public void SqlConnectionDbProviderFactoryTest()
        {
            SqlConnection con = new();
            PropertyInfo  dbProviderFactoryProperty = con.GetType().GetProperty("DbProviderFactory", BindingFlags.NonPublic | BindingFlags.Instance);

            Assert.NotNull(dbProviderFactoryProperty);
            DbProviderFactory factory = dbProviderFactoryProperty.GetValue(con) as DbProviderFactory;

            Assert.NotNull(factory);
            Assert.Same(typeof(SqlClientFactory), factory.GetType());
            Assert.Same(SqlClientFactory.Instance, factory);
        }
        /// <summary>
        ///     Unwraps a wrapped <see cref="DbProviderFactory"/>.
        /// </summary>
        /// <param name="factory">The factory to unwrap.</param>
        /// <returns>The unwrapped factory or the original factory if no wrapping occurred.</returns>
        internal static DbProviderFactory Unwrap(DbProviderFactory factory)
        {
            var sp = factory as IServiceProvider;

            if (sp == null)
            {
                return(factory);
            }

            var unwrapped = sp.GetService(factory.GetType()) as DbProviderFactory;

            return(unwrapped == null ? factory : Unwrap(unwrapped));
        }
        /// <summary>
        /// 获取该数据库提供程序的名称。
        /// </summary>
        /// <param name="factory">表示一个 <see cref="System.Data.Common.DbProviderFactory"/> 对象。</param>
        /// <returns>该数据库提供程序的名称,例如 <see cref="System.Data.SqlClient.SqlClientFactory"/> 对象返回 "System.Data.SqlClient"。</returns>
        public static string GetProviderName(this DbProviderFactory factory)
        {
            Type   factoryType  = factory.GetType();
            string providerName = null;

            if (!_factoryMappings.Value.TryGetValue(factoryType, out providerName))
            {
                DbProviderFactoryClass factoryClass = DbProviderFactoryClasses.FirstOrDefault(item => Type.GetType(item.AssemblyQualifiedName) == factoryType);
                providerName = factoryClass == null ? factoryType.Namespace : factoryClass.InvariantName;
                _factoryMappings.Value.Add(factoryType, providerName);
            }
            return(providerName);
        }
示例#13
0
        public AdoNetConnectionFactory(string connectionString, string providerName)
        {
            _connectionString = connectionString;
            _factory          = DbProviderFactories.GetFactory(providerName);
            _dialect          = SqlDialect.GetDialectFor(_factory, connectionString);

            if (_dialect == null)
            {
                throw new InvalidOperationException($"Unable to guess dialect for: {connectionString}");
            }

            _log.Info("Created new connection factory for {0}, using dialect {1}.", _factory.GetType().Name, _dialect.GetType().Name);
        }
示例#14
0
        private void SetParamPrefix()
        {
            string dbtype = (dbFactory == null ? dbConnecttion.GetType() : dbFactory.GetType()).Name;

            // 使用类型名判断
            if (dbtype.StartsWith("MySql"))
            {
                _dbType = DBType.MySql;
            }
            else if (dbtype.StartsWith("SqlCe"))
            {
                _dbType = DBType.SqlServerCE;
            }
            else if (dbtype.StartsWith("Oracle"))
            {
                _dbType = DBType.Oracle;
            }
            else if (dbtype.StartsWith("SQLite"))
            {
                _dbType = DBType.SQLite;
            }
            else if (dbtype.StartsWith("System.Data.SqlClient."))
            {
                _dbType = DBType.SqlServer;
            }
            else if (_providerName.IndexOf("MySql", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                _dbType = DBType.MySql;
            }
            else if (_providerName.IndexOf("SqlServerCe", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                _dbType = DBType.SqlServerCE;
            }
            else if (_providerName.IndexOf("Oracle", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                _dbType = DBType.Oracle;
            }
            else if (_providerName.IndexOf("SQLite", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                _dbType = DBType.SQLite;
            }

            if (_dbType == DBType.MySql && dbConnecttion != null && dbConnecttion.ConnectionString != null && dbConnecttion.ConnectionString.IndexOf("Allow User Variables=true") >= 0)
            {
                paramPrefix = "?";
            }
            if (_dbType == DBType.Oracle)
            {
                paramPrefix = ":";
            }
        }
示例#15
0
        private void initSqlHelper(string connectionString, string providerName)
        {
            _lastConnectionString = connectionString;
            _lastProviderName     = providerName;

            _connectionString = connectionString;
            var txts = connectionString.Split(';');

            foreach (var txt in txts)
            {
                var sp = txt.Split('=');
                if (sp.Length != 2)
                {
                    continue;
                }
                if (sp[0].ToLower() == "database")
                {
                    _schemaName = sp[1];
                    break;
                }
                if (sp[0].ToLower() == "data source")
                {
                    _schemaName = sp[1];
                    break;
                }
            }


            _cacheService = new MemoryCacheService();
            _events       = new SqlEvents();
            _sqlConfig    = new SqlConfig(this);
            _sql          = new SqlRecord();
            _sqlMonitor   = new NullSqlMonitor();


            if (_sqlType == SqlType.None)
            {
                _sqlType = DatabaseProvider.GetSqlType(providerName ?? _factory.GetType().FullName, _connectionString);
            }
            _provider = DatabaseProvider.Resolve(_sqlType);
            if (_factory == null)
            {
                _factory     = _provider.GetFactory();
                _lastFactory = _factory;
            }
            if (_lastSqlHelper == null || _lastSqlHelper._isDisposable)
            {
                _lastSqlHelper = this;
            }
        }
示例#16
0
        /// <summary>
        /// 创建链接类型
        /// </summary>
        private void CommonCreate()
        {
            if (_providerName != null)
            {
                _factory = DbProviderFactories.GetFactory(_providerName);
            }
            string dbtype = (_factory == null ? _sharedConn.GetType() : _factory.GetType()).Name;

            if (dbtype.Contains("Oracle"))
            {
                dbType = DBType.Oracle;
            }
            else if (dbtype.Contains("MySql"))
            {
                dbType = DBType.MySql;
            }
            else if (dbtype.Contains("System.Data.SqlClient"))
            {
                dbType = DBType.SqlServer;
            }
            else if (_providerName.IndexOf("Oracle", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                dbType = DBType.Oracle;
            }
            else if (_providerName.IndexOf("MySql", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                dbType = DBType.MySql;
            }

            if (dbType == DBType.MySql && _connStr != null && _connStr.IndexOf("Allow User Variables=true") >= 0)
            {
                _paramPrefix = "?";
            }
            if (dbType == DBType.Oracle)
            {
                _paramPrefix = ":";
            }

            try
            {
                _sharedConn = _factory.CreateConnection();
                _sharedConn.ConnectionString = _connStr;
                _sharedConn.Open();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(ex.Message);
            }
        }
示例#17
0
        /// <summary>
        ///     Unwraps a wrapped <see cref="DbProviderFactory" />.
        /// </summary>
        /// <param name="factory">The factory to unwrap.</param>
        /// <returns>The unwrapped factory or the original factory if no wrapping occurred.</returns>
        internal static DbProviderFactory Unwrap(DbProviderFactory factory)
        {
            if (!(factory is IServiceProvider sp))
            {
                return(factory);
            }

            try
            {
                return(!(sp.GetService(factory.GetType()) is DbProviderFactory unwrapped) ? factory : Unwrap(unwrapped));
            }
            catch (Exception)
            {
                return(factory);
            }
        }
        private void SendProviderAndConnection(Object obj, Type type)
        {
            IEnumerable <FieldInfo> dbSetFields = type.GetFields();

            foreach (FieldInfo elem in dbSetFields)
            {
                if (elem.FieldType == dbConnection.GetType().BaseType)
                {
                    elem.SetValue(obj, dbConnection);
                }
                else if (elem.FieldType == providerFactory.GetType().BaseType)
                {
                    elem.SetValue(obj, providerFactory);
                }
            }
        }
示例#19
0
文件: XContext.cs 项目: lipz89/XData
        /// <summary>
        /// 初始化数据库上下文
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="providerName">数据库连接提供程序</param>
        public XContext(string connectionString, string providerName)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw Error.ArgumentNullException(nameof(connectionString));
            }
            if (string.IsNullOrWhiteSpace(providerName))
            {
                throw Error.ArgumentNullException(nameof(providerName));
            }

            ProviderName      = providerName;
            DbProviderFactory = DbProviderFactories.GetFactory(this.ProviderName);
            ConnectionString  = connectionString;
            DatabaseType      = DatabaseType.Resolve(DbProviderFactory.GetType().FullName, ProviderName);
        }
        private static IDbExecutionStrategy GetExecutionStrategy(
            DbConnection connection,
            DbProviderFactory providerFactory,
            string providerInvariantName = null)
        {
            EntityConnection entityConnection = connection as EntityConnection;

            if (entityConnection != null)
            {
                connection = entityConnection.StoreConnection;
            }
            string dataSource        = DbInterception.Dispatch.Connection.GetDataSource(connection, new DbInterceptionContext());
            ExecutionStrategyKey key = new ExecutionStrategyKey(providerFactory.GetType().FullName, dataSource);

            return(DbProviderServices._executionStrategyFactories.GetOrAdd(key, (Func <ExecutionStrategyKey, Func <IDbExecutionStrategy> >)(k => DbConfiguration.DependencyResolver.GetService <Func <IDbExecutionStrategy> >((object)new ExecutionStrategyKey(providerInvariantName ?? DbConfiguration.DependencyResolver.GetService <IProviderInvariantName>((object)providerFactory).Name, dataSource))))());
        }
示例#21
0
文件: Massive.cs 项目: goyuix/massive
        /// <summary>
        /// Adds a record to the database. You can pass in an Anonymous object, an ExpandoObject,
        /// A regular old POCO, or a NameValueColletion from a Request.Form or Request.QueryString
        /// </summary>
        public virtual object Insert(object o)
        {
            dynamic result = 0;

            using (var conn = OpenConnection()) {
                var cmd = CreateInsertCommand(o);
                cmd.Connection = conn;
                cmd.ExecuteNonQuery();
                if (!_factory.GetType().FullName.Contains("Oracle"))
                {
                    cmd.CommandText = "SELECT @@IDENTITY as newID";
                    result          = cmd.ExecuteScalar();
                }
            }
            return(result);
        }
示例#22
0
        private static IDbConnection GetConnection(string connectionName)
        {
            ConnectionStringSettings settings = Configuration.GetConnectionSettings(connectionName);
            DbProviderFactory        factory  = GetProviderFactory(settings.ProviderName);

            try
            {
                IDbConnection connection = factory.CreateConnection();
                connection.ConnectionString = settings.ConnectionString;
                return(connection);
            }
            catch (Exception ex)
            {
                throw new Exception($"{factory.GetType().Name} failed to create a connection.", ex);
            }
        }
示例#23
0
            private string GetParameterName(string paramName)
            {
                switch (_providerFactory.GetType().Name)
                {
                case "SqlClientFactory":
                case "MySqlClientFactory":
                    return("@" + paramName);

                case "OracleClientFactory":
                case "NpgsqlFactory":
                    return(":" + paramName);

                default:
                    // If we don't know, try to get it from the CommandBuilder.
                    return(GetParameterNameFromBuilder(_commandBuilder, paramName));
                }
            }
示例#24
0
        public OracleTimestampConverter(DbProviderFactory factory)
        {
            OracleAssembly = factory.GetType().Assembly;
            var globalizationType = OracleAssembly.GetType("Oracle.DataAccess.Client.OracleGlobalization");

            if (globalizationType != null)
            {
                DateTimeOffsetInputFormat = DateTimeOffsetOutputFormat = "yyyy-MM-dd HH:mm:ss.ffffff zzz";
                TimestampTzFormat         = "YYYY-MM-DD HH24:MI:SS.FF6 TZH:TZM";

                SetThreadInfoArgs = new [] { globalizationType.InvokeMember("GetClientInfo", InvokeStaticPublic, null, null, null) };
                const BindingFlags setProperty = BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance;
                globalizationType.InvokeMember("TimeStampTZFormat", setProperty, null, SetThreadInfoArgs[0], new object[] { TimestampTzFormat });
                SetThreadInfo = globalizationType.GetMethod("SetThreadInfo", BindingFlags.Public | BindingFlags.Static);

                var parameterType        = OracleAssembly.GetType("Oracle.DataAccess.Client.OracleParameter");
                var oracleDbTypeProperty = parameterType.GetProperty("OracleDbType", BindingFlags.Public | BindingFlags.Instance);
                SetOracleDbType = oracleDbTypeProperty.GetSetMethod();

                var oracleDbType = OracleAssembly.GetType("Oracle.DataAccess.Client.OracleDbType");
                SetOracleDbTypeArgs = new [] { Enum.Parse(oracleDbType, "TimeStampTZ") };

                var readerType = OracleAssembly.GetType("Oracle.DataAccess.Client.OracleDataReader");
                GetOracleValue = readerType.GetMethod("GetOracleValue", BindingFlags.Public | BindingFlags.Instance);
            }
            else
            {
                //TODO This is Microsoft provider support and it does not handle the offsets correctly,
                // but I don't know how to make it work.

                DateTimeOffsetOutputFormat = "dd-MMM-yy hh:mm:ss.fff tt";
                DateTimeOffsetInputFormat  = "dd-MMM-yy hh:mm:ss tt";
                TimestampTzFormat          = "DD-MON-RR HH.MI.SSXFF AM";

//                var parameterType = OracleAssembly.GetType("System.Data.OracleClient.OracleParameter");
//                var oracleTypeProperty = parameterType.GetProperty("OracleType", BindingFlags.Public | BindingFlags.Instance);
//                SetOracleDbType = oracleTypeProperty.GetSetMethod();

                var oracleDbType = OracleAssembly.GetType("System.Data.OracleClient.OracleType");
                SetOracleDbTypeArgs = new [] { Enum.Parse(oracleDbType, "TimestampWithTZ") };

//                var readerType = OracleAssembly.GetType("System.Data.OracleClient.OracleDataReader");
//                GetOracleValue = readerType.GetMethod("GetOracleValue", BindingFlags.Public | BindingFlags.Instance);
            }
        }
        static IMessageQueryProvider CreateSqlProviderByFactory(DbProviderFactory factory, IObjectSerializer serializer)
        {
            var name = factory.GetType().Name.ToLowerInvariant();

            if (name.Contains("mysql"))
            {
                return(new MySqlQueryProvider(serializer));
            }
            if (name.Contains("sqlite"))
            {
                return(new SqliteQueryProvider(serializer));
            }
            if (name.Contains("sqlclient"))
            {
                return(new SqlServerQueryProvider(serializer));
            }
            return(null);
        }
示例#26
0
        private static DatabaseType DetectDatabaseType(DbProviderFactory factory)
        {
            switch (factory.GetType().Name.ToLower())
            {
            // OracleClientFactory
            case "oracleclientfactory": return(DatabaseType.Oracle);

            // SqlClientFactory
            case "sqlclientfactory": return(DatabaseType.SqlServer);

            // MySqlClientFactory
            case "mysqlclientfactory": return(DatabaseType.MySql);

            // SQLiteFactory
            case "sqlitefactory": return(DatabaseType.SQLite);

            default: return(DatabaseType.Default);
            }
        }
示例#27
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="factory">The factory.</param>
        /// <param name="connection">The connection.</param>
        /// <param name="name">The name.</param>
        /// <param name="parameterPrefix">The parameter prefix.</param>
        /// <exception cref="System.ArgumentNullException">configuration</exception>
        public Connection(IConfiguration configuration, DbProviderFactory factory, string connection, string name, string parameterPrefix = "@")
        {
            Configuration = configuration ?? throw new System.ArgumentNullException(nameof(configuration));
            Name          = string.IsNullOrEmpty(name) ? "Default" : name;
            SourceType    = factory.GetType().FullName;
            Factory       = factory;
            var TempConfig = configuration.GetConnectionString(Name);

            if (string.IsNullOrEmpty(connection) && TempConfig != null)
            {
                ConnectionString = TempConfig;
            }
            else
            {
                ConnectionString = string.IsNullOrEmpty(connection) ? name : connection;
            }
            if (string.IsNullOrEmpty(parameterPrefix))
            {
                if (SourceType.Contains("MySql"))
                {
                    ParameterPrefix = "?";
                }
                else if (SourceType.Contains("Oracle"))
                {
                    ParameterPrefix = ":";
                }
                else
                {
                    DatabaseName    = Regex.Match(ConnectionString, @"Initial Catalog=([^;]*)").Groups[1].Value;
                    ParameterPrefix = "@";
                }
            }
            else
            {
                ParameterPrefix = parameterPrefix;
                if (SourceType.Contains("SqlClient"))
                {
                    DatabaseName = Regex.Match(ConnectionString, @"Initial Catalog=([^;]*)").Groups[1].Value;
                }
            }
        }
示例#28
0
 private void db_query(string SQLite)
 {
     using (DbCommand cmd = _dbcon.CreateCommand())
     {
         if (_dbfact.GetType().Name.IndexOf("SQLite", StringComparison.OrdinalIgnoreCase) == -1)
         {
             cmd.CommandText = SQLite;
         }
         else
         {
             cmd.CommandText = SQLite;
         }
         try
         {
             cmd.ExecuteNonQuery();
         }
         catch (Exception)
         {
         }
     }
 }
        /// <summary>
        /// Makes sure that the given <paramref name="dbProviderFactory"/> is registered inside global <see cref="DbProviderFactories"/>.
        /// It queries the needed information from the runtime type and creates a new entry inside <c>system.data</c> configuration section.
        /// Additionally the path of the factory is added to <see cref="AppDomain.CurrentDomain"/> as "PrivatePath" to allow
        /// proper assembly lookup inside subfolder.
        /// </summary>
        /// <param name="dbProviderFactory">DbProviderFactory instance</param>
        public static void AssureKnownFactory(DbProviderFactory dbProviderFactory)
        {
            var dataSet = ConfigurationManager.GetSection("system.data") as DataSet;

            if (dataSet == null)
            {
                return;
            }

            Type      factoryType   = dbProviderFactory.GetType();
            string    invariantName = factoryType.Namespace;
            DataTable dt            = dataSet.Tables[0];

            if (dt.Rows.Cast <DataRow>().Any(row => row["InvariantName"].ToString() == invariantName))
            {
                return;
            }

            dt.Rows.Add(invariantName, "Temporary added factory for EF use", invariantName, factoryType.AssemblyQualifiedName);
            AppDomain.CurrentDomain.AppendPrivatePath(Path.GetDirectoryName(factoryType.Assembly.Location));
        }
示例#30
0
        /// <summary>
        /// Get ZDBMS.
        /// </summary>
        /// <param name="provider">Provider</param>
        /// <returns></returns>
        public static ZDBMS GetDBMS(DbProviderFactory provider)
        {
            string providerType = provider.GetType().FullName;

            return(GetDBMS(providerType));

            /*
             * switch (providerType)
             * {
             *  // "FirebirdSql.Data.FirebirdClient.FirebirdClientFactory"
             *  case "firebirdsql.data.firebirdclient.firebirdclientfactory":
             *      return ZDBMS.Firebird;
             *
             *  // "MySql.Data.MySqlClient.MySqlClientFactory"
             *  case "mysql.data.mysqlclient.mysqlclientfactory":
             *      return ZDBMS.MySQL;
             *
             *  // "Oracle.DataAccess.Client.OracleClientFactory"
             *  // "System.Data.OracleClient.OracleClientFactory"
             *  case "oracle.dataaccess.client.oracleclientfactory":
             *  case "system.data.oracleclient.oracleclientfactory":
             *      return ZDBMS.Oracle;
             *
             *  // "Npgsql.NpgsqlFactory":
             *  case "npgsql.npgsqlfactory":
             *      return ZDBMS.PostgreSQL;
             *
             *  // "System.Data.SQLite.SQLiteFactory"
             *  case "system.data.sqlite.sqlitefactory":
             *      return ZDBMS.SQLite;
             *
             *  // "System.Data.SqlClient.SqlClientFactory"
             *  case "system.data.sqlclient.sqlclientfactory":
             *      return ZDBMS.SQLServer;
             *
             *  default:
             *      return ZDBMS.Unknown;
             * }
             */
        }