public bool PosTest2()
    {
        bool retVal = true;

        const string c_TEST_DESC = "PosTest2: Verify the objectName is empty";
        const string c_TEST_ID = "P002";

        string name = String.Empty;
        ObjectDisposedException exception = new ObjectDisposedException(name);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            if (exception.ObjectName != name)
            {
                string errorDesc = "ObjectName is not empty as expected: Actual(" + exception.ObjectName + ")";
                TestLibrary.TestFramework.LogError("003 " + "TestID_" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004 " + "TestID_" + c_TEST_ID, "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest1()
    {
        bool retVal = true;

        const string c_TEST_DESC = "PosTest1: Verify the objectName is random string";
        const string c_TEST_ID = "P001";

        string name = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
        ObjectDisposedException exception = new ObjectDisposedException(name);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            if (exception.ObjectName != name)
            {
                string errorDesc = "ObjectName is not " + name + " as expected: Actual(" + exception.ObjectName+ ")";
                TestLibrary.TestFramework.LogError("001 " + "TestID_" + c_TEST_ID, errorDesc);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002" + "TestID_" + c_TEST_ID, "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
    public bool PosTest1()
    {
        bool retVal = true;

        const string c_TEST_DESC = "PosTest1: Verify the objectName is random string";
        const string c_TEST_ID = "P001";

        string name = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
        string message = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
        ObjectDisposedException  exception = new ObjectDisposedException(name,message);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            if (exception.Message != message)
            {
                int index = exception.Message.IndexOf(name);
                if (index == -1)
                {
                    string errorDesc = "Message shoule contains the object name";
                    errorDesc += TestLibrary.Env.NewLine + "objectName is " + name;
                    errorDesc += TestLibrary.Env.NewLine + "message is " + message;
                    errorDesc += TestLibrary.Env.NewLine + "exception's message is " + exception.Message;
                    TestLibrary.TestFramework.LogError("001 " + "TestID_" + c_TEST_ID, errorDesc);
                    retVal = false;
                }
                index = exception.Message.IndexOf(message);
                if (index == -1)
                {
                    string errorDesc = "Message shoule contains the message";
                    errorDesc += TestLibrary.Env.NewLine + "objectName is " + name;
                    errorDesc += TestLibrary.Env.NewLine + "message is " + message;
                    errorDesc += TestLibrary.Env.NewLine + "exception's message is " + exception.Message;
                    TestLibrary.TestFramework.LogError("001 " + "TestID_" + c_TEST_ID, errorDesc);
                    retVal = false;
                }
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 public void EndWrite(IAsyncResult result)
 {
     try
     {
         this.CancelSendTimer();
         lock (this.ThisLock)
         {
             this.asyncWritePending = false;
         }
         this.Stream.EndWrite(result);
     }
     catch (ObjectDisposedException objectDisposedException1)
     {
         ObjectDisposedException objectDisposedException = objectDisposedException1;
         throw Fx.Exception.AsInformation(this.ConvertObjectDisposedException(objectDisposedException), null);
     }
     catch (IOException oException1)
     {
         IOException oException = oException1;
         throw Fx.Exception.AsInformation(BaseStreamConnection.ConvertIOException(oException), null);
     }
     catch (CommunicationException communicationException)
     {
         throw;
     }
     catch (TimeoutException timeoutException)
     {
         throw;
     }
     catch (Exception exception1)
     {
         Exception exception = exception1;
         if (!Fx.IsFatal(exception))
         {
             throw Fx.Exception.AsError(new CommunicationException(exception.Message, exception), null);
         }
         throw;
     }
 }
Exemple #5
0
        public byte[] ComputeHash(byte[] buffer, int offset, int count)
        {
            ArgumentNullException.ThrowIfNull(buffer);

            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            if (count < 0 || (count > buffer.Length))
            {
                throw new ArgumentException(SR.Argument_InvalidValue);
            }
            if ((buffer.Length - count) < offset)
            {
                throw new ArgumentException(SR.Argument_InvalidOffLen);
            }

            ObjectDisposedException.ThrowIf(_disposed, this);

            HashCore(buffer, offset, count);
            return(CaptureHashCodeAndReinitialize());
        }
Exemple #6
0
        public bool TryComputeHash(ReadOnlySpan <byte> source, Span <byte> destination, out int bytesWritten)
        {
            ObjectDisposedException.ThrowIf(_disposed, this);

            if (destination.Length < HashSizeValue / 8)
            {
                bytesWritten = 0;
                return(false);
            }

            HashCore(source);
            if (!TryHashFinal(destination, out bytesWritten))
            {
                // The only reason for failure should be that the destination isn't long enough,
                // but we checked the size earlier.
                throw new InvalidOperationException(SR.InvalidOperation_IncorrectImplementation);
            }
            HashValue = null;

            Initialize();
            return(true);
        }
Exemple #7
0
        /// <summary>
        /// This method retrieves the counter value associated with counter 'counterId'
        /// based on isNumerator parameter.
        /// </summary>
        public override bool GetCounterValue(int counterId, bool isNumerator, out long counterValue)
        {
            counterValue = -1;
            if (_Disposed)
            {
                ObjectDisposedException objectDisposedException =
                    new ObjectDisposedException("PSCounterSetInstance");
                _tracer.TraceException(objectDisposedException);
                return(false);
            }

            int targetCounterId;

            if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId))
            {
                CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId];

                if (targetCounterData != null)
                {
                    counterValue = targetCounterData.Value;
                    return(true);
                }
                else
                {
                    InvalidOperationException invalidOperationException =
                        new InvalidOperationException(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                "Lookup for counter corresponding to counter id {0} failed",
                                counterId));
                    _tracer.TraceException(invalidOperationException);
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Exemple #8
0
        /// <summary>
        /// Imports a blob that represents DSA key information.
        /// </summary>
        /// <param name="keyBlob">A byte array that represents a DSA key blob.</param>
        public void ImportCspBlob(byte[] keyBlob)
        {
            ObjectDisposedException.ThrowIf(_disposed, this);

            SafeCapiKeyHandle safeKeyHandle;

            if (IsPublic(keyBlob))
            {
                SafeProvHandle safeProvHandleTemp = AcquireSafeProviderHandle();
                CapiHelper.ImportKeyBlob(safeProvHandleTemp, (CspProviderFlags)0, false, keyBlob, out safeKeyHandle);

                // The property set will take care of releasing any already-existing resources.
                SafeProvHandle = safeProvHandleTemp;
            }
            else
            {
                CapiHelper.ImportKeyBlob(SafeProvHandle, _parameters.Flags, false, keyBlob, out safeKeyHandle);
            }

            // The property set will take care of releasing any already-existing resources.
            SafeKeyHandle = safeKeyHandle;
        }
        protected int Read(byte[] buffer, int offset, int size, TimeSpan timeout, bool closing)
        {
            int num = 0;

            Microsoft.ServiceBus.Common.TimeoutHelper timeoutHelper = new Microsoft.ServiceBus.Common.TimeoutHelper(timeout);
            try
            {
                this.SetReadTimeout(timeoutHelper.RemainingTime(), true, closing);
                num = this.Stream.Read(buffer, offset, size);
            }
            catch (ObjectDisposedException objectDisposedException1)
            {
                ObjectDisposedException objectDisposedException = objectDisposedException1;
                throw Fx.Exception.AsInformation(this.ConvertObjectDisposedException(objectDisposedException), null);
            }
            catch (IOException oException1)
            {
                IOException oException = oException1;
                throw Fx.Exception.AsInformation(BaseStreamConnection.ConvertIOException(oException), null);
            }
            catch (CommunicationException communicationException)
            {
                throw;
            }
            catch (TimeoutException timeoutException)
            {
                throw;
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                if (!Fx.IsFatal(exception))
                {
                    throw Fx.Exception.AsError(new CommunicationException(exception.Message, exception), null);
                }
                throw;
            }
            return(num);
        }
Exemple #10
0
        internal async Task WriteWebSocketHandshakeHeadersAsync()
        {
            ObjectDisposedException.ThrowIf(_closed, this);

            if (_stream.CanWrite)
            {
                MemoryStream ms      = GetHeaders(closing: false, isWebSocketHandshake: true) !;
                bool         chunked = _response.SendChunked;

                long start = ms.Position;
                if (chunked)
                {
                    byte[] bytes = GetChunkSizeBytes(0, true);
                    ms.Position = ms.Length;
                    ms.Write(bytes, 0, bytes.Length);
                }

                await InternalWriteAsync(ms.GetBuffer(), (int)start, (int)(ms.Length - start)).ConfigureAwait(false);

                await _stream.FlushAsync().ConfigureAwait(false);
            }
        }
Exemple #11
0
        private void close(bool force)
        {
            if (!_listening)
            {
                _disposed = true;

                return;
            }

            _listening = false;

            cleanupContextQueue(force);
            cleanupContextRegistry();

            var ex = new ObjectDisposedException(_objectName);

            cleanupWaitQueue(ex);

            EndPointManager.RemoveListener(this);

            _disposed = true;
        }
Exemple #12
0
        public Task SendAsync(Message message)
        {
            lock (_messageQueue)
            {
                ObjectDisposedException.ThrowIf(_senderClosed, typeof(TestWebSocket));

                if (_receiverClosed)
                {
                    throw new IOException("The remote end closed the connection.", new ObjectDisposedException(typeof(TestWebSocket).FullName));
                }

                // we return immediately so we need to copy the buffer since the sender can re-use it
                var array = new byte[message.Buffer.Count];
                Array.Copy(message.Buffer.Array !, message.Buffer.Offset, array, 0, message.Buffer.Count);
                message.Buffer = new ArraySegment <byte>(array);

                _messageQueue.Enqueue(message);
                _sem.Release();

                return(Task.FromResult(true));
            }
        }
Exemple #13
0
    private async ValueTask FinishConnectAsync(QuicClientConnectionOptions options, CancellationToken cancellationToken = default)
    {
        ObjectDisposedException.ThrowIf(_disposed == 1, this);

        if (_connectedTcs.TryInitialize(out ValueTask valueTask, this, cancellationToken))
        {
            _canAccept = options.MaxInboundBidirectionalStreams > 0 || options.MaxInboundUnidirectionalStreams > 0;
            _defaultStreamErrorCode = options.DefaultStreamErrorCode;
            _defaultCloseErrorCode  = options.DefaultCloseErrorCode;

            if (!options.RemoteEndPoint.TryParse(out string?host, out IPAddress? address, out int port))
            {
                throw new ArgumentException(SR.Format(SR.net_quic_unsupported_endpoint_type, options.RemoteEndPoint.GetType()), nameof(options));
            }
            int addressFamily = QUIC_ADDRESS_FAMILY_UNSPEC;

            // RemoteEndPoint is either IPEndPoint or DnsEndPoint containing IPAddress string.
            // --> Set the IP directly, no name resolution needed.
            if (address is not null)
            {
                QuicAddr quicAddress = new IPEndPoint(address, port).ToQuicAddr();
                MsQuicHelpers.SetMsQuicParameter(_handle, QUIC_PARAM_CONN_REMOTE_ADDRESS, quicAddress);
            }
            // RemoteEndPoint is DnsEndPoint containing hostname that is different from requested SNI.
            // --> Resolve the hostname and set the IP directly, use requested SNI in ConnectionStart.
            else if (host is not null &&
                     !host.Equals(options.ClientAuthenticationOptions.TargetHost, StringComparison.InvariantCultureIgnoreCase))
            {
                IPAddress[] addresses = await Dns.GetHostAddressesAsync(host !, cancellationToken).ConfigureAwait(false);

                cancellationToken.ThrowIfCancellationRequested();
                if (addresses.Length == 0)
                {
                    throw new SocketException((int)SocketError.HostNotFound);
                }

                QuicAddr quicAddress = new IPEndPoint(addresses[0], port).ToQuicAddr();
                MsQuicHelpers.SetMsQuicParameter(_handle, QUIC_PARAM_CONN_REMOTE_ADDRESS, quicAddress);
            }
        private bool IsValid(out Exception exception)
        {
            exception = null;
            if (m_isDisposed)
            {
                exception = new ObjectDisposedException(GetType().Name);
            }
            else if (Connection is null)
            {
                exception = new InvalidOperationException("Connection property must be non-null.");
            }
            else if (Connection.State != ConnectionState.Open && Connection.State != ConnectionState.Connecting)
            {
                exception = new InvalidOperationException("Connection must be Open; current state is {0}".FormatInvariant(Connection.State));
            }
            else if (!Connection.IgnoreCommandTransaction && Transaction != Connection.CurrentTransaction)
            {
                exception = new InvalidOperationException("The transaction associated with this command is not the connection's active transaction; see https://fl.vu/mysql-trans");
            }
            else if (BatchCommands.Count == 0)
            {
                exception = new InvalidOperationException("BatchCommands must contain a command");
            }

            if (exception is null)
            {
                foreach (var command in BatchCommands)
                {
                    if ((command.CommandBehavior & CommandBehavior.CloseConnection) != 0)
                    {
                        exception = new NotSupportedException("CommandBehavior.CloseConnection is not supported by MySqlBatch");
                        break;
                    }
                }
            }

            return(exception is null);
        }
Exemple #15
0
        public override async Task <DocumentQueryResult> ExecuteQuery(IndexQueryServerSide query, DocumentsOperationContext documentsContext, long?existingResultEtag, OperationCancelToken token)
        {
            ObjectDisposedException lastException = null;

            for (var i = 0; i < NumberOfRetries; i++)
            {
                try
                {
                    Stopwatch           sw = null;
                    QueryTimingsScope   scope;
                    DocumentQueryResult result;
                    using (scope = query.Timings?.Start())
                    {
                        if (scope == null)
                        {
                            sw = Stopwatch.StartNew();
                        }

                        result = await GetRunner(query).ExecuteQuery(query, documentsContext, existingResultEtag, token);
                    }

                    result.DurationInMs = sw != null ? (long)sw.Elapsed.TotalMilliseconds : (long)scope.Duration.TotalMilliseconds;

                    return(result);
                }
                catch (ObjectDisposedException e)
                {
                    if (Database.DatabaseShutdown.IsCancellationRequested)
                    {
                        throw;
                    }

                    lastException = e;
                }
            }

            throw CreateRetriesFailedException(lastException);
        }
Exemple #16
0
    public bool PosTest2()
    {
        bool retVal = true;

        const string c_TEST_DESC = "PosTest2: Verify the message parameter is empty";
        const string c_TEST_ID   = "P002";

        string name    = string.Empty;
        string message = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH);
        ObjectDisposedException exception = new ObjectDisposedException(name, message);

        TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);

        try
        {
            if (exception.Message != "An error occurred.")
            {
                int index = exception.Message.IndexOf(message);
                if (index == -1)
                {
                    string errorDesc = "Message shoule contains the message";
                    errorDesc += Environment.NewLine + "objectName is empty";
                    errorDesc += Environment.NewLine + "message parameter" + message;
                    errorDesc += Environment.NewLine + "exception's message is " + exception.Message;
                    TestLibrary.TestFramework.LogError("003 " + "TestID_" + c_TEST_ID, errorDesc);
                    retVal = false;
                }
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return(retVal);
    }
Exemple #17
0
        public void SetDistributedTransactionIdentifier(IPromotableSinglePhaseNotification promotableNotification,
                                                        Guid distributedTransactionIdentifier)
        {
            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;

            if (etwLog.IsEnabled())
            {
                etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
            }

            ObjectDisposedException.ThrowIf(Disposed, this);

            ArgumentNullException.ThrowIfNull(promotableNotification);

            if (distributedTransactionIdentifier == Guid.Empty)
            {
                throw new ArgumentException(null, nameof(distributedTransactionIdentifier));
            }

            if (_complete)
            {
                throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
            }

            lock (_internalTransaction)
            {
                Debug.Assert(_internalTransaction.State != null);
                _internalTransaction.State.SetDistributedTransactionId(_internalTransaction,
                                                                       promotableNotification,
                                                                       distributedTransactionIdentifier);

                if (etwLog.IsEnabled())
                {
                    etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
                }
                return;
            }
        }
Exemple #18
0
        /// <summary>
        /// Create a promotable single phase enlistment that promotes to a distributed transaction manager other than MSDTC.
        /// </summary>
        /// <param name="promotableSinglePhaseNotification">The object that implements the IPromotableSinglePhaseNotification interface.</param>
        /// <param name="promoterType">
        /// The promoter type Guid that identifies the format of the byte[] that is returned by the ITransactionPromoter.Promote
        /// call that is implemented by the IPromotableSinglePhaseNotificationObject, and thus the promoter of the transaction.
        /// </param>
        /// <returns>
        /// True if the enlistment is successful.
        ///
        /// False if the transaction already has a durable enlistment or promotable single phase enlistment or
        /// if the transaction has already promoted. In this case, the caller will need to enlist in the transaction through other
        /// means.
        ///
        /// If the Transaction.PromoterType matches the promoter type supported by the caller, then the
        /// Transaction.PromotedToken can be retrieved and used to enlist directly with the identified distributed transaction manager.
        ///
        /// How the enlistment is created with the distributed transaction manager identified by the Transaction.PromoterType
        /// is defined by that distributed transaction manager.
        /// </returns>
        public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType)
        {
            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;

            if (etwLog.IsEnabled())
            {
                etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
            }

            ObjectDisposedException.ThrowIf(Disposed, this);

            ArgumentNullException.ThrowIfNull(promotableSinglePhaseNotification);

            if (promoterType == Guid.Empty)
            {
                throw new ArgumentException(SR.PromoterTypeInvalid, nameof(promoterType));
            }

            if (_complete)
            {
                throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
            }

            bool succeeded = false;

            lock (_internalTransaction)
            {
                Debug.Assert(_internalTransaction.State != null);
                succeeded = _internalTransaction.State.EnlistPromotableSinglePhase(_internalTransaction, promotableSinglePhaseNotification, this, promoterType);
            }

            if (etwLog.IsEnabled())
            {
                etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
            }

            return(succeeded);
        }
Exemple #19
0
        public override bool UpdateCounterByValue(int counterId, long stepAmount, bool isNumerator)
        {
            int num;

            if (this._Disposed)
            {
                ObjectDisposedException exception = new ObjectDisposedException("PSCounterSetInstance");
                this._tracer.TraceException(exception);
                return(false);
            }
            if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out num))
            {
                CounterData targetCounterData = this._CounterSetInstance.Counters[num];
                if (targetCounterData != null)
                {
                    this.UpdateCounterByValue(targetCounterData, stepAmount);
                    return(true);
                }
                InvalidOperationException exception2 = new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Lookup for counter corresponding to counter id {0} failed", new object[] { counterId }));
                this._tracer.TraceException(exception2);
            }
            return(false);
        }
 public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout)
 {
     this.ThrowIfNotOpen();
     try
     {
         IAsyncResult asyncResult = this.webSocket.BeginSend(buffer, offset, size, ServiceBusClientWebSocket.WebSocketMessageType.Binary, timeout, null, null);
         this.webSocket.EndSend(asyncResult);
     }
     catch (IOException oException1)
     {
         IOException oException = oException1;
         throw Fx.Exception.AsError(ClientWebSocketConnection.ConvertIOException(oException), this.Activity);
     }
     catch (ObjectDisposedException objectDisposedException1)
     {
         ObjectDisposedException objectDisposedException = objectDisposedException1;
         if (this.webSocket.State != ServiceBusClientWebSocket.WebSocketState.Faulted)
         {
             throw Fx.Exception.AsError(new CommunicationObjectAbortedException(objectDisposedException.Message, objectDisposedException), this.Activity);
         }
         throw Fx.Exception.AsError(new CommunicationObjectFaultedException(objectDisposedException.Message, objectDisposedException), this.Activity);
     }
 }
        protected override void Destroy()
        {
            var disposedEx = new ObjectDisposedException(GetType().Name);

            if (Interlocked.CompareExchange(ref destroyed, disposedEx, null) != null)
            {
                return;
            }

            try {
                if (sslStream != null)
                {
                    sslStream.Dispose();
                }
            } catch {
                ;
            } finally {
                sslStream = null;
            }
            innerSocket     = accepted = socket = null;
            innerStream     = null;
            instrumentation = null;
        }
Exemple #22
0
        protected override void Act()
        {
            ThreadAbstraction.ExecuteThread(() =>
            {
                Thread.Sleep(500);
                _reader.Dispose();
                _disposeCompleted.Set();
            });

            try
            {
                _reader.Read();
                Assert.Fail();
            }
            catch (ObjectDisposedException ex)
            {
                _actualException = ex;
            }

            // Dispose may unblock Read() before the dispose has fully completed, so
            // let's wait until it has completed
            _disposeCompleted.WaitOne(500);
        }
Exemple #23
0
        public void Rollback(Exception?e)
        {
            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;

            if (etwLog.IsEnabled())
            {
                etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
                etwLog.TransactionRollback(this, "Transaction");
            }

            ObjectDisposedException.ThrowIf(Disposed, this);

            lock (_internalTransaction)
            {
                Debug.Assert(_internalTransaction.State != null);
                _internalTransaction.State.Rollback(_internalTransaction, e);
            }

            if (etwLog.IsEnabled())
            {
                etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
            }
        }
Exemple #24
0
        public void LogTest()
        {
            string message = "Out of range";
            IndexOutOfRangeException ex = Exceptions.Log(new IndexOutOfRangeException(message));

            Assert.AreEqual(message, ex.Message);

            // The category parameter is only for logging.
            InvalidCastException castEx = Exceptions.Log(new InvalidCastException(message), typeof(ExceptionsTest));

            Assert.AreEqual(message, castEx.Message);

            ObjectDisposedException disposedEx = Exceptions.Log(new ObjectDisposedException("Testing"));

            disposedEx.ObjectName.ShouldBe("Testing");

            Exceptions.Log(ex, typeof(ExceptionsTest));

            Dictionary <string, object> properties = CreateProperties();

            Exceptions.Log(ex, properties);
            Exceptions.Log(ex, this.GetType(), properties);
        }
Exemple #25
0
        internal static Exception ConvertAggregateExceptionToCommunicationException(AggregateException ex)
        {
            Exception          exception          = FxTrace.Exception.AsError <WebSocketException>(ex);
            WebSocketException webSocketException = exception as WebSocketException;

            if (webSocketException != null && webSocketException.InnerException != null)
            {
                HttpListenerException httpListenerException = webSocketException.InnerException as HttpListenerException;
                if (httpListenerException != null)
                {
                    return(HttpChannelUtilities.CreateCommunicationException(httpListenerException));
                }
            }

            ObjectDisposedException objectDisposedException = exception as ObjectDisposedException;

            if (objectDisposedException != null)
            {
                return(new CommunicationObjectAbortedException(exception.Message, exception));
            }

            return(new CommunicationException(exception.Message, exception));
        }
            // Method called to prepare for a native async http.sys call.
            // This method performs the tasks common to all http.sys operations.
            internal void StartOperationCommon(WebSocketHttpListenerDuplexStream currentStream, ThreadPoolBoundHandle boundHandle)
            {
                // Change status to "in-use".
                if (Interlocked.CompareExchange(ref _operating, InProgress, Free) != Free)
                {
                    // If it was already "in-use" check if Dispose was called.
                    ObjectDisposedException.ThrowIf(_disposeCalled, this);

                    Debug.Fail("Only one outstanding async operation is allowed per HttpListenerAsyncEventArgs instance.");
                    // Only one at a time.
                    throw new InvalidOperationException();
                }

                // HttpSendResponseEntityBody can return ERROR_INVALID_PARAMETER if the InternalHigh field of the overlapped
                // is not IntPtr.Zero, so we have to reset this field because we are reusing the Overlapped.
                // When using the IAsyncResult based approach of HttpListenerResponseStream the Overlapped is reinitialized
                // for each operation by the CLR when returned from the OverlappedDataCache.

                InitializeOverlapped(boundHandle);

                _exception        = null;
                _bytesTransferred = 0;
            }
Exemple #27
0
        public override async Task <IOperationResult> ExecutePatchQuery(IndexQueryServerSide query, QueryOperationOptions options, PatchRequest patch, BlittableJsonReaderObject patchArgs, DocumentsOperationContext context, Action <IOperationProgress> onProgress, OperationCancelToken token)
        {
            ObjectDisposedException lastException = null;

            for (var i = 0; i < NumberOfRetries; i++)
            {
                try
                {
                    return(await GetRunner(query).ExecutePatchQuery(query, options, patch, patchArgs, context, onProgress, token));
                }
                catch (ObjectDisposedException e)
                {
                    if (Database.DatabaseShutdown.IsCancellationRequested)
                    {
                        throw;
                    }

                    lastException = e;
                }
            }

            throw CreateRetriesFailedException(lastException);
        }
Exemple #28
0
        public override async Task <IndexEntriesQueryResult> ExecuteIndexEntriesQuery(IndexQueryServerSide query, DocumentsOperationContext context, long?existingResultEtag, OperationCancelToken token)
        {
            ObjectDisposedException lastException = null;

            for (var i = 0; i < NumberOfRetries; i++)
            {
                try
                {
                    return(await GetRunner(query).ExecuteIndexEntriesQuery(query, context, existingResultEtag, token));
                }
                catch (ObjectDisposedException e)
                {
                    if (Database.DatabaseShutdown.IsCancellationRequested)
                    {
                        throw;
                    }

                    lastException = e;
                }
            }

            throw CreateRetriesFailedException(lastException);
        }
Exemple #29
0
        public void Complete()
        {
            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;

            if (etwLog.IsEnabled())
            {
                etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
            }

            lock (_internalTransaction)
            {
                ObjectDisposedException.ThrowIf(Disposed, this);

                if (_complete)
                {
                    throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
                }

                _complete = true;

                Debug.Assert(_internalTransaction.State != null);
                if (_blocking)
                {
                    _internalTransaction.State.CompleteBlockingClone(_internalTransaction);
                }
                else
                {
                    _internalTransaction.State.CompleteAbortingClone(_internalTransaction);
                }
            }

            if (etwLog.IsEnabled())
            {
                etwLog.TransactionDependentCloneComplete(TraceSourceType.TraceSourceLtm, TransactionTraceId, "DependentTransaction");
                etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
            }
        }
Exemple #30
0
        /// <summary>
        /// Attempts to increment the <see cref="System.Threading.CountdownEvent"/>'s current count by a
        /// specified value.
        /// </summary>
        /// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param>
        /// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is
        /// already at zero this will return false.</returns>
        /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less
        /// than 0.</exception>
        /// <exception cref="System.InvalidOperationException">The current instance is already
        /// set.</exception>
        /// <exception cref="System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
        /// cref="int.MaxValue"/>.</exception>
        /// <exception cref="System.ObjectDisposedException">The current instance has already been
        /// disposed.</exception>
        public bool TryAddCount(int signalCount)
        {
            if (signalCount <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(signalCount));
            }

            ObjectDisposedException.ThrowIf(_disposed, this);

            // Loop around until we successfully increment the count.
            int      observedCount;
            SpinWait spin = default;

            while (true)
            {
                observedCount = _currentCount;

                if (observedCount <= 0)
                {
                    return(false);
                }
                else if (observedCount > (int.MaxValue - signalCount))
                {
                    throw new InvalidOperationException(SR.CountdownEvent_Increment_AlreadyMax);
                }

                if (Interlocked.CompareExchange(ref _currentCount, observedCount + signalCount, observedCount) == observedCount)
                {
                    break;
                }

                // The CAS failed.  Spin briefly and try again.
                spin.SpinOnce(sleep1Threshold: -1);
            }

            return(true);
        }
Exemple #31
0
        // Create a clone of the transaction that forwards requests to this object.
        //
        public Transaction Clone()
        {
            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;

            if (etwLog.IsEnabled())
            {
                etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
            }

            ObjectDisposedException.ThrowIf(Disposed, this);

            if (_complete)
            {
                throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
            }

            Transaction clone = InternalClone();

            if (etwLog.IsEnabled())
            {
                etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
            }
            return(clone);
        }
Exemple #32
0
        // Forward request to the state machine to take the appropriate action.
        //
        public Enlistment EnlistVolatile(ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions)
        {
            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;

            if (etwLog.IsEnabled())
            {
                etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
            }

            ObjectDisposedException.ThrowIf(Disposed, this);

            ArgumentNullException.ThrowIfNull(singlePhaseNotification);

            if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
            {
                throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
            }

            if (_complete)
            {
                throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
            }

            lock (_internalTransaction)
            {
                Debug.Assert(_internalTransaction.State != null);
                Enlistment enlistment = _internalTransaction.State.EnlistVolatile(_internalTransaction,
                                                                                  singlePhaseNotification, enlistmentOptions, this);

                if (etwLog.IsEnabled())
                {
                    etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
                }
                return(enlistment);
            }
        }
        /// <summary>
        /// This method retrieves the counter value associated with counter 'counterName'
        /// based on isNumerator parameter.
        /// </summary>
        public override bool GetCounterValue(string counterName, bool isNumerator, out long counterValue)
        {
            counterValue = -1;
            if (_Disposed)
            {
                ObjectDisposedException objectDisposedException =
                    new ObjectDisposedException("PSCounterSetInstance");
                _tracer.TraceException(objectDisposedException);
                return(false);
            }

            // retrieve counter id associated with the counter name
            if (counterName == null)
            {
                ArgumentNullException argNullException = new ArgumentNullException("counterName");
                _tracer.TraceException(argNullException);
                return(false);
            }

            try
            {
                int targetCounterId = this._counterNameToIdMapping[counterName];
                return(this.GetCounterValue(targetCounterId, isNumerator, out counterValue));
            }
            catch (KeyNotFoundException)
            {
                InvalidOperationException invalidOperationException =
                    new InvalidOperationException(
                        string.Format(
                            CultureInfo.InvariantCulture,
                            "Lookup for counter corresponding to counter name {0} failed",
                            counterName));
                _tracer.TraceException(invalidOperationException);
                return(false);
            }
        }
 private static WebSocketException ConvertObjectDisposedException(WebSocketBase webSocket, ObjectDisposedException innerException)
 {
     return new WebSocketException(WebSocketError.InvalidState,
         SR.Format(SR.net_WebSockets_InvalidState_ClosedOrAborted, webSocket.GetType().FullName, webSocket.State),
         innerException);
 }
Exemple #35
0
 static internal ObjectDisposedException ObjectDisposed(object instance)
 {
     ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name);
     return e;
 }
Exemple #36
0
        // This method was originally in an AcceptAsyncResult class but that class got useless.
        private void AcceptCallback(object nullState)
        {
            // We know we need to try completing an accept at first.  Keep going until the queue is empty (inside the lock).
            // At that point, BeginAccept() takes control of restarting the pump if necessary.
            bool acceptNeeded = true;
            Queue acceptQueue = GetAcceptQueue();

            while (acceptNeeded)
            {
                LazyAsyncResult asyncResult = null;
                SocketError errorCode = SocketError.OperationAborted;
                SocketAddress socketAddress = null;
                SafeCloseSocket acceptedSocket = null;
                Exception otherException = null;
                object result = null;

                lock (this)
                {
                    //
                    // Accept Callback - called on the callback path, when we expect to release
                    //  an accept socket that winsock says has completed.
                    //
                    //  While we still have items in our Queued list of Accept Requests,
                    //   we recall the Winsock accept, to attempt to gather new
                    //   results, and then match them again the queued items,
                    //   when accept call returns would_block, we reinvoke ourselves
                    //   and rewait for the next asyc callback.
                    //

                    //
                    // We may not have items in the queue because of possible ----
                    // between re-entering this callback manually and from the thread pool.
                    //
                    if (acceptQueue.Count == 0)
                        break;

                    // pick an element from the head of the list
                    asyncResult = (LazyAsyncResult) acceptQueue.Peek();

                    if (!CleanedUp)
                    {
                        socketAddress = m_RightEndPoint.Serialize();

                        try
                        {
                            // We know we're in non-blocking because of SetAsyncEventSelect().
                            GlobalLog.Assert(!willBlockInternal, "Socket#{0}::AcceptCallback|Socket should be in non-blocking state.", ValidationHelper.HashString(this));
                            acceptedSocket = SafeCloseSocket.Accept(
                                m_Handle,
                                socketAddress.m_Buffer,
                                ref socketAddress.m_Size);

                            errorCode = acceptedSocket.IsInvalid ? (SocketError) Marshal.GetLastWin32Error() : SocketError.Success;

                            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::AcceptCallback() UnsafeNclNativeMethods.OSSOCK.accept returns:" + errorCode.ToString());
                        }
                        catch (ObjectDisposedException)
                        {
                            // Listener socket was closed.
                            errorCode = SocketError.OperationAborted;
                        }
                        catch (Exception exception)
                        {
                            if (NclUtilities.IsFatal(exception)) throw;

                            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::AcceptCallback() caught exception:" + exception.Message + " CleanedUp:" + CleanedUp);
                            otherException = exception;
                        }
                    }

                    if (errorCode == SocketError.WouldBlock && otherException == null)
                    {
                        // The accept found no waiting connections, so start listening for more.
                        try
                        {
                            m_AsyncEvent.Reset(); // reset event to wait for the next client.
                            if (SetAsyncEventSelect(AsyncEventBits.FdAccept))
                                break;
                        }
                        catch (ObjectDisposedException)
                        { 
                            // Handle ---- with Dispose, m_AsyncEvent may have been Close()'d already.
                        }
                        otherException = new ObjectDisposedException(this.GetType().FullName);
                    }

                    // CreateAcceptSocket() must be done before InternalSetBlocking() so that the fixup is correct inside
                    // UpdateAcceptSocket().  InternalSetBlocking() must happen in the lock.
                    if (otherException != null)
                    {
                        result = otherException;
                    }
                    else if (errorCode == SocketError.Success)
                    {
                        result = CreateAcceptSocket(acceptedSocket, m_RightEndPoint.Create(socketAddress), true);
                    }
                    else
                    {
                        asyncResult.ErrorCode = (int) errorCode;
                    }

                    // This request completed, so it can be taken off the queue.
                    acceptQueue.Dequeue();

                    // If the queue is empty, cancel the select and indicate not to loop anymore.
                    if (acceptQueue.Count == 0)
                    {
                        if (!CleanedUp)
                            UnsetAsyncEventSelect();

                        acceptNeeded = false;
                    }
                }

                // Notify about the completion outside the lock.
                try {
                    asyncResult.InvokeCallback(result);
                }
                catch {
                    // Exception from the user callback,
                    // If we need to loop, offload to a different thread and re-throw for debugging
                    if (acceptNeeded)
                        ThreadPool.UnsafeQueueUserWorkItem(new WaitCallback(AcceptCallback), nullState);

                    throw;
                }
            }
        }
        private Stream EnsureNotDisposed()
        {
            Stream str = _managedStream;

            if (str == null)
            {
                ObjectDisposedException ex = new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation);
                ex.SetErrorCode(HResults.RO_E_CLOSED);
                throw ex;
            }

            return str;
        }
        public void SendAsync_CreateAndDisposeAndSend_ThrowsObjectDisposedExceptionWithMessage()
        {
            var cws = new ClientWebSocket();
            cws.Dispose();

            var buffer = new byte[100];
            var segment = new ArraySegment<byte>(buffer);
            var ct = new CancellationToken();

            var expectedException = new ObjectDisposedException(cws.GetType().FullName);

            AssertExtensions.Throws<ObjectDisposedException>(
                () => cws.SendAsync(segment, WebSocketMessageType.Text, false, ct).GetAwaiter().GetResult(),
                expectedException.Message);

            Assert.Equal(WebSocketState.Closed, cws.State);
        }
	// Test the ObjectDisposedException class.
	public void TestObjectDisposedException()
			{
				ObjectDisposedException e;

				e = new ObjectDisposedException("obj");
				AssertEquals("ObjectDisposedException (1)",
							 "obj", e.ObjectName);
				AssertNotNull("ObjectDisposedException (2)", e.Message);
				ExceptionTester.CheckHResult
						("ObjectDisposedException (3)", e,
						 unchecked((int)0x80131509));

				e = new ObjectDisposedException("obj", "msg");
				AssertEquals("ObjectDisposedException (4)",
							 "obj", e.ObjectName);
				AssertEquals("ObjectDisposedException (5)",
							 "obj: msg", e.Message);
				ExceptionTester.CheckHResult
						("ObjectDisposedException (6)", e,
						 unchecked((int)0x80131509));

				e = new ObjectDisposedException(null, "msg");
				AssertNull("ObjectDisposedException (7)", e.ObjectName);
				AssertEquals("ObjectDisposedException (8)",
							 "msg", e.Message);
				ExceptionTester.CheckHResult
						("ObjectDisposedException (9)", e,
						 unchecked((int)0x80131509));
			}
        public void CloseAsync_DisposeAndCloseOutput_ThrowsObjectDisposedExceptionWithMessage()
        {
            var cws = new ClientWebSocket();
            cws.Dispose();

            var expectedException = new ObjectDisposedException(cws.GetType().FullName);

            AssertExtensions.Throws<ObjectDisposedException>(
                () =>
                cws.CloseOutputAsync(WebSocketCloseStatus.Empty, "", new CancellationToken()).GetAwaiter().GetResult(),
                expectedException.Message);

            Assert.Equal(WebSocketState.Closed, cws.State);
        }
Exemple #41
0
		void Cleanup (bool close_existing)
		{
			lock (registry) {
				if (close_existing) {
					// Need to copy this since closing will call UnregisterContext
					ICollection keys = registry.Keys;
					var all = new HttpListenerContext [keys.Count];
					keys.CopyTo (all, 0);
					registry.Clear ();
					for (int i = all.Length - 1; i >= 0; i--)
						all [i].Connection.Close (true);
				}

				lock (connections.SyncRoot) {
					ICollection keys = connections.Keys;
					var conns = new HttpConnection [keys.Count];
					keys.CopyTo (conns, 0);
					connections.Clear ();
					for (int i = conns.Length - 1; i >= 0; i--)
						conns [i].Close (true);
				}
				lock (ctx_queue) {
					var ctxs = (HttpListenerContext []) ctx_queue.ToArray (typeof (HttpListenerContext));
					ctx_queue.Clear ();
					for (int i = ctxs.Length - 1; i >= 0; i--)
						ctxs [i].Connection.Close (true);
				}

				lock (wait_queue) {
					Exception exc = new ObjectDisposedException ("listener");
					foreach (ListenerAsyncResult ares in wait_queue) {
						ares.Complete (exc);
					}
					wait_queue.Clear ();
				}
			}
		}
        /// <summary>
        /// This method retrieves the counter value associated with counter 'counterId'
        /// based on isNumerator parameter.
        /// </summary>
        public override bool GetCounterValue(int counterId, bool isNumerator, out long counterValue)
        {
            counterValue = -1;
            if (_Disposed)
            {
                ObjectDisposedException objectDisposedException =
                    new ObjectDisposedException("PSCounterSetInstance");
                _tracer.TraceException(objectDisposedException);
                return false;
            }
            int targetCounterId;
            if (base.RetrieveTargetCounterIdIfValid(counterId, isNumerator, out targetCounterId))
            {
                CounterData targetCounterData = _CounterSetInstance.Counters[targetCounterId];

                if (targetCounterData != null)
                {
                    counterValue = targetCounterData.Value;
                    return true;
                }
                else
                {
                    InvalidOperationException invalidOperationException =
                        new InvalidOperationException(
                            String.Format(
                            CultureInfo.InvariantCulture,
                            "Lookup for counter corresponding to counter id {0} failed",
                            counterId));
                    _tracer.TraceException(invalidOperationException);
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// This method retrieves the counter value associated with counter 'counterName'
        /// based on isNumerator parameter.
        /// </summary>
        public override bool GetCounterValue(string counterName, bool isNumerator, out long counterValue)
        {
            counterValue = -1;
            if (_Disposed)
            {
                ObjectDisposedException objectDisposedException =
                    new ObjectDisposedException("PSCounterSetInstance");
                _tracer.TraceException(objectDisposedException);
                return false;
            }

            // retrieve counter id associated with the counter name
            if (counterName == null)
            {
                ArgumentNullException argNullException = new ArgumentNullException("counterName");
                _tracer.TraceException(argNullException);
                return false;
            }
            try
            {
                int targetCounterId = this._counterNameToIdMapping[counterName];
                return this.GetCounterValue(targetCounterId, isNumerator, out counterValue);
            }
            catch (KeyNotFoundException)
            {
                InvalidOperationException invalidOperationException =
                    new InvalidOperationException(
                        String.Format(
                        CultureInfo.InvariantCulture,
                        "Lookup for counter corresponding to counter name {0} failed",
                        counterName));
                _tracer.TraceException(invalidOperationException);
                return false;
            }
        }
 protected Exception ConvertObjectDisposedException(ObjectDisposedException originalException, TransferOperation transferOperation)
 {
     if (_timeoutErrorString != null)
     {
         return ConvertTimeoutErrorException(originalException, transferOperation, _timeoutErrorString, _timeoutErrorTransferOperation);
     }
     else if (_aborted)
     {
         return new CommunicationObjectAbortedException(SR.SocketConnectionDisposed, originalException);
     }
     else
     {
         return originalException;
     }
 }