예제 #1
0
 private void SetDbParams(System.Data.Common.DbConnection conn)
 {
     if (conn.GetType().Name.ToLower().IndexOf("oracle") > -1 || conn.GetType().Name.ToLower().IndexOf("pgsql") > -1)
     {
         dbParamChar = ':';
     }
 }
예제 #2
0
        /// <summary>
        /// Creates data adapter for specifided database connection.
        /// </summary>
        /// <param name="connection">Database connection for detection specialization.</param>
        /// <returns>Relatived data adapter.</returns>
        public static DbDataAdapter CreateDataAdapter(DbConnection connection)
        {
            Debug.Assert(null != connection); // created
            Debug.Assert((connection.GetType() == typeof(OleDbConnection)) ||
                         (connection.GetType() == typeof(OdbcConnection))); // supported type

            // select DB provider factory by connection type
            DbProviderFactory factory = (connection.GetType() == typeof(OleDbConnection)) ?
                                            (DbProviderFactory)OleDbFactory.Instance :
                                            (DbProviderFactory)OdbcFactory.Instance;
            return _CreateDataAdapter(factory);
        }
예제 #3
0
    public static string GenerateAllTables(this System.Data.Common.DbConnection connection, GeneratorBehavior generatorBehavior = GeneratorBehavior.Default)
    {
        if (connection.State != ConnectionState.Open)
        {
            connection.Open();
        }

        var conneciontName = connection.GetType().Name.ToLower();
        var tables         = new List <string>();
        var sql            = generatorBehavior.HasFlag(GeneratorBehavior.View) ? TableSchemaSqls[conneciontName].Split("where")[0] : TableSchemaSqls[conneciontName];

        using (var command = connection.CreateCommand(sql))
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    tables.Add(reader.GetString(0));
                }
            }

        var sb = new StringBuilder();

        sb.AppendLine("namespace Models { ");
        tables.ForEach(table => sb.Append(connection.GenerateClass(
                                              string.Format(QuerySqls[conneciontName], table), table, generatorBehavior: generatorBehavior
                                              )));
        sb.AppendLine("}");
        return(sb.ToString());
    }
        public DbProviderFactory GetProviderFactory(DbConnection connection)
        {
            Check.NotNull(connection, "connection");

#if NET40
            var connectionType = connection.GetType();

            return _cache.GetOrAdd(
                connectionType,
                t =>
                    {
                        var row = _finder.FindRow(t, r => ExactMatch(r, t))
                                  ?? _finder.FindRow(null, r => ExactMatch(r, t))
                                  ?? _finder.FindRow(t, r => AssignableMatch(r, t))
                                  ?? _finder.FindRow(null, r => AssignableMatch(r, t));

                        if (row == null)
                        {
                            throw new NotSupportedException(Strings.ProviderNotFound(connection.ToString()));
                        }

                        return DbProviderFactories.GetFactory(row);
                    });
#else
            return DbProviderFactories.GetFactory(connection);
#endif
        }
예제 #5
0
 public string ResolveManifestToken(DbConnection connection)
 {
     return (!string.IsNullOrWhiteSpace(connection.Database) // Some negative cases require the provider to fail
            && connection is SqlConnection)
            || connection.GetType().FullName.StartsWith("Castle.Proxies.")
                ? "2008"
                : _defaultManifestTokenResolver.ResolveManifestToken(connection);
 }
예제 #6
0
//#if COREFX
        public SchemaParameters(System.Data.Common.DbConnection dbConnection)
        {
            DbConnection     = dbConnection;
            ProviderName     = DbConnection.GetType().Namespace;
            ConnectionString = dbConnection.ConnectionString;
            SqlType          = ProviderToSqlType.Convert(ProviderName);
            Exclusions       = new Exclusions();
        }
        protected override string GetDbProviderManifestToken(DbConnection connection)
        {
            if (connection.GetType()
                != typeof(EntityConnection))
            {
                throw new ArgumentException(Strings.Mapping_Provider_WrongConnectionType(typeof(EntityConnection)));
            }

            return MetadataItem.EdmProviderManifest.Token;
        }
예제 #8
0
        protected override string GetDbProviderManifestToken(DbConnection connection)
        {
            EntityUtil.CheckArgumentNull(connection, "connection");
            if (connection.GetType() != typeof(EntityConnection))
            {
                throw EntityUtil.Argument(System.Data.Entity.Strings.Mapping_Provider_WrongConnectionType(typeof(EntityConnection)));
            }

            return MetadataItem.EdmProviderManifest.Token;
        }
        /// <inheritdoc />
        public string ResolveManifestToken(DbConnection connection)
        {
            Check.NotNull(connection, "connection");

            var interceptionContext = new DbInterceptionContext();
            var key = Tuple.Create(connection.GetType(),
                DbInterception.Dispatch.Connection.GetDataSource(connection, interceptionContext),
                DbInterception.Dispatch.Connection.GetDatabase(connection, interceptionContext));

            return _cachedTokens.GetOrAdd(
                key,
                k => DbProviderServices.GetProviderServices(connection).GetProviderManifestTokenChecked(connection));
        }
예제 #10
0
        public static ISchemaBuilder For(DbConnection connection)
        {
            string connectionName = connection.GetType().Name.ToLower();

            if (!SchemaBuilders.ContainsKey(connectionName))
            {
                throw new ArgumentException("Unknown connection name: " + connectionName);
            }

            var dialect = SqlDialectFactory.For(connection);

            return SchemaBuilders[connectionName](dialect);
        }
예제 #11
0
      /// <summary>
      /// Factory method
      /// </summary>
      /// <param name="connection"></param>
      /// <param name="doInjectFaultAction"></param>
      /// <returns></returns>
      public static ChaosDbConnection Create(DbConnection connection, Func<bool> doInjectFaultAction = null)
      {
         ChaosDbConnection result = null;
         if (connection != null)
         {
            var connType = connection.GetType();

            if (connType == typeof(System.Data.SqlClient.SqlConnection))
            {
               result = new Sql.SqlChaosDbConnection(connection, doInjectFaultAction ?? ChaosHelper.DefaultDoInjectFault);
            }
            else
            {
               // default 
               result = new ChaosDbConnection(connection, doInjectFaultAction ?? ChaosHelper.DefaultDoInjectFault);
            }

         }
         return result;
      }
        public static DbDataAdapter CreateDataAdapter(DbCommand dbCommand, DbConnection connection)
        {
            DbDataAdapter adapter; //we can't construct an adapter directly
            //So let's run around the block 3 times, before potentially crashing

            if (connection is System.Data.SqlClient.SqlConnection)

                adapter = new System.Data.SqlClient.SqlDataAdapter(dbCommand.CommandText, connection as SqlConnection);
            else if (connection is System.Data.OleDb.OleDbConnection)
                adapter = new System.Data.OleDb.OleDbDataAdapter(dbCommand.CommandText, connection as System.Data.OleDb.OleDbConnection);
            else if (connection is System.Data.Odbc.OdbcConnection)
                adapter = new System.Data.Odbc.OdbcDataAdapter(dbCommand.CommandText, connection as System.Data.Odbc.OdbcConnection);
            else if (connection is System.Data.SqlServerCe.SqlCeConnection)
                adapter = new System.Data.SqlServerCe.SqlCeDataAdapter(dbCommand.CommandText, connection as System.Data.SqlServerCe.SqlCeConnection);
            //TODO: Add more DbConnection kinds as they become invented
            else
            {
                throw new Exception("[CreateDataAdapter] Unknown DbConnection type: " + connection.GetType().FullName);
            }

            return adapter;
        }
        public DbProviderFactory GetProviderFactory(DbConnection connection, IEnumerable<DataRow> dataRows)
        {
            DebugCheck.NotNull(connection);
            DebugCheck.NotNull(dataRows);

            var connectionType = connection.GetType();

            return _cache.GetOrAdd(
                connectionType,
                t =>
                    {
                        var row = _finder.FindRow(t, r => ExactMatch(r, t), dataRows)
                                  ?? _finder.FindRow(null, r => ExactMatch(r, t), dataRows)
                                  ?? _finder.FindRow(t, r => AssignableMatch(r, t), dataRows)
                                  ?? _finder.FindRow(null, r => AssignableMatch(r, t), dataRows);

                        if (row == null)
                        {
                            throw new NotSupportedException(Strings.ProviderNotFound(connection.ToString()));
                        }

                        return DbProviderFactories.GetFactory(row);
                    });
        }
예제 #14
0
 /// <summary>
 /// 根据连接类型建立联接
 /// </summary>
 /// <param name="connection">所需建立的连接,目前有OleConnection和SqlConnection</param>
 public static void BuildConnection(DbConnection connection)
 {
     if (connection.GetType().FullName.Equals("System.Data.SqlClient.SqlConnection"))
     {
         ExcelUtility.sqlConnectionString = "Data Source=.; database=JXT; uid=sa; pwd=123456";
         ExcelUtility.sqlConnection = new SqlConnection(ExcelUtility.sqlConnectionString);
     }
     else if (connection.GetType().FullName.Equals("System.Data.OleDb.OleDbConnection"))
     {
         ExcelUtility.oleConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelUtility.excelItem.Path + @";Extended Properties=""Excel 8.0;HDR=YES;IMEX=1;""";
         ExcelUtility.OleConnection = new OleDbConnection(ExcelUtility.oleConnectionString);
     }
 }
예제 #15
0
        private void MultipleErrorHandling(DbConnection connection)
        {
            try
            {
                Console.WriteLine("MultipleErrorHandling {0}", connection.GetType().Name);
                Type expectedException = null;
                if (connection is SqlConnection)
                {
                    ((SqlConnection)connection).InfoMessage += delegate (object sender, SqlInfoMessageEventArgs args)
                    {
                        Console.WriteLine("*** SQL CONNECTION INFO MESSAGE : {0} ****", args.Message);
                    };
                    expectedException = typeof(SqlException);
                }
                connection.Open();

                using (DbCommand command = connection.CreateCommand())
                {
                    command.CommandText =
                        "PRINT N'0';\n" +
                        "SELECT num = 1, str = 'ABC';\n" +
                        "PRINT N'1';\n" +
                        "RAISERROR('Error 1', 15, 1);\n" +
                        "PRINT N'3';\n" +
                        "SELECT num = 2, str = 'ABC';\n" +
                        "PRINT N'4';\n" +
                        "RAISERROR('Error 2', 15, 1);\n" +
                        "PRINT N'5';\n" +
                        "SELECT num = 3, str = 'ABC';\n" +
                        "PRINT N'6';\n" +
                        "RAISERROR('Error 3', 15, 1);\n" +
                        "PRINT N'7';\n" +
                        "SELECT num = 4, str = 'ABC';\n" +
                        "PRINT N'8';\n" +
                        "RAISERROR('Error 4', 15, 1);\n" +
                        "PRINT N'9';\n" +
                        "SELECT num = 5, str = 'ABC';\n" +
                        "PRINT N'10';\n" +
                        "RAISERROR('Error 5', 15, 1);\n" +
                        "PRINT N'11';\n";

                    try
                    {
                        Console.WriteLine("**** ExecuteNonQuery *****");
                        command.ExecuteNonQuery();
                    }
                    catch (Exception e)
                    {
                        PrintException(expectedException, e);
                    }

                    try
                    {
                        Console.WriteLine("**** ExecuteScalar ****");
                        command.ExecuteScalar();
                    }
                    catch (Exception e)
                    {
                        PrintException(expectedException, e);
                    }

                    try
                    {
                        Console.WriteLine("**** ExecuteReader ****");
                        using (DbDataReader reader = command.ExecuteReader())
                        {
                            bool moreResults = true;
                            do
                            {
                                try
                                {
                                    Console.WriteLine("NextResult");
                                    moreResults = reader.NextResult();
                                }
                                catch (Exception e)
                                {
                                    PrintException(expectedException, e);
                                }
                            } while (moreResults);
                        }
                    }
                    catch (Exception e)
                    {
                        PrintException(null, e);
                    }
                }
            }
            catch (Exception e)
            {
                PrintException(null, e);
            }
            try
            {
                connection.Dispose();
            }
            catch (Exception e)
            {
                PrintException(null, e);
            }
        }
 /// <summary>Retrieves the DbProviderFactory based on the specified DbConnection.</summary>
 /// <returns>The retrieved DbProviderFactory.</returns>
 /// <param name="connection">The connection to use.</param>
 public static DbProviderFactory GetProviderFactory(DbConnection connection)
 {
     Check.NotNull(connection, "connection");
     var factory = connection.GetProviderFactory();
     if (factory == null)
     {
         throw new ProviderIncompatibleException(
             Strings.EntityClient_ReturnedNullOnProviderMethod(
                 "get_ProviderFactory",
                 connection.GetType().ToString()));
     }
     return factory;
 }
예제 #17
0
    internal void Run(DbConnection cnn)
    {
      frm = new Form1();

      frm.Show();

      frm.WriteLine("\r\nBeginning Test on " + cnn.GetType().ToString());
      try { CreateTable(cnn); frm.WriteLine("SUCCESS - CreateTable"); }
      catch (Exception) { frm.WriteLine("FAIL - CreateTable"); }

      try { DataTypeTest(cnn); frm.WriteLine("SUCCESS - DataType Test"); }
      catch (Exception) { frm.WriteLine("FAIL - DataType Test"); }

      try { FullTextTest(cnn); frm.WriteLine("SUCCESS - Full Text Search"); }
      catch (Exception) { frm.WriteLine("FAIL - Full Text Search"); }

      try { KeyInfoTest(cnn); frm.WriteLine("SUCCESS - KeyInfo Fetch"); }
      catch (Exception) { frm.WriteLine("FAIL - KeyInfo Fetch"); }

      try { InsertTable(cnn); frm.WriteLine("SUCCESS - InsertTable"); }
      catch (Exception) { frm.WriteLine("FAIL - InsertTable"); }

      try { VerifyInsert(cnn); frm.WriteLine("SUCCESS - VerifyInsert"); }
      catch (Exception) { frm.WriteLine("FAIL - VerifyInsert"); }

      try { CoersionTest(cnn); frm.WriteLine("FAIL - CoersionTest"); }
      catch (Exception) { frm.WriteLine("SUCCESS - CoersionTest"); }

      try { ParameterizedInsert(cnn); frm.WriteLine("SUCCESS - ParameterizedInsert"); }
      catch (Exception) { frm.WriteLine("FAIL - ParameterizedInsert"); }

      try { BinaryInsert(cnn); frm.WriteLine("SUCCESS - BinaryInsert"); }
      catch (Exception) { frm.WriteLine("FAIL - BinaryInsert"); }

      try { VerifyBinaryData(cnn); frm.WriteLine("SUCCESS - VerifyBinaryData"); }
      catch (Exception) { frm.WriteLine("FAIL - VerifyBinaryData"); }

      try { LockTest(cnn); frm.WriteLine("SUCCESS - LockTest"); }
      catch (Exception) { frm.WriteLine("FAIL - LockTest"); }

      try { ParameterizedInsertMissingParams(cnn); frm.WriteLine("FAIL - ParameterizedInsertMissingParams"); }
      catch (Exception) { frm.WriteLine("SUCCESS - ParameterizedInsertMissingParams"); }

      try { InsertMany(cnn, false); frm.WriteLine("SUCCESS - InsertMany"); }
      catch (Exception) { frm.WriteLine("FAIL - InsertMany"); }

      try { InsertMany(cnn, true); frm.WriteLine("SUCCESS - InsertManyWithIdentityFetch"); }
      catch (Exception) { frm.WriteLine("FAIL - InsertManyWithIdentityFetch"); }

      try { FastInsertMany(cnn); frm.WriteLine("SUCCESS - FastInsertMany"); }
      catch (Exception) { frm.WriteLine("FAIL - FastInsertMany"); }

      try { IterationTest(cnn); frm.WriteLine("SUCCESS - Iteration Test"); }
      catch (Exception) { frm.WriteLine("FAIL - Iteration Test"); }

      try { UserFunction(cnn); frm.WriteLine("SUCCESS - UserFunction"); }
      catch (Exception) { frm.WriteLine("FAIL - UserFunction"); }

      try { UserAggregate(cnn); frm.WriteLine("SUCCESS - UserAggregate"); }
      catch (Exception) { frm.WriteLine("FAIL - UserAggregate"); }

      try { UserCollation(cnn); frm.WriteLine("SUCCESS - UserCollation"); }
      catch (Exception) { frm.WriteLine("FAIL - UserCollation"); }

      try { DropTable(cnn); frm.WriteLine("SUCCESS - DropTable"); }
      catch (Exception) { frm.WriteLine("FAIL - DropTable"); }

      frm.WriteLine("\r\nTests Finished.");
    }
예제 #18
0
 public static IDatabaseFactory FindFactory(DbConnection connection)
 {
     if (_factoryByType.ContainsKey(connection.GetType())) return _factoryByType[connection.GetType()];
     return null;
 }
예제 #19
0
        /// <summary>
        /// 通过DbConnection对象创建DbConfiguration对象
        /// </summary>
        /// <param name="conn"></param>
        /// <returns></returns>
        public static DbConfiguration Configure(DbConnection conn)
        {
            Guard.NotNull(conn, "conn");
            var providerType = conn.GetType()
                .Assembly
                .GetTypes()
                .Where(t => typeof(System.Data.Common.DbProviderFactory).IsAssignableFrom(t)
                && t.Namespace == conn.GetType().Namespace)
                .FirstOrDefault()
                ;
            if (providerType == null)
                throw new NotSupportedException("not found 'DbProviderFactory'");
            var factory = providerType.GetField("Instance", BindingFlags.Public | BindingFlags.Static).GetValue(null) as DbProviderFactory;
            Guard.NotNull(factory, "factory");

            var providerName = providerType.Namespace;
            var cfg = new DbConfiguration(providerName, Guid.NewGuid().ToString(), conn.ConnectionString, factory);
            if (!Options.ContainsKey(providerName))
            {
                var dbtype = conn.GetType().Name;
                if (dbtype.StartsWith("MySql")) providerName = DbProviderNames.MySQL;
                else if (dbtype.StartsWith("SqlCe")) providerName = DbProviderNames.SqlCe35;
                else if (dbtype.StartsWith("Oledb")) providerName = DbProviderNames.Oledb;
                else if (dbtype.StartsWith("Oracle")) providerName = DbProviderNames.Oracle;
                else if (dbtype.StartsWith("SQLite")) providerName = DbProviderNames.SQLite;
                else if (dbtype.StartsWith("System.Data.SqlClient.")) providerName = DbProviderNames.SqlServer;
            }
            if (Options.ContainsKey(providerName))
            {
                cfg.Option = Options[providerName];
            }

            PopulateSqlServer2000(conn, factory, cfg);
            cfg.connection = conn;
            return cfg;
        }
        // The provider manifest token helps to distinguish between store versions. 
        // We have only one backend version.
        // However, use the connection passed in to determine whether 
        // the provider is local provider or remote provider
        //
        protected override string GetDbProviderManifestToken(DbConnection connection)
        {
            // vamshikb: Do we need to validate the connection and connection string
            // before returning the ProviderManifestToken????

            // Determine the type of DbConnection
            // This method should never be called at runtime, so the provider
            // must be remote provider.
            // Throw if it is none.
            //
            if (connection.GetType()
                == typeof(SqlCeConnection))
            {
                _isLocalProvider = true;
            }
            else if (RemoteProviderHelper.CompareObjectEqualsToType(connection, RemoteProvider.SqlCeConnection))
            {
                _isLocalProvider = false;
            }
            else
            {
                throw ADP1.Argument(EntityRes.GetString(EntityRes.Mapping_Provider_WrongConnectionType, "SqlCeConnection"));
            }

            return SqlCeProviderManifest.Token40;
        }
예제 #21
0
 //
 // : IDbTransaction
 //
 internal static Exception ParallelTransactionsNotSupported(DbConnection obj)
 {
     return(InvalidOperation(SR.GetString(SR.ADP_ParallelTransactionsNotSupported, obj.GetType().Name)));
 }
예제 #22
0
 public static DbParameter[] GetCachedParameters(DbConnection dbConnection, string name)
 {
     if (dbConnection == null)
     {
         throw new ArgumentNullException("dbConn");
     }
     if (string.IsNullOrEmpty(name))
     {
         throw new ArgumentNullException("spName");
     }
     string str = name + "###" + dbConnection.ConnectionString + "###" + dbConnection.GetType().ToString();
     DbParameter[] parameterArray = hashtable[str] as DbParameter[];
     if (parameterArray == null)
     {
         lock (hashtable.SyncRoot)
         {
             parameterArray = hashtable[str] as DbParameter[];
             if (parameterArray == null)
             {
                 parameterArray = DeriveParameters(dbConnection, name);
                 hashtable[str] = parameterArray;
             }
         }
     }
     return CloneParameters(parameterArray);
 }
        private static MetadataWorkspace GetProviderSchemaMetadataWorkspace(DbProviderServices providerServices, DbConnection providerConnection, Version targetEntityFrameworkVersion)
        {
            XmlReader csdl = null;
            XmlReader ssdl = null;
            XmlReader msl = null;

            Debug.Assert(EntityFrameworkVersions.IsValidVersion(targetEntityFrameworkVersion), "EntityFrameworkVersions.IsValidVersion(targetEntityFrameworkVersion)");
            string csdlName;
            string ssdlName;
            string mslName;
            if (targetEntityFrameworkVersion >= EntityFrameworkVersions.Version3)
            {
                csdlName = DbProviderManifest.ConceptualSchemaDefinitionVersion3;
                ssdlName = DbProviderManifest.StoreSchemaDefinitionVersion3;
                mslName = DbProviderManifest.StoreSchemaMappingVersion3;
            }
            else
            {
                csdlName = DbProviderManifest.ConceptualSchemaDefinition;
                ssdlName = DbProviderManifest.StoreSchemaDefinition;
                mslName = DbProviderManifest.StoreSchemaMapping;
            }

            try
            {
                // create the metadata workspace
                MetadataWorkspace workspace = new MetadataWorkspace();

                string manifestToken = providerServices.GetProviderManifestToken(providerConnection);
                DbProviderManifest providerManifest = providerServices.GetProviderManifest(manifestToken);

                // create the EdmItemCollection
                IList<EdmSchemaError> errors;
                ssdl = providerManifest.GetInformation(ssdlName);
                string location = Strings.DbProviderServicesInformationLocationPath(providerConnection.GetType().Name, ssdlName);
                List<string> ssdlLocations = new List<string>(1);
                ssdlLocations.Add(location);
                StoreItemCollection storeItemCollection = new StoreItemCollection(new XmlReader[] { ssdl }, ssdlLocations.AsReadOnly(), out errors);
                ThrowOnError(errors);
                workspace.RegisterItemCollection(storeItemCollection);

                csdl = DbProviderServices.GetConceptualSchemaDefinition(csdlName);
                location = Strings.DbProviderServicesInformationLocationPath(typeof(DbProviderServices).Name, csdlName);
                List<string> csdlLocations = new List<string>(1);
                csdlLocations.Add(location);
                EdmItemCollection edmItemCollection = new EdmItemCollection(new XmlReader[] { csdl }, csdlLocations.AsReadOnly(), out errors);
                ThrowOnError(errors);
                workspace.RegisterItemCollection(edmItemCollection);

                msl = providerManifest.GetInformation(mslName);
                location = Strings.DbProviderServicesInformationLocationPath(providerConnection.GetType().Name, DbProviderManifest.StoreSchemaMapping);
                List<string> mslLocations = new List<string>(1);
                mslLocations.Add(location);
                StorageMappingItemCollection mappingItemCollection = new StorageMappingItemCollection(edmItemCollection,
                                                                         storeItemCollection,
                                                                         new XmlReader[] { msl },
                                                                         mslLocations,
                                                                         out errors);
                ThrowOnError(errors);
                workspace.RegisterItemCollection(mappingItemCollection);

                // make the views generate here so we can wrap the provider schema problems
                // in a ProviderIncompatibleException
                ForceViewGeneration(workspace);
                return workspace;
            }
            catch (ProviderIncompatibleException)
            {
                // we don't really want to catch this one, just rethrow it
                throw;
            }
            catch (Exception e)
            {
                if (MetadataUtil.IsCatchableExceptionType(e))
                {
                    throw EDesignUtil.ProviderIncompatible(Strings.ProviderSchemaErrors, e);
                }

                throw;
            }
            finally
            {
                if (csdl != null) ((IDisposable)csdl).Dispose();
                if (ssdl != null) ((IDisposable)ssdl).Dispose();
                if (msl != null) ((IDisposable)msl).Dispose();
            }
        }
예제 #24
0
 private void btnOpen_Click(object sender, EventArgs e)
 {
     btnClose_Click(sender, null);
     // main.
     string sFactory = cboProvider.Text.Trim();
     try {
         m_provider = DbProviderFactories.GetFactory(sFactory);
     }
     catch (Exception ex) {
         OutLog(ex.Message);
         MessageBox.Show(this, ex.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     if (null == m_provider) return;
     try {
         // DbConnection.
         try {
             OutLog("Create DbConnection:");
             m_conn = m_provider.CreateConnection();
             OutLog(string.Format("\t{0}", m_conn.GetType().ToString()));
         }
         catch (Exception ex) {
             OutLog(ex.Message);
             MessageBox.Show(this, ex.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
             try {
                 m_conn.Dispose();
             }
             catch (Exception ex2) {
                 OutLog(ex2.ToString());
             }
             m_conn = null;
             return;
         }
         if (null == m_conn) return;
         // open.
         try {
             m_conn.ConnectionString = txtConnstr.Text.Trim();
             m_conn.Open();
         }
         catch (Exception ex) {
             OutLog(ex.Message);
             MessageBox.Show(this, ex.ToString(), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
             try {
                 m_conn.Dispose();
             }
             catch (Exception ex2) {
                 OutLog(ex2.ToString());
             }
             m_conn = null;
             return;
         }
     }
     finally {
         if (null == m_conn) {
             m_provider = null;
         }
     }
     // done.
     bool isconn = true;
     btnOpen.Enabled = !isconn;
     btnClose.Enabled = isconn;
     btnExec.Enabled = isconn;
     cboProvider.Enabled = !isconn;
     txtConnstr.ReadOnly = isconn;
     OutLog("Db opened.");
     // show tables.
     DataTable dt = m_conn.GetSchema("Tables");
     grdTable.DataSource = dt;
     m_CurTableName = null;
     tbcInput.SelectedIndex = 1;
 }
        protected override DataTable StoredProcedureArguments(string storedProcedureName, DbConnection connection)
        {
            //for latest Devart (8.4.254.0, possibly some earlier versions)
            //the GetSchema for ALL_ARGUMENTS doesn't get package parameters unless specified
            //Devart.Data.Oracle.a4, method m
            if (connection.GetType().FullName.StartsWith("Devart", StringComparison.OrdinalIgnoreCase))
            {
                //don't filter by package. This is approximately the same as System.Data.OracleClient
                const string sqlCommand = @"SELECT
            OWNER, PACKAGE_NAME, OBJECT_NAME, ARGUMENT_NAME, POSITION, SEQUENCE, DEFAULT_VALUE, DEFAULT_LENGTH,
            IN_OUT, DATA_LENGTH, DATA_PRECISION, DATA_SCALE , DATA_TYPE
            FROM ALL_ARGUMENTS
            WHERE
            (OWNER= :schemaOwner OR :schemaOwner is null) AND
            (OBJECT_NAME = :PROCEDURENAME OR :PROCEDURENAME is null)";
                var dt = CreateDataTable("Arguments");
                using (DbDataAdapter da = Factory.CreateDataAdapter())
                {
                    using (DbCommand cmd = connection.CreateCommand())
                    {
                        cmd.CommandText = sqlCommand;

                        EnsureOracleBindByName(cmd);

                        cmd.Parameters.Add(
                            AddDbParameter("schemaOwner", Owner));
                        cmd.Parameters.Add(
                            AddDbParameter("PROCEDURENAME", storedProcedureName));
                        da.SelectCommand = cmd;

                        da.Fill(dt);
                    }
                }
                return dt;
            }
            return base.StoredProcedureArguments(storedProcedureName, connection);
        }
예제 #26
0
        public static ISqlDialect For(DbConnection connection)
        {
            string connectionName = connection.GetType().Name.ToLower();

            ISqlDialect dialect = null;

            if (!SqlDialects.TryGetValue(connectionName, out dialect))
            {
                throw new ArgumentException("Unknown connection name: " + connectionName);
            }

            return dialect;
        }
예제 #27
0
        internal static void Run(DbProviderFactory fact, DbConnection cnn)
        {
            Console.WriteLine("\r\nBeginning Test on " + cnn.GetType().ToString());
              try { CreateTable(cnn); Console.WriteLine("SUCCESS - CreateTable"); }
              catch (Exception) { Console.WriteLine("FAIL - CreateTable"); }

              try { TransactionTest(cnn); Console.WriteLine("SUCCESS - Transaction Enlistment"); }
              catch (Exception) { Console.WriteLine("FAIL - Transaction Enlistment"); }

              try { GuidTest(cnn); Console.WriteLine("SUCCESS - Guid Test"); }
              catch (Exception) { Console.WriteLine("FAIL - Guid Test"); }

              try { InsertTable(cnn); Console.WriteLine("SUCCESS - InsertTable"); }
              catch (Exception) { Console.WriteLine("FAIL - InsertTable"); }

              try { VerifyInsert(cnn); Console.WriteLine("SUCCESS - VerifyInsert"); }
              catch (Exception) { Console.WriteLine("FAIL - VerifyInsert"); }

              try { CoersionTest(cnn); Console.WriteLine("FAIL - CoersionTest"); }
              catch (Exception) { Console.WriteLine("SUCCESS - CoersionTest"); }

              try { ParameterizedInsert(cnn); Console.WriteLine("SUCCESS - ParameterizedInsert"); }
              catch (Exception) { Console.WriteLine("FAIL - ParameterizedInsert"); }

              try { BinaryInsert(cnn); Console.WriteLine("SUCCESS - BinaryInsert (using named parameter)"); }
              catch (Exception) { Console.WriteLine("FAIL - BinaryInsert"); }

              try { VerifyBinaryData(cnn); Console.WriteLine("SUCCESS - VerifyBinaryData"); }
              catch (Exception) { Console.WriteLine("FAIL - VerifyBinaryData"); }

              try { LockTest(cnn); Console.WriteLine("SUCCESS - LockTest"); }
              catch (Exception) { Console.WriteLine("FAIL - LockTest"); }

              try { ParameterizedInsertMissingParams(cnn); Console.WriteLine("FAIL - ParameterizedInsertMissingParams\r\n"); }
              catch (Exception) { Console.WriteLine("SUCCESS - ParameterizedInsertMissingParams\r\n"); }

            //      try { TimeoutTest(cnn); Console.WriteLine("SUCCESS - TimeoutTest"); }
            //      catch (Exception) { Console.WriteLine("FAIL - TimeoutTest"); }

              try { DataAdapter(fact, cnn, false); Console.WriteLine(""); }
              catch (Exception) { Console.WriteLine("FAIL - DataAdapter"); }

              try { DataAdapter(fact, cnn, true); Console.WriteLine(""); }
              catch (Exception) { Console.WriteLine("FAIL - DataAdapterWithIdentityFetch"); }

              try { FastInsertMany(cnn); Console.WriteLine(""); }
              catch (Exception) { Console.WriteLine("FAIL - FastInsertMany"); }

              try { IterationTest(cnn); Console.WriteLine(""); }
              catch (Exception) { Console.WriteLine("FAIL - Iteration Test"); }

              try { UserFunction(cnn); Console.WriteLine(""); }
              catch (Exception) { Console.WriteLine("FAIL - UserFunction"); }

              try { UserAggregate(cnn); Console.WriteLine(""); }
              catch (Exception) { Console.WriteLine("FAIL - UserAggregate"); }

              try { UserCollation(cnn); Console.WriteLine("SUCCESS - UserCollation"); }
              catch (Exception) { Console.WriteLine("FAIL - UserCollation"); }

              try { DropTable(cnn); Console.WriteLine("SUCCESS - DropTable"); }
              catch (Exception) { Console.WriteLine("FAIL - DropTable"); }

              Console.WriteLine("\r\nTests Finished.");
        }
예제 #28
0
 /// <summary>
 ///     Retrieve the DbProviderFactory based on the specified DbConnection
 /// </summary>
 /// <param name="connection"> The DbConnection to use </param>
 /// <returns> An instance of DbProviderFactory </returns>
 public static DbProviderFactory GetProviderFactory(DbConnection connection)
 {
     Contract.Requires(connection != null);
     var factory = DbProviderFactories.GetFactory(connection);
     if (factory == null)
     {
         throw new ProviderIncompatibleException(
             Strings.EntityClient_ReturnedNullOnProviderMethod(
                 "get_ProviderFactory",
                 connection.GetType().ToString()));
     }
     Contract.Assert(factory != null, "Should have thrown on null");
     return factory;
 }
예제 #29
0
		private void CreateDBConnectionFieldAndProperty (CodeTypeDeclaration t, DbConnection conn)
		{
			CodeExpression expr;
			CodeStatement setStmt;
			CodeStatement stmt;
			CodeMemberField f = new CodeMemberField ();
			f.Name = "_connection";
			f.Type = TypeRef (conn.GetType ());
			t.Members.Add (f);

			CodeMemberProperty p = new CodeMemberProperty ();
			p.Name = "Connection";
			p.Attributes = MemberAttributes.Assembly;
			p.Type = f.Type;

			expr = FieldRef ("_connection");
			setStmt = Eval (MethodInvoke ("InitConnection"));
			stmt = new CodeConditionStatement (Equals (expr, Const (null)),
			                                   new CodeStatement [] {setStmt},
			                                   new CodeStatement [] {});
			p.GetStatements.Add (stmt);
			p.GetStatements.Add (Return (expr));
			p.SetStatements.Add (Let (expr, new CodePropertySetValueReferenceExpression()));

			// update connection in Insert/Delete/Update commands of adapter
						
			// insert command
			string cmdStr = "InsertCommand";
			string connStr = "Connection";
			setStmt = null;
			stmt = null;
			expr = null;

			expr = PropRef (PropRef ("Adapter"), cmdStr);
			setStmt = Let (PropRef (expr, connStr), new CodePropertySetValueReferenceExpression());
			stmt = new CodeConditionStatement (Inequals (expr, Const (null)),
			                                   new CodeStatement [] {setStmt},
			                                   new CodeStatement [] {});			
			p.SetStatements.Add (stmt);

			// delete command
			setStmt = null;
			stmt = null;
			expr = null;
			
			cmdStr = "DeleteCommand";
			expr = PropRef (PropRef ("Adapter"), cmdStr);
			setStmt = Let (PropRef (expr, connStr), new CodePropertySetValueReferenceExpression());
			stmt = new CodeConditionStatement (Inequals (expr, Const (null)),
			                                   new CodeStatement [] {setStmt}, new CodeStatement [] {});
			p.SetStatements.Add (stmt);

			// update command
			setStmt = null;
			stmt = null;

			cmdStr = "UpdateCommand";
			expr = PropRef (PropRef ("Adapter"), cmdStr);			
			setStmt = Let (PropRef (expr, connStr), new CodePropertySetValueReferenceExpression());
			stmt = new CodeConditionStatement (Inequals (expr, Const (null)),
			                                   new CodeStatement [] {setStmt}, new CodeStatement [] {});
			p.SetStatements.Add (stmt);

			// iterate through command collection and update it
			setStmt = null;
			expr = null;
			stmt = null;
			setStmt = VarDecl (typeof (int), "i", Const (0));
			expr = LessThan (Local ("i"), PropRef (PropRef ("CommandCollection"), "Length"));
			stmt = Let (Local ("i"), Compute (Local ("i"), Const (1), CodeBinaryOperatorType.Add));
			
			// statements to execute in the loop
			CodeExpression expr1 = IndexerRef (PropRef ("CommandCollection"), Local ("i"));
			CodeStatement setStmt1 = Let (PropRef (expr1, "Connection"), new CodePropertySetValueReferenceExpression());
			CodeStatement stmt1 = new CodeConditionStatement (Inequals (expr1, Const (null)),
			                                   new CodeStatement [] {setStmt1}, new CodeStatement [] {});
			CodeIterationStatement forLoop = new CodeIterationStatement (setStmt, expr, stmt,
			                                                             new CodeStatement[] {stmt1});
			p.SetStatements.Add (forLoop);						
			t.Members.Add (p);
		}
예제 #30
0
 //
 // : IDbTransaction
 //
 static internal Exception ParallelTransactionsNotSupported(DbConnection obj)
 {
     return InvalidOperation(Res.GetString(Res.ADP_ParallelTransactionsNotSupported, obj.GetType().Name));
 }
예제 #31
0
 /// <summary>
 /// Retrieve the DbProviderFactory based on the specified DbConnection
 /// </summary>
 /// <param name="connection">The DbConnection to use</param>
 /// <returns>An instance of DbProviderFactory</returns>
 public static DbProviderFactory GetProviderFactory(DbConnection connection)
 {
     EntityUtil.CheckArgumentNull(connection, "connection");
     DbProviderFactory factory = DbProviderFactories.GetFactory(connection);
     if (factory == null)
     {
         throw EntityUtil.ProviderIncompatible(System.Data.Entity.Strings.EntityClient_ReturnedNullOnProviderMethod(
                 "get_ProviderFactory",
                 connection.GetType().ToString()));
     }
     Debug.Assert(factory != null, "Should have thrown on null"); 
     return factory;
 }
예제 #32
0
        /// <summary>
        /// 关闭连接
        /// </summary>
        /// <param name="connection"></param>
        public static void CloseConnection(DbConnection connection)
        {
            if (connection != null && connection.State != ConnectionState.Closed)
            {
                connection.Close();

                if (connection.GetType().FullName.Equals("System.Data.SqlClient.SqlConnection"))
                {
                    ExcelUtility.sqlConnection.Dispose();
                    ExcelUtility.sqlConnectionString = String.Empty;
                }
                else if (connection.GetType().FullName.Equals("System.Data.OleDb.OleDbConnection"))
                {
                    ExcelUtility.oleConnection.Dispose();
                    ExcelUtility.oleConnectionString = String.Empty;
                }
            }
        }
 public DbProviderFactory GetProviderFactory(DbConnection connection)
 {
     return connection.GetType().FullName.StartsWith("Castle.Proxies.")
                ? (DbProviderFactory)_factoryProperty.GetValue(connection, null)
                : _originalProviderFactoryService.GetProviderFactory(connection);
 }
예제 #34
0
 public DbProviderFactory GetProviderFactory(DbConnection cx)
 {
     if (cx == null)
     {
         return this.GetProviderFactory();
     }
     PropertyInfo property = cx.GetType().GetProperty("DbProviderFactory", BindingFlags.NonPublic | BindingFlags.Instance);
     if (property == null)
     {
         return this.GetProviderFactory();
     }
     try
     {
         return (((DbProviderFactory) property.GetValue(cx, null)) ?? this.GetProviderFactory());
     }
     catch
     {
         return this.GetProviderFactory();
     }
 }