Exemple #1
0
        /// <summary>
        /// Registers a signal with the <see cref="System.Threading.CountdownEvent"/>, decrementing its
        /// count.
        /// </summary>
        /// <returns>true if the signal caused the count to reach zero and the event was set; otherwise,
        /// false.</returns>
        /// <exception cref="System.InvalidOperationException">The current instance is already set.
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">The current instance has already been
        /// disposed.</exception>
        public bool Signal()
        {
            ObjectDisposedException.ThrowIf(_disposed, this);
            Debug.Assert(_event != null);

            if (_currentCount <= 0)
            {
                throw new InvalidOperationException(SR.CountdownEvent_Decrement_BelowZero);
            }

            int newCount = Interlocked.Decrement(ref _currentCount);

            if (newCount == 0)
            {
                _event.Set();
                return(true);
            }
            else if (newCount < 0)
            {
                //if the count is decremented below zero, then throw, it's OK to keep the count negative, and we shouldn't set the event here
                //because there was a thread already which decremented it to zero and set the event
                throw new InvalidOperationException(SR.CountdownEvent_Decrement_BelowZero);
            }

            return(false);
        }
Exemple #2
0
    /// <inheritdoc/>
    public override void WriteLine(ReadOnlySpan <char> value)
    {
        ObjectDisposedException.ThrowIf(_disposed, nameof(HttpResponseStreamWriter));

        Write(value);
        Write(NewLine);
    }
Exemple #3
0
        private void ThrowNoReceive()
        {
            ObjectDisposedException.ThrowIf(_receiverClosed, typeof(TestWebSocket));

            // _senderClosed must be true.
            throw new IOException("The remote end closed the connection.", new ObjectDisposedException(typeof(TestWebSocket).FullName));
        }
Exemple #4
0
        /// <summary>
        /// Gets the PromotedToken for the transaction.
        ///
        /// If the transaction has not already been promoted, retrieving this value will cause promotion. Before retrieving the
        /// PromotedToken, the Transaction.PromoterType value should be checked to see if it is a promoter type (Guid) that the
        /// caller understands. If the caller does not recognize the PromoterType value, retrieving the PromotedToken doesn't
        /// have much value because the caller doesn't know how to utilize it. But if the PromoterType is recognized, the
        /// caller should know how to utilize the PromotedToken to communicate with the promoting distributed transaction
        /// coordinator to enlist on the distributed transaction.
        ///
        /// If the value of a transaction's PromoterType is TransactionInterop.PromoterTypeDtc, then that transaction's
        /// PromotedToken will be an MSDTC-based TransmitterPropagationToken.
        /// </summary>
        /// <returns>
        /// The byte[] that can be used to enlist with the distributed transaction coordinator used to promote the transaction.
        /// The format of the byte[] depends upon the value of Transaction.PromoterType.
        /// </returns>
        public byte[] GetPromotedToken()
        {
            // We need to ask the current transaction state for the PromotedToken because depending on the state
            // we may need to induce a promotion.
            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;

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

            ObjectDisposedException.ThrowIf(Disposed, this);

            // We always make a copy of the promotedToken stored in the internal transaction.
            byte[] internalPromotedToken;
            lock (_internalTransaction)
            {
                Debug.Assert(_internalTransaction.State != null);
                internalPromotedToken = _internalTransaction.State.PromotedToken(_internalTransaction);
            }

            byte[] toReturn = new byte[internalPromotedToken.Length];
            Array.Copy(internalPromotedToken, toReturn, toReturn.Length);
            return(toReturn);
        }
Exemple #5
0
        public IAsyncResult BeginCommit(AsyncCallback?asyncCallback, object?asyncState)
        {
            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;

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

            ObjectDisposedException.ThrowIf(Disposed, this);

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

                Debug.Assert(_internalTransaction.State != null);
                // this.complete will get set to true when the transaction enters a state that is
                // beyond Phase0.
                _internalTransaction.State.BeginCommit(_internalTransaction, true, asyncCallback, asyncState);
            }

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

            return(this);
        }
Exemple #6
0
        // Create a dependent clone of the transaction that forwards requests to this object.
        //
        public DependentTransaction DependentClone(
            DependentCloneOption cloneOption
            )
        {
            TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;

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

            if (cloneOption != DependentCloneOption.BlockCommitUntilComplete &&
                cloneOption != DependentCloneOption.RollbackIfNotComplete)
            {
                throw new ArgumentOutOfRangeException(nameof(cloneOption));
            }

            ObjectDisposedException.ThrowIf(Disposed, this);

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

            DependentTransaction clone = new DependentTransaction(
                _isoLevel, _internalTransaction, cloneOption == DependentCloneOption.BlockCommitUntilComplete);

            if (etwLog.IsEnabled())
            {
                etwLog.TransactionCloneCreate(clone, "DependentTransaction");
                etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
            }
            return(clone);
        }
Exemple #7
0
        public byte[] ComputeHash(Stream inputStream)
        {
            ObjectDisposedException.ThrowIf(_disposed, this);

            // Use ArrayPool.Shared instead of CryptoPool because the array is passed out.
            byte[] buffer = ArrayPool <byte> .Shared.Rent(4096);

            int bytesRead;
            int clearLimit = 0;

            while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                if (bytesRead > clearLimit)
                {
                    clearLimit = bytesRead;
                }

                HashCore(buffer, 0, bytesRead);
            }

            CryptographicOperations.ZeroMemory(buffer.AsSpan(0, clearLimit));
            ArrayPool <byte> .Shared.Return(buffer, clearArray : false);

            return(CaptureHashCodeAndReinitialize());
        }
Exemple #8
0
        public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
        {
            if (millisecondsTimeout < -1)
            {
                throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
            }

            ObjectDisposedException.ThrowIf(_disposed, this);
            cancellationToken.ThrowIfCancellationRequested();

            // Check whether the event is already set.  This is checked instead of this.IsSet, as this.Signal
            // will first decrement the count and then if it's 0 will set the event, thus it's possible
            // we could observe this.IsSet as true while _event.IsSet is false; that could in turn lead
            // a caller to think it's safe to use Reset, while an operation is still in flight calling _event.Set.
            bool returnValue = _event.IsSet;

            // If not completed yet, wait on the event.
            if (!returnValue)
            {
                // ** the actual wait
                returnValue = _event.Wait(millisecondsTimeout, cancellationToken);
                //the Wait will throw OCE itself if the token is canceled.
            }

            return(returnValue);
        }
Exemple #9
0
        public virtual HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            ArgumentNullException.ThrowIfNull(request);

            ObjectDisposedException.ThrowIf(_disposed, this);

            if (ShouldSendWithTelemetry(request))
            {
                HttpTelemetry.Log.RequestStart(request);

                try
                {
                    return(_handler.Send(request, cancellationToken));
                }
                catch when(LogRequestFailed(telemetryStarted: true))
                {
                    // Unreachable as LogRequestFailed will return false
                    throw;
                }
                finally
                {
                    HttpTelemetry.Log.RequestStop();
                }
            }
            else
            {
                return(_handler.Send(request, cancellationToken));
            }
        }
Exemple #10
0
    // Reads a line. A line is defined as a sequence of characters followed by
    // a carriage return ('\r'), a line feed ('\n'), or a carriage return
    // immediately followed by a line feed. The resulting string does not
    // contain the terminating carriage return and/or line feed. The returned
    // value is null if the end of the input stream has been reached.
    /// <inheritdoc />
    public override string?ReadLine()
    {
        ObjectDisposedException.ThrowIf(_disposed, nameof(HttpRequestStreamReader));

        StringBuilder?sb = null;
        var           consumeLineFeed = false;

        while (true)
        {
            if (_charBufferIndex == _charsRead)
            {
                if (ReadIntoBuffer() == 0)
                {
                    // reached EOF, we need to return null if we were at EOF from the beginning
                    return(sb?.ToString());
                }
            }

            var stepResult = ReadLineStep(ref sb, ref consumeLineFeed);

            if (stepResult.Completed)
            {
                return(stepResult.Result ?? sb?.ToString());
            }
        }
    }
 private void CheckDisposedOrStarted()
 {
     ObjectDisposedException.ThrowIf(_disposed, this);
     if (_handler != null)
     {
         throw new InvalidOperationException(SR.net_http_operation_started);
     }
 }
        public static void Throw_Type()
        {
            Type type = new object().GetType();
            ObjectDisposedException ex = AssertExtensions.Throws <ObjectDisposedException>(
                () => ObjectDisposedException.ThrowIf(true, type));

            Assert.Equal("System.Object", ex.ObjectName);
        }
        public static void Throw_Object()
        {
            var obj = new object();
            ObjectDisposedException ex = AssertExtensions.Throws <ObjectDisposedException>(
                () => ObjectDisposedException.ThrowIf(true, obj));

            Assert.Equal("System.Object", ex.ObjectName);
        }
Exemple #14
0
        public byte[] ComputeHash(byte[] buffer)
        {
            ObjectDisposedException.ThrowIf(_disposed, this);
            ArgumentNullException.ThrowIfNull(buffer);

            HashCore(buffer, 0, buffer.Length);
            return(CaptureHashCodeAndReinitialize());
        }
Exemple #15
0
        public void Send(string from, string recipients, string?subject, string?body)
        {
            ObjectDisposedException.ThrowIf(_disposed, this);
            //validation happens in MailMessage constructor
            MailMessage mailMessage = new MailMessage(from, recipients, subject, body);

            Send(mailMessage);
        }
 public override void ImportEncryptedPkcs8PrivateKey(
     ReadOnlySpan <char> password,
     ReadOnlySpan <byte> source,
     out int bytesRead)
 {
     ObjectDisposedException.ThrowIf(_disposed, this);
     base.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead);
 }
        /// <summary>
        /// Import the public key into CNG
        /// </summary>
        /// <returns></returns>
        public CngKey Import()
        {
            ObjectDisposedException.ThrowIf(_disposed, this);

#pragma warning disable SYSLIB0043 // ToByteArray is obsolete.
            return(CngKey.Import(ToByteArray(), _curveName, BlobFormat));

#pragma warning restore SYSLIB0043
        }
Exemple #18
0
        private (string, string) ValidateWriteEntryArguments(string fileName, string?entryName)
        {
            ObjectDisposedException.ThrowIf(_isDisposed, this);
            ArgumentException.ThrowIfNullOrEmpty(fileName);

            string fullPath        = Path.GetFullPath(fileName);
            string?actualEntryName = string.IsNullOrEmpty(entryName) ? Path.GetFileName(fileName) : entryName;

            return(fullPath, actualEntryName);
        }
Exemple #19
0
        /// <summary>
        ///   Retrieves the hash or Hash-based Message Authentication Code (HMAC) for the data
        ///   accumulated from prior calls to the
        ///   <see cref="AppendData(ReadOnlySpan{byte})" />
        ///   methods, without resetting the object to its initial state.
        /// </summary>
        /// <param name="destination">
        ///   The buffer to receive the hash or HMAC value.
        /// </param>
        /// <returns>
        ///   The number of bytes written to <paramref name="destination"/>.
        /// </returns>
        /// <exception cref="ArgumentException">
        ///   <paramref name="destination"/> has a <see cref="Span{T}.Length"/> value less
        ///   than <see cref="HashLengthInBytes"/>.
        /// </exception>
        /// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
        public int GetCurrentHash(Span <byte> destination)
        {
            ObjectDisposedException.ThrowIf(_disposed, this);
            if (destination.Length < HashLengthInBytes)
            {
                throw new ArgumentException(SR.Argument_DestinationTooShort, nameof(destination));
            }

            return(GetCurrentHashCore(destination));
        }
Exemple #20
0
        public Task <byte[]> ComputeHashAsync(
            Stream inputStream,
            CancellationToken cancellationToken = default)
        {
            ArgumentNullException.ThrowIfNull(inputStream);

            ObjectDisposedException.ThrowIf(_disposed, this);

            return(ComputeHashAsyncCore(inputStream, cancellationToken));
        }
Exemple #21
0
        /// <summary>
        /// Notifies the <see cref="Barrier"/> that there will be fewer participants.
        /// </summary>
        /// <param name="participantCount">The number of additional participants to remove from the barrier.</param>
        /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="participantCount"/> is less than
        /// 0.</exception>
        /// <exception cref="System.InvalidOperationException">The barrier already has 0 participants.</exception>
        /// <exception cref="System.InvalidOperationException">
        /// The method was invoked from within a post-phase action.
        /// </exception>
        /// <exception cref="System.ObjectDisposedException">The current instance has already been
        /// disposed.</exception>
        public void RemoveParticipants(int participantCount)
        {
            ObjectDisposedException.ThrowIf(_disposed, this);

            if (participantCount < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(participantCount), participantCount,
                                                      SR.Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange);
            }

            // in case of this is called from the PHA
            if (_actionCallerID != 0 && Environment.CurrentManagedThreadId == _actionCallerID)
            {
                throw new InvalidOperationException(SR.Barrier_InvalidOperation_CalledFromPHA);
            }

            SpinWait spinner = default;

            while (true)
            {
                int  currentTotal = _currentTotalCount;
                int  total;
                int  current;
                bool sense;
                GetCurrentTotal(currentTotal, out current, out total, out sense);

                if (total < participantCount)
                {
                    throw new ArgumentOutOfRangeException(nameof(participantCount),
                                                          SR.Barrier_RemoveParticipants_ArgumentOutOfRange);
                }
                if (total - participantCount < current)
                {
                    throw new InvalidOperationException(SR.Barrier_RemoveParticipants_InvalidOperation);
                }
                // If the remaining participants = current participants, then finish the current phase
                int remaingParticipants = total - participantCount;
                if (remaingParticipants > 0 && current == remaingParticipants)
                {
                    if (SetCurrentTotal(currentTotal, 0, total - participantCount, !sense))
                    {
                        FinishPhase(sense);
                        break;
                    }
                }
                else
                {
                    if (SetCurrentTotal(currentTotal, current, total - participantCount, sense))
                    {
                        break;
                    }
                }
                spinner.SpinOnce(sleep1Threshold: -1);
            }
        }
Exemple #22
0
        /// <summary>
        /// Asynchronously writes the specified entry into the archive stream.
        /// </summary>
        /// <param name="entry">The tar entry to write.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param>
        /// <remarks><para>Before writing an entry to the archive, if you wrote data into the entry's <see cref="TarEntry.DataStream"/>, make sure to rewind it to the desired start position.</para>
        /// <para>These are the entry types supported for writing on each format:</para>
        /// <list type="bullet">
        /// <item>
        /// <para><see cref="TarEntryFormat.V7"/></para>
        /// <list type="bullet">
        /// <item><see cref="TarEntryType.Directory"/></item>
        /// <item><see cref="TarEntryType.HardLink"/></item>
        /// <item><see cref="TarEntryType.SymbolicLink"/></item>
        /// <item><see cref="TarEntryType.V7RegularFile"/></item>
        /// </list>
        /// </item>
        /// <item>
        /// <para><see cref="TarEntryFormat.Ustar"/>, <see cref="TarEntryFormat.Pax"/> and <see cref="TarEntryFormat.Gnu"/></para>
        /// <list type="bullet">
        /// <item><see cref="TarEntryType.BlockDevice"/></item>
        /// <item><see cref="TarEntryType.CharacterDevice"/></item>
        /// <item><see cref="TarEntryType.Directory"/></item>
        /// <item><see cref="TarEntryType.Fifo"/></item>
        /// <item><see cref="TarEntryType.HardLink"/></item>
        /// <item><see cref="TarEntryType.RegularFile"/></item>
        /// <item><see cref="TarEntryType.SymbolicLink"/></item>
        /// </list>
        /// </item>
        /// </list>
        /// </remarks>
        /// <exception cref="ObjectDisposedException">The archive stream is disposed.</exception>
        /// <exception cref="InvalidOperationException">The entry type of the <paramref name="entry"/> is not supported for writing.</exception>
        /// <exception cref="IOException">An I/O problem occurred.</exception>
        public Task WriteEntryAsync(TarEntry entry, CancellationToken cancellationToken = default)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(Task.FromCanceled(cancellationToken));
            }

            ObjectDisposedException.ThrowIf(_isDisposed, this);
            ArgumentNullException.ThrowIfNull(entry);
            return(WriteEntryAsyncInternal(entry, cancellationToken));
        }
        protected override void InsertItem(int index, AlternateView item)
        {
            ObjectDisposedException.ThrowIf(_disposed, this);

            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            base.InsertItem(index, item);
        }
Exemple #24
0
        public static void SetObjectProperty(this JSObject self, string name, object?value, bool createIfNotExists = true, bool hasOwnProperty = false)
        {
            ArgumentNullException.ThrowIfNull(self);
            ObjectDisposedException.ThrowIf(self.IsDisposed, self);

            Interop.Runtime.SetObjectPropertyRef(self.JSHandle, name, in value, createIfNotExists, hasOwnProperty, out int exception, out object res);
            if (exception != 0)
            {
                throw new JSException($"Error setting {name} on (js-obj js '{self.JSHandle}'): {res}");
            }
        }
Exemple #25
0
        protected override void SetItem(int index, LinkedResource item)
        {
            ObjectDisposedException.ThrowIf(_disposed, this);

            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            base.SetItem(index, item);
        }
Exemple #26
0
        public virtual Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            ArgumentNullException.ThrowIfNull(request);

            ObjectDisposedException.ThrowIf(_disposed, this);

            if (ShouldSendWithTelemetry(request))
            {
                return(SendAsyncWithTelemetry(_handler, request, cancellationToken));
            }

            return(_handler.SendAsync(request, cancellationToken));
Exemple #27
0
        public void SendAsyncCancel()
        {
            ObjectDisposedException.ThrowIf(_disposed, this);

            if (!InCall || _cancelled)
            {
                return;
            }

            _cancelled = true;
            Abort();
        }
Exemple #28
0
        /// <summary>
        ///   Retrieves the hash or Hash-based Message Authentication Code (HMAC) for the data
        ///   accumulated from prior calls to the
        ///   <see cref="AppendData(ReadOnlySpan{byte})" />
        ///   methods, without resetting the object to its initial state.
        /// </summary>
        /// <returns>
        ///   The computed hash or HMAC.
        /// </returns>
        /// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
        public byte[] GetCurrentHash()
        {
            ObjectDisposedException.ThrowIf(_disposed, this);

            byte[] ret = new byte[HashLengthInBytes];

            int written = GetCurrentHashCore(ret);

            Debug.Assert(written == HashLengthInBytes);

            return(ret);
        }
Exemple #29
0
    /// <inheritdoc/>
    public override void Write(char value)
    {
        ObjectDisposedException.ThrowIf(_disposed, nameof(HttpResponseStreamWriter));

        if (_charBufferCount == _charBufferSize)
        {
            FlushInternal(flushEncoder: false);
        }

        _charBuffer[_charBufferCount] = value;
        _charBufferCount++;
    }
Exemple #30
0
 public static object Invoke(this JSObject self, string method, params object?[] args)
 {
     ArgumentNullException.ThrowIfNull(self);
     ObjectDisposedException.ThrowIf(self.IsDisposed, self);
     Interop.Runtime.InvokeJSWithArgsRef(self.JSHandle, method, args, out int exception, out object res);
     if (exception != 0)
     {
         throw new JSException((string)res);
     }
     JSHostImplementation.ReleaseInFlight(res);
     return(res);
 }