internal static void BestEffortCleanup(SNIHandle target) { if (target != null) { target.Dispose(); } }
internal SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo, string serverName, SNIHandle parent) : base(IntPtr.Zero, true) { this._status = uint.MaxValue; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { this._status = SNINativeMethodWrapper.SNIOpen(myInfo, serverName, parent, ref this.handle, parent._fSync); } }
internal TdsParserStateObject(TdsParser parser, SNIHandle physicalConnection, bool async) { this._objectID = Interlocked.Increment(ref _objectTypeCount); this._owner = new WeakReference(null); this._inputHeaderLen = 8; this._outputHeaderLen = 8; this._outBytesUsed = 8; this._outputPacketNumber = 1; this._bTmp = new byte[12]; this._parser = parser; this.SniContext = System.Data.SqlClient.SniContext.Snix_GetMarsSession; this.SetPacketSize(this._parser._physicalStateObj._outBuff.Length); SNINativeMethodWrapper.ConsumerInfo myInfo = this.CreateConsumerInfo(async); this._sessionHandle = new SNIHandle(myInfo, "session:", physicalConnection); if (this._sessionHandle.Status != 0) { parser.Errors.Add(parser.ProcessSNIError(this)); parser.ThrowExceptionAndWarning(); } this.IncrementPendingCallbacks(); }
private uint SNIWriteAsync(SNIHandle handle, SNIPacket packet, DbAsyncResult asyncResult) { uint num; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { this.IncrementPendingCallbacks(); num = SNINativeMethodWrapper.SNIWriteAsync(handle, packet); if ((num == 0) || (num != 0x3e5)) { this.DecrementPendingCallbacks(false); } } if (num != 0) { if (num != 0x3e5) { Bid.Trace("<sc.TdsParser.WritePacket|Info> write async returned error code %d\n", (int) num); this._parser.Errors.Add(this._parser.ProcessSNIError(this)); this.ThrowExceptionAndWarning(); return num; } if (num != 0x3e5) { return num; } try { ((IAsyncResult) asyncResult).AsyncWaitHandle.WaitOne(); if (this._error != null) { this._parser.Errors.Add(this._error); this._error = null; Bid.Trace("<sc.TdsParser.WritePacket|Info> write async returned error code %d\n", (int) num); this.ThrowExceptionAndWarning(); } } finally { asyncResult.Reset(); } } return num; }
internal static unsafe uint SNISecGenClientContext(SNIHandle pConnectionObject, byte[] inBuff, uint receivedLength, byte[] OutBuff, ref uint sendLength, byte[] serverUserName) { fixed (byte* pin_serverUserName = &serverUserName[0]) { bool local_fDone; return SNISecGenClientContextWrapper( pConnectionObject, inBuff, receivedLength, OutBuff, ref sendLength, out local_fDone, pin_serverUserName, (uint)(serverUserName == null ? 0 : serverUserName.Length), null, null); } }
internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId) { return SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_CONNID, out connId); }
private static extern uint SNIWriteAsyncWrapper(SNIHandle pConn, [In] SNIPacket pPacket);
internal static extern uint SNIRemoveProvider(SNIHandle pConn, ProviderEnum ProvNum);
internal static extern uint SNIReadAsync(SNIHandle pConn, ref IntPtr ppNewPacket);
internal void CreatePhysicalSNIHandle(string serverName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, byte[] spnBuffer, bool flushCache, bool async, bool fParallel) { SNINativeMethodWrapper.ConsumerInfo myInfo = CreateConsumerInfo(async); // Translate to SNI timeout values (Int32 milliseconds) long timeout; if (Int64.MaxValue == timerExpire) { timeout = Int32.MaxValue; } else { timeout = ADP.TimerRemainingMilliseconds(timerExpire); if (timeout > Int32.MaxValue) { timeout = Int32.MaxValue; } else if (0 > timeout) { timeout = 0; } } _sessionHandle = new SNIHandle(myInfo, serverName, spnBuffer, ignoreSniOpenTimeout, checked((int)timeout), out instanceName, flushCache, !async, fParallel); }
internal static extern uint SNIWaitForSSLHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds);
internal static extern uint SNISetInfo(SNIHandle pConn, QTypes QType, [In] ref uint pbQInfo);
internal static extern uint SNIReadSyncOverAsync(SNIHandle pConn, ref IntPtr ppNewPacket, int timeout);
internal static extern void SNIPacketReset([In] SNIHandle pConn, IOType IOType, SNIPacket pPacket, ConsumerNumber ConsNum);
internal void Dispose() { SafeHandle handle2 = this._sniPacket; SafeHandle handle = this._sessionHandle; SafeHandle handle3 = this._sniAsyncAttnPacket; this._sniPacket = null; this._sessionHandle = null; this._sniAsyncAttnPacket = null; if ((handle != null) || (handle2 != null)) { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { if (handle2 != null) { handle2.Dispose(); } if (handle3 != null) { handle3.Dispose(); } if (handle != null) { handle.Dispose(); this.DecrementPendingCallbacks(true); } } } }
internal static extern uint SNICheckConnection([In] SNIHandle pConn);
private static extern uint SNIGetInfoWrapper([In] SNIHandle pConn, SNINativeMethodWrapper.QTypes QType, out Guid pbQInfo);
internal override uint CheckConnection() { SNIHandle handle = Handle; return(handle == null ? TdsEnums.SNI_SUCCESS : SNINativeMethodWrapper.SNICheckConnection(handle)); }
private static extern uint SNIOpenWrapper( [In] ref Sni_Consumer_Info pConsumerInfo, [MarshalAs(UnmanagedType.LPStr)] string szConnect, [In] SNIHandle pConn, out IntPtr ppConn, [MarshalAs(UnmanagedType.Bool)] bool fSync);
private static extern uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket);
internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId) { return(SNIGetInfoWrapper(pConn, QTypes.SNI_QUERY_CONN_CONNID, out connId)); }
internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync) { // initialize consumer info for MARS Sni_Consumer_Info native_consumerInfo = new Sni_Consumer_Info(); MarshalConsumerInfo(consumerInfo, ref native_consumerInfo); return SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync); }
public static uint SNICheckConnection (SNIHandle handle) { throw new NotSupportedException (msg); }
internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync) { if (sync) { return SNIWriteSyncOverAsync(pConn, packet); } else { return SNIWriteAsyncWrapper(pConn, packet); } }
public static uint SNIOpenMarsSession (ConsumerInfo info, SNIHandle parent, ref IntPtr handle, bool sync) { throw new NotSupportedException (msg); }
internal void CreatePhysicalSNIHandle(string serverName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, byte[] spnBuffer, bool flushCache, bool async, bool fParallel) { long num; SNINativeMethodWrapper.ConsumerInfo myInfo = this.CreateConsumerInfo(async); if (0x7fffffffffffffffL == timerExpire) { num = 0x7fffffffL; } else { num = ADP.TimerRemainingMilliseconds(timerExpire); if (num > 0x7fffffffL) { num = 0x7fffffffL; } else if (0L > num) { num = 0L; } } this._sessionHandle = new SNIHandle(myInfo, serverName, spnBuffer, ignoreSniOpenTimeout, (int) num, out instanceName, flushCache, !async, fParallel); }
// constructs SNI Handle for MARS session internal SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo, SNIHandle parent) : base(IntPtr.Zero, true) { RuntimeHelpers.PrepareConstrainedRegions(); try {} finally { _status = SNINativeMethodWrapper.SNIOpenMarsSession(myInfo, parent, ref base.handle, parent._fSync); } }
internal TdsParserStateObject(TdsParser parser, SNIHandle physicalConnection, bool async) { // Construct a MARS session Debug.Assert(null != parser, "no parser?"); _parser = parser; SniContext = SniContext.Snix_GetMarsSession; Debug.Assert(null != _parser._physicalStateObj, "no physical session?"); Debug.Assert(null != _parser._physicalStateObj._inBuff, "no in buffer?"); Debug.Assert(null != _parser._physicalStateObj._outBuff, "no out buffer?"); Debug.Assert(_parser._physicalStateObj._outBuff.Length == _parser._physicalStateObj._inBuff.Length, "Unexpected unequal buffers."); // Determine packet size based on physical connection buffer lengths. SetPacketSize(_parser._physicalStateObj._outBuff.Length); SNINativeMethodWrapper.ConsumerInfo myInfo = CreateConsumerInfo(async); _sessionHandle = new SNIHandle(myInfo, physicalConnection); if (_sessionHandle.Status != TdsEnums.SNI_SUCCESS) { AddError(parser.ProcessSNIError(this)); ThrowExceptionAndWarning(); } // we post a callback that represents the call to dispose; once the // object is disposed, the next callback will cause the GC Handle to // be released. IncrementPendingCallbacks(); _lastSuccessfulIOTimer = parser._physicalStateObj._lastSuccessfulIOTimer; }
internal static extern uint SNIAddProvider(SNIHandle pConn, ProviderEnum ProvNum, [In] ref uint pInfo);
public SNIPacket Take(SNIHandle sniHandle) { SNIPacket packet; if (_packets.Count > 0) { // Success - reset the packet packet = _packets.Pop(); SNINativeMethodWrapper.SNIPacketReset(sniHandle, SNINativeMethodWrapper.IOType.WRITE, packet, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI); } else { // Failed to take a packet - create a new one packet = new SNIPacket(sniHandle); } return packet; }
// constructs SNI Handle for MARS session internal SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo, SNIHandle parent) : base(IntPtr.Zero, true) { try { } finally { _status = SNINativeMethodWrapper.SNIOpenMarsSession(myInfo, parent, ref base.handle, parent._fSync); } }
#pragma warning disable 0420 // a reference to a volatile field will not be treated as volatile private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out UInt32 sniError, bool canAccumulate, bool callerHasConnectionLock) { // Check for a stored exception var delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null); if (delayedException != null) { throw delayedException; } Task task = null; _writeCompletionSource = null; IntPtr packetPointer = IntPtr.Zero; bool sync = !_parser._asyncWrite; if (sync && _asyncWriteCount > 0) { // for example, SendAttention while there are writes pending Task waitForWrites = WaitForAccumulatedWrites(); if (waitForWrites != null) { try { waitForWrites.Wait(); } catch (AggregateException ae) { throw ae.InnerException; } } Debug.Assert(_asyncWriteCount == 0, "All async write should be finished"); } if (!sync) { // Add packet to the pending list (since the callback can happen any time after we call SNIWritePacket) packetPointer = AddPacketToPendingList(packet); } // Async operation completion may be delayed (success pending). try { } finally { sniError = SNINativeMethodWrapper.SNIWritePacket(handle, packet, sync); } if (sniError == TdsEnums.SNI_SUCCESS_IO_PENDING) { Debug.Assert(!sync, "Completion should be handled in SniManagedWwrapper"); Interlocked.Increment(ref _asyncWriteCount); Debug.Assert(_asyncWriteCount >= 0); if (!canAccumulate) { // Create completion source (for callback to complete) _writeCompletionSource = new TaskCompletionSource<object>(); task = _writeCompletionSource.Task; // Ensure that setting _writeCompletionSource completes before checking _delayedWriteAsyncCallbackException Interlocked.MemoryBarrier(); // Check for a stored exception delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null); if (delayedException != null) { throw delayedException; } // If there are no outstanding writes, see if we can shortcut and return null if ((_asyncWriteCount == 0) && ((!task.IsCompleted) || (task.Exception == null))) { task = null; } } } #if DEBUG else if (!sync && !canAccumulate && SqlCommand.DebugForceAsyncWriteDelay > 0) { // Executed synchronously - callback will not be called TaskCompletionSource<object> completion = new TaskCompletionSource<object>(); uint error = sniError; new Timer(obj => { try { if (_parser.MARSOn) { // Only take reset lock on MARS. CheckSetResetConnectionState(error, CallbackType.Write); } if (error != TdsEnums.SNI_SUCCESS) { AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(); } AssertValidState(); completion.SetResult(null); } catch (Exception e) { completion.SetException(e); } }, null, SqlCommand.DebugForceAsyncWriteDelay, Timeout.Infinite); task = completion.Task; } #endif else { if (_parser.MARSOn) { // Only take reset lock on MARS. CheckSetResetConnectionState(sniError, CallbackType.Write); } if (sniError == TdsEnums.SNI_SUCCESS) { _lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks; if (!sync) { // Since there will be no callback, remove the packet from the pending list Debug.Assert(packetPointer != IntPtr.Zero, "Packet added to list has an invalid pointer, can not remove from pending list"); RemovePacketFromPendingList(packetPointer); } } else { AddError(_parser.ProcessSNIError(this)); ThrowExceptionAndWarning(callerHasConnectionLock); } AssertValidState(); } return task; }
internal void Dispose() { SafeHandle packetHandle = _sniPacket; SafeHandle sessionHandle = _sessionHandle; SafeHandle asyncAttnPacket = _sniAsyncAttnPacket; _sniPacket = null; _sessionHandle = null; _sniAsyncAttnPacket = null; Timer networkPacketTimeout = _networkPacketTimeout; if (networkPacketTimeout != null) { _networkPacketTimeout = null; networkPacketTimeout.Dispose(); } Debug.Assert(Volatile.Read(ref _readingCount) >= 0, "_readingCount is negative"); if (Volatile.Read(ref _readingCount) > 0) { // if _reading is true, we need to wait for it to complete // if _reading is false, then future read attempts will // already see the null _sessionHandle and abort. // We block after nulling _sessionHandle but before disposing it // to give a chance for a read that has already grabbed the // handle to complete. SpinWait.SpinUntil(() => Volatile.Read(ref _readingCount) == 0); } if (null != sessionHandle || null != packetHandle) { try { } finally { if (packetHandle != null) { packetHandle.Dispose(); } if (asyncAttnPacket != null) { asyncAttnPacket.Dispose(); } if (sessionHandle != null) { sessionHandle.Dispose(); DecrementPendingCallbacks(true); // Will dispose of GC handle. } } } if (_writePacketCache != null) { lock (_writePacketLockObject) { try { } finally { _writePacketCache.Dispose(); // Do not set _writePacketCache to null, just in case a WriteAsyncCallback completes after this point } } } }
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; } }