Esempio n. 1
0
        public static IDBAccess Create(DBType type)
        {
            IDBAccess IRet = null;
            switch (type)
            {
                case DBType.Access:
                    IRet = new Access(type);
                    break;

                case DBType.SQL:
                    IRet = new SQL(type);
                    break;

                default:
                    break;
            }
            return IRet;
        }
Esempio n. 2
0
        override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
        {
            SqlConnectionString   opt    = (SqlConnectionString)options;
            SqlConnectionPoolKey  key    = (SqlConnectionPoolKey)poolKey;
            SqlInternalConnection result = null;
            SessionData           recoverySessionData = null;

            SqlConnection sqlOwningConnection         = (SqlConnection)owningConnection;
            bool          applyTransientFaultHandling = sqlOwningConnection != null ? sqlOwningConnection._applyTransientFaultHandling : false;

            SqlConnectionString userOpt = null;

            if (userOptions != null)
            {
                userOpt = (SqlConnectionString)userOptions;
            }
            else if (sqlOwningConnection != null)
            {
                userOpt = (SqlConnectionString)(sqlOwningConnection.UserConnectionOptions);
            }

            if (sqlOwningConnection != null)
            {
                recoverySessionData = sqlOwningConnection._recoverySessionData;
            }

            bool redirectedUserInstance       = false;
            DbConnectionPoolIdentity identity = null;

            // Pass DbConnectionPoolIdentity to SqlInternalConnectionTds if using integrated security.
            // Used by notifications.
            if (opt.IntegratedSecurity)
            {
                if (pool != null)
                {
                    identity = pool.Identity;
                }
                else
                {
                    identity = DbConnectionPoolIdentity.GetCurrent();
                }
            }

            // FOLLOWING IF BLOCK IS ENTIRELY FOR SSE USER INSTANCES
            // If "user instance=true" is in the connection string, we're using SSE user instances
            if (opt.UserInstance)
            {
                // opt.DataSource is used to create the SSE connection
                redirectedUserInstance = true;
                string instanceName;

                if ((null == pool) ||
                    (null != pool && pool.Count <= 0))
                { // Non-pooled or pooled and no connections in the pool.
                    SqlInternalConnectionTds sseConnection = null;
                    try
                    {
                        // We throw an exception in case of a failure
                        // NOTE: Cloning connection option opt to set 'UserInstance=True' and 'Enlist=False'
                        //       This first connection is established to SqlExpress to get the instance name
                        //       of the UserInstance.
                        SqlConnectionString sseopt = new SqlConnectionString(opt, opt.DataSource, userInstance: true, setEnlistValue: false);
                        sseConnection = new SqlInternalConnectionTds(identity, sseopt, null, false, applyTransientFaultHandling: applyTransientFaultHandling);
                        // NOTE: Retrieve <UserInstanceName> here. This user instance name will be used below to connect to the Sql Express User Instance.
                        instanceName = sseConnection.InstanceName;

                        if (!instanceName.StartsWith("\\\\.\\", StringComparison.Ordinal))
                        {
                            throw SQL.NonLocalSSEInstance();
                        }

                        if (null != pool)
                        { // Pooled connection - cache result
                            SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo;
                            // No lock since we are already in creation mutex
                            providerInfo.InstanceName = instanceName;
                        }
                    }
                    finally
                    {
                        if (null != sseConnection)
                        {
                            sseConnection.Dispose();
                        }
                    }
                }
                else
                { // Cached info from pool.
                    SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo;
                    // No lock since we are already in creation mutex
                    instanceName = providerInfo.InstanceName;
                }

                // NOTE: Here connection option opt is cloned to set 'instanceName=<UserInstanceName>' that was
                //       retrieved from the previous SSE connection. For this UserInstance connection 'Enlist=True'.
                // options immutable - stored in global hash - don't modify
                opt = new SqlConnectionString(opt, instanceName, userInstance: false, setEnlistValue: null);
                poolGroupProviderInfo = null; // null so we do not pass to constructor below...
            }
            result = new SqlInternalConnectionTds(identity, opt, poolGroupProviderInfo, redirectedUserInstance, userOpt, recoverySessionData, applyTransientFaultHandling: applyTransientFaultHandling);
            return(result);
        }
        internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms(), false)
        {
            bool inProc = InOutOfProcHelper.InProc;

            this._integratedSecurity = base.ConvertValueToIntegratedSecurity();
            this._async             = base.ConvertValueToBoolean("asynchronous processing", false);
            this._connectionReset   = base.ConvertValueToBoolean("connection reset", true);
            this._contextConnection = base.ConvertValueToBoolean("context connection", false);
            this._encrypt           = base.ConvertValueToBoolean("encrypt", false);
            this._enlist            = base.ConvertValueToBoolean("enlist", ADP.IsWindowsNT);
            this._mars = base.ConvertValueToBoolean("multipleactiveresultsets", false);
            this._persistSecurityInfo    = base.ConvertValueToBoolean("persist security info", false);
            this._pooling                = base.ConvertValueToBoolean("pooling", true);
            this._replication            = base.ConvertValueToBoolean("replication", false);
            this._userInstance           = base.ConvertValueToBoolean("user instance", false);
            this._multiSubnetFailover    = base.ConvertValueToBoolean("multisubnetfailover", false);
            this._connectTimeout         = base.ConvertValueToInt32("connect timeout", 15);
            this._loadBalanceTimeout     = base.ConvertValueToInt32("load balance timeout", 0);
            this._maxPoolSize            = base.ConvertValueToInt32("max pool size", 100);
            this._minPoolSize            = base.ConvertValueToInt32("min pool size", 0);
            this._packetSize             = base.ConvertValueToInt32("packet size", 0x1f40);
            this._applicationIntent      = this.ConvertValueToApplicationIntent();
            this._applicationName        = base.ConvertValueToString("application name", ".Net SqlClient Data Provider");
            this._attachDBFileName       = base.ConvertValueToString("attachdbfilename", "");
            this._currentLanguage        = base.ConvertValueToString("current language", "");
            this._dataSource             = base.ConvertValueToString("data source", "");
            this._localDBInstance        = LocalDBAPI.GetLocalDbInstanceNameFromServerName(this._dataSource);
            this._failoverPartner        = base.ConvertValueToString("failover partner", "");
            this._initialCatalog         = base.ConvertValueToString("initial catalog", "");
            this._networkLibrary         = base.ConvertValueToString("network library", null);
            this._password               = base.ConvertValueToString("password", "");
            this._trustServerCertificate = base.ConvertValueToBoolean("trustservercertificate", false);
            string str  = base.ConvertValueToString("type system version", null);
            string str2 = base.ConvertValueToString("transaction binding", null);

            this._userID        = base.ConvertValueToString("user id", "");
            this._workstationId = base.ConvertValueToString("workstation id", null);
            if (this._contextConnection)
            {
                if (!inProc)
                {
                    throw SQL.ContextUnavailableOutOfProc();
                }
                foreach (DictionaryEntry entry in base.Parsetable)
                {
                    if ((((string)entry.Key) != "context connection") && (((string)entry.Key) != "type system version"))
                    {
                        throw SQL.ContextAllowsLimitedKeywords();
                    }
                }
            }
            if (!this._encrypt)
            {
                object obj2 = ADP.LocalMachineRegistryValue(@"Software\Microsoft\MSSQLServer\Client\SuperSocketNetLib", "Encrypt");
                if ((obj2 is int) && (1 == ((int)obj2)))
                {
                    this._encrypt = true;
                }
            }
            if (this._loadBalanceTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue("load balance timeout");
            }
            if (this._connectTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue("connect timeout");
            }
            if (this._maxPoolSize < 1)
            {
                throw ADP.InvalidConnectionOptionValue("max pool size");
            }
            if (this._minPoolSize < 0)
            {
                throw ADP.InvalidConnectionOptionValue("min pool size");
            }
            if (this._maxPoolSize < this._minPoolSize)
            {
                throw ADP.InvalidMinMaxPoolSizeValues();
            }
            if ((this._packetSize < 0x200) || (0x8000 < this._packetSize))
            {
                throw SQL.InvalidPacketSizeValue();
            }
            if (this._networkLibrary != null)
            {
                string    key       = this._networkLibrary.Trim().ToLower(CultureInfo.InvariantCulture);
                Hashtable hashtable = NetlibMapping();
                if (!hashtable.ContainsKey(key))
                {
                    throw ADP.InvalidConnectionOptionValue("network library");
                }
                this._networkLibrary = (string)hashtable[key];
            }
            else
            {
                this._networkLibrary = "";
            }
            this.ValidateValueLength(this._applicationName, 0x80, "application name");
            this.ValidateValueLength(this._currentLanguage, 0x80, "current language");
            this.ValidateValueLength(this._dataSource, 0x80, "data source");
            this.ValidateValueLength(this._failoverPartner, 0x80, "failover partner");
            this.ValidateValueLength(this._initialCatalog, 0x80, "initial catalog");
            this.ValidateValueLength(this._password, 0x80, "password");
            this.ValidateValueLength(this._userID, 0x80, "user id");
            if (this._workstationId != null)
            {
                this.ValidateValueLength(this._workstationId, 0x80, "workstation id");
            }
            if (!string.Equals("", this._failoverPartner, StringComparison.OrdinalIgnoreCase))
            {
                if (this._multiSubnetFailover)
                {
                    bool serverProvidedFailoverPartner = false;
                    throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner);
                }
                if (string.Equals("", this._initialCatalog, StringComparison.OrdinalIgnoreCase))
                {
                    throw ADP.MissingConnectionOptionValue("failover partner", "initial catalog");
                }
            }
            string datadir = null;

            this._expandedAttachDBFilename = DbConnectionOptions.ExpandDataDirectory("attachdbfilename", this._attachDBFileName, ref datadir);
            if (this._expandedAttachDBFilename != null)
            {
                if (0 <= this._expandedAttachDBFilename.IndexOf('|'))
                {
                    throw ADP.InvalidConnectionOptionValue("attachdbfilename");
                }
                this.ValidateValueLength(this._expandedAttachDBFilename, 260, "attachdbfilename");
                if (this._localDBInstance == null)
                {
                    string host     = this._dataSource;
                    string protocol = this._networkLibrary;
                    TdsParserStaticMethods.AliasRegistryLookup(ref host, ref protocol);
                    VerifyLocalHostAndFixup(ref host, true, false);
                }
            }
            else
            {
                if (0 <= this._attachDBFileName.IndexOf('|'))
                {
                    throw ADP.InvalidConnectionOptionValue("attachdbfilename");
                }
                this.ValidateValueLength(this._attachDBFileName, 260, "attachdbfilename");
            }
            if (this._async && inProc)
            {
                throw SQL.AsyncInProcNotSupported();
            }
            if (this._userInstance && !ADP.IsEmpty(this._failoverPartner))
            {
                throw SQL.UserInstanceFailoverNotCompatible();
            }
            if (ADP.IsEmpty(str))
            {
                str = "Latest";
            }
            if (str.Equals("Latest", StringComparison.OrdinalIgnoreCase))
            {
                this._typeSystemVersion = TypeSystem.Latest;
            }
            else if (str.Equals("SQL Server 2000", StringComparison.OrdinalIgnoreCase))
            {
                if (this._contextConnection)
                {
                    throw SQL.ContextAllowsOnlyTypeSystem2005();
                }
                this._typeSystemVersion = TypeSystem.SQLServer2000;
            }
            else if (str.Equals("SQL Server 2005", StringComparison.OrdinalIgnoreCase))
            {
                this._typeSystemVersion = TypeSystem.SQLServer2005;
            }
            else
            {
                if (!str.Equals("SQL Server 2008", StringComparison.OrdinalIgnoreCase))
                {
                    throw ADP.InvalidConnectionOptionValue("type system version");
                }
                this._typeSystemVersion = TypeSystem.Latest;
            }
            if (ADP.IsEmpty(str2))
            {
                str2 = "Implicit Unbind";
            }
            if (str2.Equals("Implicit Unbind", StringComparison.OrdinalIgnoreCase))
            {
                this._transactionBinding = TransactionBindingEnum.ImplicitUnbind;
            }
            else
            {
                if (!str2.Equals("Explicit Unbind", StringComparison.OrdinalIgnoreCase))
                {
                    throw ADP.InvalidConnectionOptionValue("transaction binding");
                }
                this._transactionBinding = TransactionBindingEnum.ExplicitUnbind;
            }
            if ((this._applicationIntent == System.Data.SqlClient.ApplicationIntent.ReadOnly) && !string.IsNullOrEmpty(this._failoverPartner))
            {
                throw SQL.ROR_FailoverNotSupportedConnString();
            }
        }
        private void EnlistNonNull(Transaction tx)
        {
            if (Bid.AdvancedOn)
            {
                Bid.Trace("<sc.SqlInternalConnection.EnlistNonNull|ADV> %d#, transaction %d#.\n", base.ObjectID, tx.GetHashCode());
            }
            bool flag = false;

            if (this.IsYukonOrNewer)
            {
                if (Bid.AdvancedOn)
                {
                    Bid.Trace("<sc.SqlInternalConnection.EnlistNonNull|ADV> %d#, attempting to delegate\n", base.ObjectID);
                }
                SqlDelegatedTransaction promotableSinglePhaseNotification = new SqlDelegatedTransaction(this, tx);
                try
                {
                    if (tx.EnlistPromotableSinglePhase(promotableSinglePhaseNotification))
                    {
                        flag = true;
                        this.DelegatedTransaction = promotableSinglePhaseNotification;
                        if (Bid.AdvancedOn)
                        {
                            long transactionId = 0L;
                            int  objectID      = 0;
                            if (this.CurrentTransaction != null)
                            {
                                transactionId = this.CurrentTransaction.TransactionId;
                                objectID      = this.CurrentTransaction.ObjectID;
                            }
                            Bid.Trace("<sc.SqlInternalConnection.EnlistNonNull|ADV> %d#, delegated to transaction %d# with transactionId=0x%I64x\n", base.ObjectID, objectID, transactionId);
                        }
                    }
                }
                catch (SqlException exception)
                {
                    if (exception.Class >= 20)
                    {
                        throw;
                    }
                    SqlInternalConnectionTds tds = this as SqlInternalConnectionTds;
                    if (tds != null)
                    {
                        TdsParser parser = tds.Parser;
                        if ((parser == null) || (parser.State != TdsParserState.OpenLoggedIn))
                        {
                            throw;
                        }
                    }
                    ADP.TraceExceptionWithoutRethrow(exception);
                }
            }
            if (!flag)
            {
                if (Bid.AdvancedOn)
                {
                    Bid.Trace("<sc.SqlInternalConnection.EnlistNonNull|ADV> %d#, delegation not possible, enlisting.\n", base.ObjectID);
                }
                byte[] transactionCookie = null;
                if (this._whereAbouts == null)
                {
                    byte[] dTCAddress = this.GetDTCAddress();
                    if (dTCAddress == null)
                    {
                        throw SQL.CannotGetDTCAddress();
                    }
                    this._whereAbouts = dTCAddress;
                }
                transactionCookie = GetTransactionCookie(tx, this._whereAbouts);
                this.PropagateTransactionCookie(transactionCookie);
                this._isEnlistedInTransaction = true;
                if (Bid.AdvancedOn)
                {
                    long num2 = 0L;
                    int  num  = 0;
                    if (this.CurrentTransaction != null)
                    {
                        num2 = this.CurrentTransaction.TransactionId;
                        num  = this.CurrentTransaction.ObjectID;
                    }
                    Bid.Trace("<sc.SqlInternalConnection.EnlistNonNull|ADV> %d#, enlisted with transaction %d# with transactionId=0x%I64x\n", base.ObjectID, num, num2);
                }
            }
            base.EnlistedTransaction = tx;
        }
        private void WriteToServerInternal()
        {
            string tDSCommand = null;
            bool   flag3      = false;
            bool   flag2      = false;

            int[] useSqlValue = null;
            int   num5        = this._batchSize;
            bool  flag4       = false;

            if (this._batchSize > 0)
            {
                flag4 = true;
            }
            Exception inner = null;

            this._rowsCopied = 0;
            if (this._destinationTableName == null)
            {
                throw SQL.BulkLoadMissingDestinationTable();
            }
            if (this.ReadFromRowSource())
            {
                RuntimeHelpers.PrepareConstrainedRegions();
                try
                {
                    bool flag = true;
                    this._parser   = this._connection.Parser;
                    this._stateObj = this._parser.GetSession(this);
                    this._stateObj._bulkCopyOpperationInProgress = true;
                    try
                    {
                        BulkCopySimpleResultSet set;
                        this._stateObj.StartSession(this.ObjectID);
                        try
                        {
                            set = this.CreateAndExecuteInitialQuery();
                        }
                        catch (SqlException exception5)
                        {
                            throw SQL.BulkLoadInvalidDestinationTable(this._destinationTableName, exception5);
                        }
                        this._rowsUntilNotification = this._notifyAfter;
                        tDSCommand = this.AnalyzeTargetAndCreateUpdateBulkCommand(set);
                        if (this._sortedColumnMappings.Count == 0)
                        {
                            return;
                        }
                        this._stateObj.SniContext = SniContext.Snix_SendRows;
Label_00DD:
                        if (this.IsCopyOption(SqlBulkCopyOptions.UseInternalTransaction))
                        {
                            this._internalTransaction = this._connection.BeginTransaction();
                        }
                        this.SubmitUpdateBulkCommand(set, tDSCommand);
                        try
                        {
                            this.WriteMetaData(set);
                            object[] objArray = new object[this._sortedColumnMappings.Count];
                            if (useSqlValue == null)
                            {
                                useSqlValue = new int[objArray.Length];
                            }
                            int num3 = num5;
                            do
                            {
                                for (int i = 0; i < objArray.Length; i++)
                                {
                                    _ColumnMapping mapping  = (_ColumnMapping)this._sortedColumnMappings[i];
                                    _SqlMetaData   metadata = mapping._metadata;
                                    object         obj2     = this.GetValueFromSourceRow(mapping._sourceColumnOrdinal, metadata, useSqlValue, i);
                                    objArray[i] = this.ConvertValue(obj2, metadata);
                                }
                                this._parser.WriteByte(0xd1, this._stateObj);
                                for (int j = 0; j < objArray.Length; j++)
                                {
                                    _ColumnMapping mapping2 = (_ColumnMapping)this._sortedColumnMappings[j];
                                    _SqlMetaData   data     = mapping2._metadata;
                                    if (data.type != SqlDbType.Variant)
                                    {
                                        this._parser.WriteBulkCopyValue(objArray[j], data, this._stateObj);
                                    }
                                    else
                                    {
                                        this._parser.WriteSqlVariantDataRowValue(objArray[j], this._stateObj);
                                    }
                                }
                                this._rowsCopied++;
                                if (((this._notifyAfter > 0) && (this._rowsUntilNotification > 0)) && (--this._rowsUntilNotification == 0))
                                {
                                    try
                                    {
                                        this._stateObj.BcpLock = true;
                                        flag2 = this.FireRowsCopiedEvent((long)this._rowsCopied);
                                        Bid.Trace("<sc.SqlBulkCopy.WriteToServerInternal|INFO> \n");
                                        if (ConnectionState.Open != this._connection.State)
                                        {
                                            goto Label_02F7;
                                        }
                                    }
                                    catch (Exception exception2)
                                    {
                                        if (!ADP.IsCatchableExceptionType(exception2))
                                        {
                                            throw;
                                        }
                                        inner = OperationAbortedException.Aborted(exception2);
                                        goto Label_02F7;
                                    }
                                    finally
                                    {
                                        this._stateObj.BcpLock = false;
                                    }
                                    if (flag2)
                                    {
                                        goto Label_02F7;
                                    }
                                    this._rowsUntilNotification = this._notifyAfter;
                                }
                                if (this._rowsUntilNotification > this._notifyAfter)
                                {
                                    this._rowsUntilNotification = this._notifyAfter;
                                }
                                flag3 = this.ReadFromRowSource();
                                if (flag4)
                                {
                                    num3--;
                                    if (num3 == 0)
                                    {
                                        goto Label_02F7;
                                    }
                                }
                            }while (flag3);
                        }
                        catch (NullReferenceException)
                        {
                            this._stateObj.CancelRequest();
                            throw;
                        }
                        catch (Exception exception4)
                        {
                            if (ADP.IsCatchableExceptionType(exception4))
                            {
                                this._stateObj.CancelRequest();
                            }
                            throw;
                        }
Label_02F7:
                        if (ConnectionState.Open != this._connection.State)
                        {
                            throw ADP.OpenConnectionRequired("WriteToServer", this._connection.State);
                        }
                        this._parser.WriteBulkCopyDone(this._stateObj);
                        this._parser.Run(RunBehavior.UntilDone, null, null, null, this._stateObj);
                        if (flag2 || (inner != null))
                        {
                            throw OperationAbortedException.Aborted(inner);
                        }
                        if (this._internalTransaction != null)
                        {
                            this._internalTransaction.Commit();
                            this._internalTransaction = null;
                        }
                        if (flag3)
                        {
                            goto Label_00DD;
                        }
                        this._localColumnMappings = null;
                    }
                    catch (Exception exception3)
                    {
                        flag = ADP.IsCatchableExceptionType(exception3);
                        if (flag)
                        {
                            this._stateObj._internalTimeout = false;
                            if (this._internalTransaction != null)
                            {
                                if (!this._internalTransaction.IsZombied)
                                {
                                    this._internalTransaction.Rollback();
                                }
                                this._internalTransaction = null;
                            }
                        }
                        throw;
                    }
                    finally
                    {
                        if (flag && (this._stateObj != null))
                        {
                            this._stateObj.CloseSession();
                        }
                    }
                }
                finally
                {
                    if (this._stateObj != null)
                    {
                        this._stateObj._bulkCopyOpperationInProgress = false;
                        this._stateObj = null;
                    }
                }
            }
        }
        private string AnalyzeTargetAndCreateUpdateBulkCommand(BulkCopySimpleResultSet internalResults)
        {
            bool hasLocalTransaction;

            this._sortedColumnMappings = new ArrayList();
            StringBuilder query = new StringBuilder();

            if (this._connection.IsShiloh && (internalResults[2].Count == 0))
            {
                throw SQL.BulkLoadNoCollation();
            }
            query.Append("insert bulk " + this.DestinationTableName + " (");
            int num3 = 0;
            int num6 = 0;

            if (this._parser.IsYukonOrNewer)
            {
                hasLocalTransaction = this._connection.HasLocalTransaction;
            }
            else
            {
                hasLocalTransaction = 0 < ((SqlInt32)internalResults[0][0][0]);
            }
            if (((hasLocalTransaction && (this._externalTransaction == null)) && ((this._internalTransaction == null) && (this._connection.Parser != null))) && ((this._connection.Parser.CurrentTransaction != null) && this._connection.Parser.CurrentTransaction.IsLocal))
            {
                throw SQL.BulkLoadExistingTransaction();
            }
            for (int i = 0; i < internalResults[1].MetaData.Length; i++)
            {
                _SqlMetaData metadata = internalResults[1].MetaData[i];
                bool         flag2    = false;
                if ((metadata.type == SqlDbType.Timestamp) || (metadata.isIdentity && !this.IsCopyOption(SqlBulkCopyOptions.KeepIdentity)))
                {
                    internalResults[1].MetaData[i] = null;
                    flag2 = true;
                }
                int num = 0;
                while (num < this._localColumnMappings.Count)
                {
                    if ((this._localColumnMappings[num]._destinationColumnOrdinal == metadata.ordinal) || (this.UnquotedName(this._localColumnMappings[num]._destinationColumnName) == metadata.column))
                    {
                        if (flag2)
                        {
                            num6++;
                            break;
                        }
                        this._sortedColumnMappings.Add(new _ColumnMapping(this._localColumnMappings[num]._internalSourceColumnOrdinal, metadata));
                        num3++;
                        if (num3 > 1)
                        {
                            query.Append(", ");
                        }
                        if (metadata.type == SqlDbType.Variant)
                        {
                            this.AppendColumnNameAndTypeName(query, metadata.column, "sql_variant");
                        }
                        else if (metadata.type == SqlDbType.Udt)
                        {
                            this.AppendColumnNameAndTypeName(query, metadata.column, "varbinary");
                        }
                        else
                        {
                            this.AppendColumnNameAndTypeName(query, metadata.column, metadata.type.ToString());
                        }
                        switch (metadata.metaType.NullableType)
                        {
                        case 0x29:
                        case 0x2a:
                        case 0x2b:
                            query.Append("(" + metadata.scale.ToString((IFormatProvider)null) + ")");
                            break;

                        case 0x6a:
                        case 0x6c:
                            query.Append("(" + metadata.precision.ToString((IFormatProvider)null) + "," + metadata.scale.ToString((IFormatProvider)null) + ")");
                            break;

                        case 240:
                            if (metadata.IsLargeUdt)
                            {
                                query.Append("(max)");
                            }
                            else
                            {
                                query.Append("(" + metadata.length.ToString((IFormatProvider)null) + ")");
                            }
                            break;

                        default:
                            if (!metadata.metaType.IsFixed && !metadata.metaType.IsLong)
                            {
                                int length = metadata.length;
                                switch (metadata.metaType.NullableType)
                                {
                                case 0x63:
                                case 0xe7:
                                case 0xef:
                                    length /= 2;
                                    break;
                                }
                                query.Append("(" + length.ToString((IFormatProvider)null) + ")");
                            }
                            else if (metadata.metaType.IsPlp && (metadata.metaType.SqlDbType != SqlDbType.Xml))
                            {
                                query.Append("(max)");
                            }
                            break;
                        }
                        if (!this._connection.IsShiloh)
                        {
                            break;
                        }
                        Result result = internalResults[2];
                        object obj2   = result[i][3];
                        if (obj2 == null)
                        {
                            break;
                        }
                        SqlString str = (SqlString)obj2;
                        if (str.IsNull)
                        {
                            break;
                        }
                        query.Append(" COLLATE " + str.ToString());
                        if ((this._SqlDataReaderRowSource == null) || (metadata.collation == null))
                        {
                            break;
                        }
                        int num9     = this._localColumnMappings[num]._internalSourceColumnOrdinal;
                        int lCID     = metadata.collation.LCID;
                        int localeId = this._SqlDataReaderRowSource.GetLocaleId(num9);
                        if (localeId == lCID)
                        {
                            break;
                        }
                        throw SQL.BulkLoadLcidMismatch(localeId, this._SqlDataReaderRowSource.GetName(num9), lCID, metadata.column);
                    }
                    num++;
                }
                if (num == this._localColumnMappings.Count)
                {
                    internalResults[1].MetaData[i] = null;
                }
            }
            if ((num3 + num6) != this._localColumnMappings.Count)
            {
                throw SQL.BulkLoadNonMatchingColumnMapping();
            }
            query.Append(")");
            if ((this._copyOptions & (SqlBulkCopyOptions.FireTriggers | SqlBulkCopyOptions.KeepNulls | SqlBulkCopyOptions.TableLock | SqlBulkCopyOptions.CheckConstraints)) != SqlBulkCopyOptions.Default)
            {
                bool flag = false;
                query.Append(" with (");
                if (this.IsCopyOption(SqlBulkCopyOptions.KeepNulls))
                {
                    query.Append("KEEP_NULLS");
                    flag = true;
                }
                if (this.IsCopyOption(SqlBulkCopyOptions.TableLock))
                {
                    query.Append((flag ? ", " : "") + "TABLOCK");
                    flag = true;
                }
                if (this.IsCopyOption(SqlBulkCopyOptions.CheckConstraints))
                {
                    query.Append((flag ? ", " : "") + "CHECK_CONSTRAINTS");
                    flag = true;
                }
                if (this.IsCopyOption(SqlBulkCopyOptions.FireTriggers))
                {
                    query.Append((flag ? ", " : "") + "FIRE_TRIGGERS");
                    flag = true;
                }
                query.Append(")");
            }
            return(query.ToString());
        }
        private BulkCopySimpleResultSet CreateAndExecuteInitialQuery()
        {
            string[] strArray;
            try
            {
                strArray = MultipartIdentifier.ParseMultipartIdentifier(this.DestinationTableName, "[\"", "]\"", "SQL_BulkCopyDestinationTableName", true);
            }
            catch (Exception exception)
            {
                throw SQL.BulkLoadInvalidDestinationTable(this.DestinationTableName, exception);
            }
            if (ADP.IsEmpty(strArray[3]))
            {
                throw SQL.BulkLoadInvalidDestinationTable(this.DestinationTableName, null);
            }
            BulkCopySimpleResultSet bulkCopyHandler = new BulkCopySimpleResultSet();
            string str3 = "select @@trancount; SET FMTONLY ON select * from " + this.DestinationTableName + " SET FMTONLY OFF ";

            if (this._connection.IsShiloh)
            {
                string str5;
                if (this._connection.IsKatmaiOrNewer)
                {
                    str5 = "sp_tablecollations_100";
                }
                else if (this._connection.IsYukonOrNewer)
                {
                    str5 = "sp_tablecollations_90";
                }
                else
                {
                    str5 = "sp_tablecollations";
                }
                string str  = strArray[3];
                bool   flag = (str.Length > 0) && ('#' == str[0]);
                if (!ADP.IsEmpty(str))
                {
                    str = SqlServerEscapeHelper.EscapeIdentifier(SqlServerEscapeHelper.EscapeStringAsLiteral(str));
                }
                string str2 = strArray[2];
                if (!ADP.IsEmpty(str2))
                {
                    str2 = SqlServerEscapeHelper.EscapeIdentifier(SqlServerEscapeHelper.EscapeStringAsLiteral(str2));
                }
                string str4 = strArray[1];
                if (flag && ADP.IsEmpty(str4))
                {
                    str3 = str3 + string.Format(null, "exec tempdb..{0} N'{1}.{2}'", new object[] { str5, str2, str });
                }
                else
                {
                    if (!ADP.IsEmpty(str4))
                    {
                        str4 = SqlServerEscapeHelper.EscapeIdentifier(str4);
                    }
                    str3 = str3 + string.Format(null, "exec {0}..{1} N'{2}.{3}'", new object[] { str4, str5, str2, str });
                }
            }
            Bid.Trace("<sc.SqlBulkCopy.CreateAndExecuteInitialQuery|INFO> Initial Query: '%ls' \n", str3);
            this._parser.TdsExecuteSQLBatch(str3, this.BulkCopyTimeout, null, this._stateObj);
            this._parser.Run(RunBehavior.UntilDone, null, null, bulkCopyHandler, this._stateObj);
            return(bulkCopyHandler);
        }
        private void WriteRowSourceToServer(int columnCount)
        {
            this.CreateOrValidateConnection("WriteToServer");
            bool flag = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            SNIHandle target = null;

            try
            {
                target = SqlInternalConnection.GetBestEffortCleanupTarget(this._connection);
                this._columnMappings.ReadOnly = true;
                this._localColumnMappings     = this._columnMappings;
                if (this._localColumnMappings.Count > 0)
                {
                    this._localColumnMappings.ValidateCollection();
                    foreach (SqlBulkCopyColumnMapping mapping2 in this._localColumnMappings)
                    {
                        if (mapping2._internalSourceColumnOrdinal == -1)
                        {
                            flag = true;
                            break;
                        }
                    }
                }
                else
                {
                    this._localColumnMappings = new SqlBulkCopyColumnMappingCollection();
                    this._localColumnMappings.CreateDefaultMapping(columnCount);
                }
                if (flag)
                {
                    int ordinal = -1;
                    flag = false;
                    if (this._localColumnMappings.Count > 0)
                    {
                        foreach (SqlBulkCopyColumnMapping mapping in this._localColumnMappings)
                        {
                            if (mapping._internalSourceColumnOrdinal != -1)
                            {
                                continue;
                            }
                            string name = this.UnquotedName(mapping.SourceColumn);
                            switch (this._rowSourceType)
                            {
                            case ValueSourceType.IDataReader:
                                try
                                {
                                    ordinal = ((IDataRecord)this._rowSource).GetOrdinal(name);
                                }
                                catch (IndexOutOfRangeException exception4)
                                {
                                    throw SQL.BulkLoadNonMatchingColumnName(name, exception4);
                                }
                                break;

                            case ValueSourceType.DataTable:
                                ordinal = ((DataTable)this._rowSource).Columns.IndexOf(name);
                                break;

                            case ValueSourceType.RowArray:
                                ordinal = ((DataRow[])this._rowSource)[0].Table.Columns.IndexOf(name);
                                break;
                            }
                            if (ordinal == -1)
                            {
                                throw SQL.BulkLoadNonMatchingColumnName(name);
                            }
                            mapping._internalSourceColumnOrdinal = ordinal;
                        }
                    }
                }
                this.WriteToServerInternal();
            }
            catch (OutOfMemoryException exception3)
            {
                this._connection.Abort(exception3);
                throw;
            }
            catch (StackOverflowException exception2)
            {
                this._connection.Abort(exception2);
                throw;
            }
            catch (ThreadAbortException exception)
            {
                this._connection.Abort(exception);
                SqlInternalConnection.BestEffortCleanup(target);
                throw;
            }
            finally
            {
                this._columnMappings.ReadOnly = false;
            }
        }
Esempio n. 9
0
        internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms())
        {
            ThrowUnsupportedIfKeywordSet(KEY.AsynchronousProcessing);
            ThrowUnsupportedIfKeywordSet(KEY.Connection_Reset);
            ThrowUnsupportedIfKeywordSet(KEY.Context_Connection);
            ThrowUnsupportedIfKeywordSet(KEY.TransactionBinding);

            // Network Library has its own special error message
            if (ContainsKey(KEY.Network_Library))
            {
                throw SQL.NetworkLibraryKeywordNotSupported();
            }

            _integratedSecurity = ConvertValueToIntegratedSecurity();
            _encrypt            = ConvertValueToBoolean(KEY.Encrypt, DEFAULT.Encrypt);
            _enlist             = ConvertValueToBoolean(KEY.Enlist, DEFAULT.Enlist);
            _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS);
            _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info);
            _pooling             = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling);
            _replication         = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication);
            _userInstance        = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance);
            _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover);

            _connectTimeout       = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout);
            _loadBalanceTimeout   = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout);
            _maxPoolSize          = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size);
            _minPoolSize          = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size);
            _packetSize           = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size);
            _connectRetryCount    = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count);
            _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval);

            _applicationIntent      = ConvertValueToApplicationIntent();
            _applicationName        = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name);
            _attachDBFileName       = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename);
            _currentLanguage        = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language);
            _dataSource             = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source);
            _localDBInstance        = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource);
            _failoverPartner        = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner);
            _initialCatalog         = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog);
            _password               = ConvertValueToString(KEY.Password, DEFAULT.Password);
            _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate);

            // Temporary string - this value is stored internally as an enum.
            string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null);

            _userID        = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID);
            _workstationId = ConvertValueToString(KEY.Workstation_Id, null);



            if (_loadBalanceTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout);
            }

            if (_connectTimeout < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout);
            }

            if (_maxPoolSize < 1)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size);
            }

            if (_minPoolSize < 0)
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size);
            }
            if (_maxPoolSize < _minPoolSize)
            {
                throw ADP.InvalidMinMaxPoolSizeValues();
            }

            if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize))
            {
                throw SQL.InvalidPacketSizeValue();
            }


            ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name);
            ValidateValueLength(_currentLanguage, TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language);
            ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source);
            ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner);
            ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog);
            ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password);
            ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID);
            if (null != _workstationId)
            {
                ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id);
            }

            if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase))
            {
                // fail-over partner is set

                if (_multiSubnetFailover)
                {
                    throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null);
                }

                if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase))
                {
                    throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog);
                }
            }

            if (0 <= _attachDBFileName.IndexOf('|'))
            {
                throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename);
            }
            else
            {
                ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename);
            }


            if (true == _userInstance && !string.IsNullOrEmpty(_failoverPartner))
            {
                throw SQL.UserInstanceFailoverNotCompatible();
            }

            if (string.IsNullOrEmpty(typeSystemVersionString))
            {
                typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion;
            }

            if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.Latest;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2000;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2005;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2008;
            }
            else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase))
            {
                _typeSystemVersion = TypeSystem.SQLServer2012;
            }
            else
            {
                throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version);
            }


            if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner))
            {
                throw SQL.ROR_FailoverNotSupportedConnString();
            }

            if ((_connectRetryCount < 0) || (_connectRetryCount > 255))
            {
                throw ADP.InvalidConnectRetryCountValue();
            }

            if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60))
            {
                throw ADP.InvalidConnectRetryIntervalValue();
            }
        }
        private object ConvertValue(object value, _SqlMetaData metadata)
        {
            object obj2;

            if (ADP.IsNull(value))
            {
                if (!metadata.isNullable)
                {
                    throw SQL.BulkLoadBulkLoadNotAllowDBNull(metadata.column);
                }
                return(value);
            }
            MetaType metaType = metadata.metaType;

            try
            {
                MetaType   metaTypeFromSqlDbType;
                SqlDecimal num2;
                switch (metaType.NullableType)
                {
                case 0x22:
                case 0x23:
                case 0x24:
                case 0x26:
                case 40:
                case 0x29:
                case 0x2a:
                case 0x2b:
                case 50:
                case 0x3a:
                case 0x3b:
                case 0x3d:
                case 0x3e:
                case 0x68:
                case 0x6d:
                case 110:
                case 0x6f:
                case 0xa5:
                case 0xa7:
                case 0xad:
                case 0xaf:
                    metaTypeFromSqlDbType = MetaType.GetMetaTypeFromSqlDbType(metaType.SqlDbType, false);
                    value = SqlParameter.CoerceValue(value, metaTypeFromSqlDbType);
                    goto Label_0290;

                case 0x62:
                    value = this.ValidateBulkCopyVariant(value);
                    goto Label_0290;

                case 0x63:
                case 0xef:
                case 0xe7:
                {
                    metaTypeFromSqlDbType = MetaType.GetMetaTypeFromSqlDbType(metaType.SqlDbType, false);
                    value = SqlParameter.CoerceValue(value, metaTypeFromSqlDbType);
                    int num3 = (value is string) ? ((string)value).Length : ((SqlString)value).Value.Length;
                    if (num3 > (metadata.length / 2))
                    {
                        throw SQL.BulkLoadStringTooLong();
                    }
                    goto Label_0290;
                }

                case 0x6a:
                case 0x6c:
                    metaTypeFromSqlDbType = MetaType.GetMetaTypeFromSqlDbType(metaType.SqlDbType, false);
                    value = SqlParameter.CoerceValue(value, metaTypeFromSqlDbType);
                    if (!(value is SqlDecimal))
                    {
                        break;
                    }
                    num2 = (SqlDecimal)value;
                    goto Label_017D;

                case 240:
                    if (value.GetType() != typeof(byte[]))
                    {
                        value = this._connection.GetBytes(value);
                    }
                    goto Label_0290;

                case 0xf1:
                    if (value is XmlReader)
                    {
                        value = MetaType.GetStringFromXml((XmlReader)value);
                    }
                    goto Label_0290;

                default:
                    throw SQL.BulkLoadCannotConvertValue(value.GetType(), metadata.metaType, null);
                }
                num2 = new SqlDecimal((decimal)value);
Label_017D:
                if (num2.Scale != metadata.scale)
                {
                    num2  = TdsParser.AdjustSqlDecimalScale(num2, metadata.scale);
                    value = num2;
                }
                if (num2.Precision > metadata.precision)
                {
                    throw SQL.BulkLoadCannotConvertValue(value.GetType(), metaTypeFromSqlDbType, ADP.ParameterValueOutOfRange(num2));
                }
Label_0290:
                obj2 = value;
            }
            catch (Exception exception)
            {
                if (!ADP.IsCatchableExceptionType(exception))
                {
                    throw;
                }
                throw SQL.BulkLoadCannotConvertValue(value.GetType(), metadata.metaType, exception);
            }
            return(obj2);
        }
Esempio n. 11
0
        // Called by the transaction to initiate commit sequence
        public void SinglePhaseCommit(SinglePhaseEnlistment enlistment)
        {
            Debug.Assert(null != enlistment, "null enlistment?");

            SqlInternalConnection connection      = GetValidConnection();
            SqlConnection         usersConnection = connection.Connection;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                // If the connection is dooomed, we can be certain that the
                // transaction will eventually be rolled back, and we shouldn't
                // attempt to commit it.
                if (connection.IsConnectionDoomed)
                {
                    lock (connection)
                    {
                        _active     = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
                        _connection = null;
                    }

                    enlistment.Aborted(SQL.ConnectionDoomed());
                }
                else
                {
                    Exception commitException;
                    lock (connection)
                    {
                        try
                        {
                            // Now that we've acquired the lock, make sure we still have valid state for this operation.
                            ValidateActiveOnConnection(connection);

                            _active     = false; // set to inactive first, doesn't matter how the rest completes, this transaction is done.
                            _connection = null;  // Set prior to ExecuteTransaction call in case this initiates a TransactionEnd event

                            connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Commit, null, IsolationLevel.Unspecified, _internalTransaction, true);
                            commitException = null;
                        }
                        catch (SqlException e)
                        {
                            commitException = e;

                            // Doom the connection, to make sure that the transaction is
                            // eventually rolled back.
                            // VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
                            connection.DoomThisConnection();
                        }
                        catch (InvalidOperationException e)
                        {
                            commitException = e;
                            connection.DoomThisConnection();
                        }
                    }
                    if (commitException != null)
                    {
                        // connection.ExecuteTransaction failed with exception
                        if (_internalTransaction.IsCommitted)
                        {
                            // Even though we got an exception, the transaction
                            // was committed by the server.
                            enlistment.Committed();
                        }
                        else if (_internalTransaction.IsAborted)
                        {
                            // The transaction was aborted, report that to
                            // SysTx.
                            enlistment.Aborted(commitException);
                        }
                        else
                        {
                            // The transaction is still active, we cannot
                            // know the state of the transaction.
                            enlistment.InDoubt(commitException);
                        }

                        // We eat the exception.  This is called on the SysTx
                        // thread, not the applications thread.  If we don't
                        // eat the exception an UnhandledException will occur,
                        // causing the process to FailFast.
                    }

                    connection.CleanupConnectionOnTransactionCompletion(_atomicTransaction);
                    if (commitException == null)
                    {
                        // connection.ExecuteTransaction succeeded
                        enlistment.Committed();
                    }
                }
            }
            catch (System.OutOfMemoryException e)
            {
                usersConnection.Abort(e);
                throw;
            }
            catch (System.StackOverflowException e)
            {
                usersConnection.Abort(e);
                throw;
            }
            catch (System.Threading.ThreadAbortException e)
            {
                usersConnection.Abort(e);
                throw;
            }
        }
Esempio n. 12
0
        public Byte[] Promote()
        {
            // Operations that might be affected by multi-threaded use MUST be done inside the lock.
            //  Don't read values off of the connection outside the lock unless it doesn't really matter
            //  from an operational standpoint (i.e. logging connection's ObjectID should be fine,
            //  but the PromotedDTCToken can change over calls. so that must be protected).
            SqlInternalConnection connection = GetValidConnection();

            Exception promoteException;

            byte[]        returnValue     = null;
            SqlConnection usersConnection = connection.Connection;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                lock (connection)
                {
                    try
                    {
                        // Now that we've acquired the lock, make sure we still have valid state for this operation.
                        ValidateActiveOnConnection(connection);

                        connection.ExecuteTransaction(SqlInternalConnection.TransactionRequest.Promote, null, IsolationLevel.Unspecified, _internalTransaction, true);
                        returnValue = _connection.PromotedDTCToken;

                        // For Global Transactions, we need to set the Transaction Id since we use a Non-MSDTC Promoter type.
                        if (_connection.IsGlobalTransaction)
                        {
                            if (SysTxForGlobalTransactions.SetDistributedTransactionIdentifier == null)
                            {
                                throw SQL.UnsupportedSysTxForGlobalTransactions();
                            }

                            if (!_connection.IsGlobalTransactionsEnabledForServer)
                            {
                                throw SQL.GlobalTransactionsNotEnabled();
                            }

                            SysTxForGlobalTransactions.SetDistributedTransactionIdentifier.Invoke(_atomicTransaction, new object[] { this, GetGlobalTxnIdentifierFromToken() });
                        }

                        promoteException = null;
                    }
                    catch (SqlException e)
                    {
                        promoteException = e;

                        // Doom the connection, to make sure that the transaction is
                        // eventually rolled back.
                        // VSTS 144562: doom the connection while having the lock on it to prevent race condition with "Transaction Ended" Event
                        connection.DoomThisConnection();
                    }
                    catch (InvalidOperationException e)
                    {
                        promoteException = e;
                        connection.DoomThisConnection();
                    }
                }
            }
            catch (System.OutOfMemoryException e)
            {
                usersConnection.Abort(e);
                throw;
            }
            catch (System.StackOverflowException e)
            {
                usersConnection.Abort(e);
                throw;
            }
            catch (System.Threading.ThreadAbortException e)
            {
                usersConnection.Abort(e);
                throw;
            }

            if (promoteException != null)
            {
                throw SQL.PromotionFailed(promoteException);
            }

            return(returnValue);
        }
        override protected DbConnectionInternal CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
        {
            SqlConnectionString   opt    = (SqlConnectionString)options;
            SqlConnectionPoolKey  key    = (SqlConnectionPoolKey)poolKey;
            SqlInternalConnection result = null;
            SessionData           recoverySessionData = null;

            SqlConnectionString userOpt = null;

            if (userOptions != null)
            {
                userOpt = (SqlConnectionString)userOptions;
            }
            else if (owningConnection != null)
            {
                userOpt = (SqlConnectionString)(((SqlConnection)owningConnection).UserConnectionOptions);
            }

            if (owningConnection != null)
            {
                recoverySessionData = ((SqlConnection)owningConnection)._recoverySessionData;
            }

            if (opt.ContextConnection)
            {
                result = GetContextConnection(opt, poolGroupProviderInfo);
            }
            else
            {
                bool redirectedUserInstance       = false;
                DbConnectionPoolIdentity identity = null;

                // Pass DbConnectionPoolIdentity to SqlInternalConnectionTds if using integrated security.
                // Used by notifications.
                if (opt.IntegratedSecurity || opt.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated)
                {
                    if (pool != null)
                    {
                        identity = pool.Identity;
                    }
                    else
                    {
                        identity = DbConnectionPoolIdentity.GetCurrent();
                    }
                }

                // FOLLOWING IF BLOCK IS ENTIRELY FOR SSE USER INSTANCES
                // If "user instance=true" is in the connection string, we're using SSE user instances
                if (opt.UserInstance)
                {
                    // opt.DataSource is used to create the SSE connection
                    redirectedUserInstance = true;
                    string instanceName;

                    if ((null == pool) ||
                        (null != pool && pool.Count <= 0))     // Non-pooled or pooled and no connections in the pool.

                    {
                        SqlInternalConnectionTds sseConnection = null;
                        try {
                            // What about a failure - throw?  YES!
                            //



                            SqlConnectionString sseopt = new SqlConnectionString(opt, opt.DataSource, true /* user instance=true */, false /* set Enlist = false */);
                            sseConnection = new SqlInternalConnectionTds(identity, sseopt, key.Credential, null, "", null, false);
                            // NOTE: Retrieve <UserInstanceName> here. This user instance name will be used below to connect to the Sql Express User Instance.
                            instanceName = sseConnection.InstanceName;

                            if (!instanceName.StartsWith("\\\\.\\", StringComparison.Ordinal))
                            {
                                throw SQL.NonLocalSSEInstance();
                            }

                            if (null != pool)   // Pooled connection - cache result
                            {
                                SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo;
                                // No lock since we are already in creation mutex
                                providerInfo.InstanceName = instanceName;
                            }
                        }
                        finally {
                            if (null != sseConnection)
                            {
                                sseConnection.Dispose();
                            }
                        }
                    }
                    else   // Cached info from pool.
                    {
                        SqlConnectionPoolProviderInfo providerInfo = (SqlConnectionPoolProviderInfo)pool.ProviderInfo;
                        // No lock since we are already in creation mutex
                        instanceName = providerInfo.InstanceName;
                    }

                    // NOTE: Here connection option opt is cloned to set 'instanceName=<UserInstanceName>' that was
                    //       retrieved from the previous SSE connection. For this UserInstance connection 'Enlist=True'.
                    // options immutable - stored in global hash - don't modify
                    opt = new SqlConnectionString(opt, instanceName, false /* user instance=false */, null /* do not modify the Enlist value */);
                    poolGroupProviderInfo = null; // null so we do not pass to constructor below...
                }
                result = new SqlInternalConnectionTds(identity, opt, key.Credential, poolGroupProviderInfo, "", null, redirectedUserInstance, userOpt, recoverySessionData, pool, key.AccessToken);
            }
            return(result);
        }
Esempio n. 14
0
        internal static MetaType GetSqlDataType(int tdsType, UInt32 userType, int length)
        {
            switch (tdsType)
            {
            case TdsEnums.SQLMONEYN: return((4 == length) ? s_metaSmallMoney : s_metaMoney);

            case TdsEnums.SQLDATETIMN: return((4 == length) ? s_metaSmallDateTime : s_metaDateTime);

            case TdsEnums.SQLINTN: return((4 <= length) ? ((4 == length) ? s_metaInt : s_metaBigInt) : ((2 == length) ? s_metaSmallInt : s_metaTinyInt));

            case TdsEnums.SQLFLTN: return((4 == length) ? s_metaReal : s_metaFloat);

            case TdsEnums.SQLTEXT: return(MetaText);

            case TdsEnums.SQLVARBINARY: return(s_metaSmallVarBinary);

            case TdsEnums.SQLBIGVARBINARY: return(MetaVarBinary);

            case TdsEnums.SQLVARCHAR:
            case TdsEnums.SQLBIGVARCHAR: return(s_metaVarChar);

            case TdsEnums.SQLBINARY:
            case TdsEnums.SQLBIGBINARY: return((TdsEnums.SQLTIMESTAMP == userType) ? s_metaTimestamp : s_metaBinary);

            case TdsEnums.SQLIMAGE: return(MetaImage);

            case TdsEnums.SQLCHAR:
            case TdsEnums.SQLBIGCHAR: return(s_metaChar);

            case TdsEnums.SQLINT1: return(s_metaTinyInt);

            case TdsEnums.SQLBIT:
            case TdsEnums.SQLBITN: return(s_metaBit);

            case TdsEnums.SQLINT2: return(s_metaSmallInt);

            case TdsEnums.SQLINT4: return(s_metaInt);

            case TdsEnums.SQLINT8: return(s_metaBigInt);

            case TdsEnums.SQLMONEY: return(s_metaMoney);

            case TdsEnums.SQLDATETIME: return(s_metaDateTime);

            case TdsEnums.SQLFLT8: return(s_metaFloat);

            case TdsEnums.SQLFLT4: return(s_metaReal);

            case TdsEnums.SQLMONEY4: return(s_metaSmallMoney);

            case TdsEnums.SQLDATETIM4: return(s_metaSmallDateTime);

            case TdsEnums.SQLDECIMALN:
            case TdsEnums.SQLNUMERICN: return(MetaDecimal);

            case TdsEnums.SQLUNIQUEID: return(s_metaUniqueId);

            case TdsEnums.SQLNCHAR: return(s_metaNChar);

            case TdsEnums.SQLNVARCHAR: return(MetaNVarChar);

            case TdsEnums.SQLNTEXT: return(MetaNText);

            case TdsEnums.SQLVARIANT: return(s_metaVariant);

            case TdsEnums.SQLUDT: return(MetaUdt);

            case TdsEnums.SQLXMLTYPE: return(MetaXml);

            case TdsEnums.SQLTABLE: return(s_metaTable);

            case TdsEnums.SQLDATE: return(s_metaDate);

            case TdsEnums.SQLTIME: return(MetaTime);

            case TdsEnums.SQLDATETIME2: return(s_metaDateTime2);

            case TdsEnums.SQLDATETIMEOFFSET: return(MetaDateTimeOffset);

            case TdsEnums.SQLVOID:
            default:
                Debug.Fail("Unknown type " + tdsType.ToString(CultureInfo.InvariantCulture));
                throw SQL.InvalidSqlDbType((SqlDbType)tdsType);
            }
        }
Esempio n. 15
0
        //
        // map SqlDbType to MetaType class
        //
        internal static MetaType GetMetaTypeFromSqlDbType(SqlDbType target, bool isMultiValued)
        { // WebData 113289
            switch (target)
            {
            case SqlDbType.BigInt: return(s_metaBigInt);

            case SqlDbType.Binary: return(s_metaBinary);

            case SqlDbType.Bit: return(s_metaBit);

            case SqlDbType.Char: return(s_metaChar);

            case SqlDbType.DateTime: return(s_metaDateTime);

            case SqlDbType.Decimal: return(MetaDecimal);

            case SqlDbType.Float: return(s_metaFloat);

            case SqlDbType.Image: return(MetaImage);

            case SqlDbType.Int: return(s_metaInt);

            case SqlDbType.Money: return(s_metaMoney);

            case SqlDbType.NChar: return(s_metaNChar);

            case SqlDbType.NText: return(MetaNText);

            case SqlDbType.NVarChar: return(MetaNVarChar);

            case SqlDbType.Real: return(s_metaReal);

            case SqlDbType.UniqueIdentifier: return(s_metaUniqueId);

            case SqlDbType.SmallDateTime: return(s_metaSmallDateTime);

            case SqlDbType.SmallInt: return(s_metaSmallInt);

            case SqlDbType.SmallMoney: return(s_metaSmallMoney);

            case SqlDbType.Text: return(MetaText);

            case SqlDbType.Timestamp: return(s_metaTimestamp);

            case SqlDbType.TinyInt: return(s_metaTinyInt);

            case SqlDbType.VarBinary: return(MetaVarBinary);

            case SqlDbType.VarChar: return(s_metaVarChar);

            case SqlDbType.Variant: return(s_metaVariant);

            case (SqlDbType)TdsEnums.SmallVarBinary: return(s_metaSmallVarBinary);

            case SqlDbType.Xml: return(MetaXml);

            case SqlDbType.Udt: return(MetaUdt);

            case SqlDbType.Structured:
                if (isMultiValued)
                {
                    return(s_metaTable);
                }
                else
                {
                    return(s_metaSUDT);
                }

            case SqlDbType.Date: return(s_metaDate);

            case SqlDbType.Time: return(MetaTime);

            case SqlDbType.DateTime2: return(s_metaDateTime2);

            case SqlDbType.DateTimeOffset: return(MetaDateTimeOffset);

            default: throw SQL.InvalidSqlDbType(target);
            }
        }