public bool ReadBoolean(PipeReader pipe, JsonReaderState state) => Read(pipe, state, BooleanReader);
 public double ReadDouble(PipeReader pipe, JsonReaderState state) => Read(pipe, state, DoubleReader);
 public float ReadSingle(PipeReader pipe, JsonReaderState state) => Read(pipe, state, SingleReader);
 public uint ReadUInt32(PipeReader pipe, JsonReaderState state) => Read(pipe, state, UInt32Reader);
 public virtual void Attach(PipeReader reader)
 {
     this.Reader = reader;
 }
 public int ReadInt32(PipeReader pipe, JsonReaderState state) => Read(pipe, state, Int32Reader);
Beispiel #7
0
 /// <summary>
 /// Creates a <see cref="PipeReader"/> that can read no more than a given number of bytes from an underlying reader.
 /// </summary>
 /// <param name="reader">The <see cref="PipeReader"/> to read from.</param>
 /// <param name="length">The number of bytes to read from the parent <paramref name="reader"/>.</param>
 /// <returns>A reader that ends after <paramref name="length"/> bytes are read.</returns>
 public static PipeReader ReadSlice(this PipeReader reader, long length) => new NestedPipeReader(reader, length);
Beispiel #8
0
 public TestPipeReader(PipeReader pipeReader)
 {
     _pipeReader = pipeReader;
 }
Beispiel #9
0
 public Server(PipeReader input, PipeWriter output)
     : this(options => options.WithInput(input).WithOutput(output))
 {
 }
Beispiel #10
0
 public Application(PipeWriter writer, PipeReader reader, IMessageProtocol messageProtocol)
 {
     _messageProtocol = messageProtocol;
     _pipeWriter      = writer;
     _pipeReader      = reader;
 }
Beispiel #11
0
 public static PipeReader ByteArrayToStream(byte[] data)
 {
     return(PipeReader.Create(new MemoryStream(data), new StreamPipeReaderOptions(bufferSize: 2880)));
 }
Beispiel #12
0
 public MyConnection(PipeReader reader)
 {
     this.reader = reader;
 }
Beispiel #13
0
        public async Task OperationCancelledExceptionNotSwallowedIfNotThrownFromSpecifiedToken()
        {
            PipeReader reader = PipeReader.Create(new ThrowsOperationCanceledExceptionStream());

            await Assert.ThrowsAsync <OperationCanceledException>(async() => await reader.ReadAsync());
        }
Beispiel #14
0
 public void NullStreamThrows()
 {
     Assert.Throws <ArgumentNullException>(() => PipeReader.Create(null));
 }
Beispiel #15
0
 /// <summary>
 /// Wraps a <see cref="PipeReader"/> in another object that will report when <see cref="PipeReader.Complete(Exception)"/> is called.
 /// </summary>
 /// <param name="reader">The reader to be wrapped.</param>
 /// <param name="callback">
 /// The callback to invoke when the <see cref="PipeReader.Complete(Exception)"/> method is called.
 /// If this delegate throws an exception it will propagate to the caller of the <see cref="PipeReader.Complete(Exception)"/> method.
 /// </param>
 /// <param name="state">An optional state object to supply to the <paramref name="callback"/>.</param>
 /// <returns>The wrapped <see cref="PipeReader"/> which should be exposed to have its <see cref="PipeReader.Complete(Exception)"/> method called.</returns>
 /// <remarks>
 /// If the <see cref="PipeReader"/> has already been completed, the provided <paramref name="callback"/> may never be invoked.
 /// </remarks>
 public static PipeReader OnCompleted(this PipeReader reader, Action <Exception?, object?> callback, object?state = null) => new PipeReaderCompletionWatcher(reader, callback, state);
Beispiel #16
0
 private static ValueTask <int> Read7BitEncodedIntAsync(this PipeReader reader, CancellationToken token)
 => reader.ReadAsync <int, SevenBitEncodedIntReader>(new SevenBitEncodedIntReader(5), token);
Beispiel #17
0
 public static Stream AsStream(this PipeReader pipeReader) => pipeReader.AsStream(leaveOpen: false);
Beispiel #18
0
 private static PipeReader CreateFakePipeReader()
 {
     return(PipeReader.Create(Stream.Null));
 }
Beispiel #19
0
 /// <summary>
 /// Decodes string asynchronously from pipe.
 /// </summary>
 /// <param name="reader">The pipe reader.</param>
 /// <param name="lengthFormat">Represents string length encoding format.</param>
 /// <param name="context">The text decoding context.</param>
 /// <param name="token">The token that can be used to cancel the operation.</param>
 /// <returns>The decoded string.</returns>
 /// <exception cref="EndOfStreamException"><paramref name="reader"/> doesn't contain the necessary number of bytes to restore string.</exception>
 /// <exception cref="OperationCanceledException">The operation has been canceled.</exception>
 /// <exception cref="ArgumentOutOfRangeException"><paramref name="lengthFormat"/> is invalid.</exception>
 public static async ValueTask <string> ReadStringAsync(this PipeReader reader, StringLengthEncoding lengthFormat, DecodingContext context, CancellationToken token = default)
 => await ReadStringAsync(reader, await reader.ReadLengthAsync(lengthFormat, token).ConfigureAwait(false), context, token).ConfigureAwait(false);
Beispiel #20
0
        private async Task ReadPipeAsync(PipeReader client, CancellationToken cancellationToken)
        {
            try
            {
                var tasks = new List <Task>();
                while (!cancellationToken.IsCancellationRequested)
                {
                    var        read = client.ReadAsync(cancellationToken);
                    ReadResult result;
                    if (read.IsCompleted)
                    {
                        result = await read;
                    }
                    else
                    {
                        var readTask = read.AsTask();
                        tasks.Add(readTask);
                        while (!read.IsCompleted)
                        {
                            var completed = await Task.WhenAny(tasks).ConfigureAwait(false);

                            if (!read.IsCompleted)
                            {
                                tasks.Remove(completed);
                                await completed.ConfigureAwait(false);
                            }
                        }
                        tasks.Remove(readTask);
                        result = await readTask.ConfigureAwait(false);
                    }
                    var buffer = result.Buffer;

                    bool success;
                    do
                    {
                        success = false;
                        if (buffer.Length < 4)
                        {
                            break;
                        }
                        var length = BinaryPrimitives.ReadUInt32BigEndian(buffer.Slice(0, 4).ToMemory().Span);
                        if (buffer.Length >= length + 4)
                        {
                            var data    = buffer.Slice(4, length).ToMemory();
                            var message = new OmmMessage(data);
                            if (message.IsReply)
                            {
                                //dispatch reply
                                if (!_pending.TryGetValue(message.MessageId, out var request))
                                {
                                    throw new InvalidDataException("unexpected reply");
                                }
                                request.Reply = message;
                            }
                            else
                            {
                                tasks.Add(_messageCallback(message, cancellationToken));
                            }
                            buffer  = buffer.Slice(4).Slice(length);
                            success = true;
                        }
                    } while (success && buffer.Length >= 4);
                    if (result.IsCompleted)
                    {
                        break;
                    }
                    client.AdvanceTo(buffer.Start, buffer.End);
                }
                client.Complete();
            }
            catch (OperationCanceledException ex)
            {
                Console.WriteLine("cancelled in ClientConnection.ReadPipeAsync");
                client.Complete(ex);
            }
        }
Beispiel #21
0
 /// <summary>
 /// Reads value of blittable type from pipe.
 /// </summary>
 /// <typeparam name="T">The blittable type to decode.</typeparam>
 /// <param name="reader">The pipe reader.</param>
 /// <param name="token">The token that can be used to cancel operation.</param>
 /// <returns>The decoded value.</returns>
 /// <exception cref="OperationCanceledException">The operation has been canceled.</exception>
 public static ValueTask <T> ReadAsync <T>(this PipeReader reader, CancellationToken token = default)
     where T : unmanaged
 => ReadAsync <T, ValueReader <T> >(reader, new ValueReader <T>(), token);
 public long ReadInt64(PipeReader pipe, JsonReaderState state) => Read(pipe, state, Int64Reader);
Beispiel #23
0
 /// <summary>
 /// Reads the block of memory.
 /// </summary>
 /// <param name="reader">The pipe reader.</param>
 /// <param name="output">The block of memory to fill from the pipe.</param>
 /// <param name="token">The token that can be used to cancel operation.</param>
 /// <returns>The task representing asynchronous state of the operation.</returns>
 /// <exception cref="EndOfStreamException">Reader doesn't have enough data.</exception>
 public static async ValueTask ReadBlockAsync(this PipeReader reader, Memory <byte> output, CancellationToken token = default)
 => await ReadAsync <Missing, MemoryReader>(reader, new MemoryReader(output), token).ConfigureAwait(false);
 public string ReadString(PipeReader pipe, JsonReaderState state) => Read(pipe, state, StringReader);
Beispiel #25
0
 public static ValueTask ReadAsync(this PipeReader reader, Memory <byte> output, CancellationToken token = default)
 => ReadBlockAsync(reader, output, token);
 public ulong ReadUInt64(PipeReader pipe, JsonReaderState state) => Read(pipe, state, UInt64Reader);
Beispiel #27
0
 /// <summary>
 /// Reads the block of memory.
 /// </summary>
 /// <param name="reader">The pipe reader.</param>
 /// <param name="output">The block of memory to fill from the pipe.</param>
 /// <param name="token">The token that can be used to cancel operation.</param>
 /// <returns>The actual number of copied bytes.</returns>
 public static ValueTask <int> CopyToAsync(this PipeReader reader, Memory <byte> output, CancellationToken token = default)
 => ReadAsync <int, MemoryReader>(reader, new MemoryReader(output), token);
 public decimal ReadDecimal(PipeReader pipe, JsonReaderState state) => Read(pipe, state, DecimalReader);
Beispiel #29
0
        internal static async ValueTask ComputeHashAsync(this PipeReader reader, HashAlgorithm algorithm, int?count, Memory <byte> output, CancellationToken token)
        {
            using var builder = await reader.ReadAsync <HashBuilder, HashReader>(new HashReader (algorithm, count), token).ConfigureAwait(false);

            builder.Build(output.Span);
        }
Beispiel #30
0
 protected virtual void ConfigureServerInputOutput(PipeReader clientOutput, PipeWriter serverInput, DebugAdapterServerOptions options) =>
 options.WithInput(clientOutput).WithOutput(serverInput);
        /// <summary>
        /// Begins to execute the specified command asynchronously.
        /// </summary>
        /// <param name="text">The command text.</param>
        /// <returns>The SSH command.</returns>
        protected SshCommand BeginCommand(string text)
        {
            lock (this.sync)
            {
                // If the client is not connected, throw an exception.
                if (this.state != ClientState.Connected)
                {
                    throw new SshException("Cannot execute the command on the SSH server because the client is not connected.");
                }
                // If the current client is null, do nothing.
                if (null == this.client)
                {
                    throw new SshException("Cannot execute the command on the SSH server because the previous connection has already been released.");
                };
                // If the current client is not connected, disconnect the client.
                if (!this.client.IsConnected)
                {
                    // Change the state.
                    this.state = ClientState.Disconnected;
                    // Show a disconnected message.
                    this.ShowMessage(
                        Resources.ServerBusy_32, "Connection Failed", "The connection to the SSH server \'{0}\' failed unexpectedly.".FormatWith(this.client.ConnectionInfo.Host),
                        false, (int)ApplicationConfig.MessageCloseDelay.TotalMilliseconds,
                        (object[] parameters) =>
                        {
                            // Call the disconnecting event handler.
                            this.OnDisconnecting(this.client.ConnectionInfo);
                            // Call the disconnected event handler.
                            this.OnDisconnected(this.client.ConnectionInfo);
                        });
                    // Dispose the clinet.
                    this.client.Dispose();
                    this.client = null;
                    // Throw an exception.
                    throw new SshException("Cannot execute the command on the SSH server because the connection failed.");
                }

                // Create a new command for the current text.
                SshCommand command = this.client.CreateCommand(text);

                // Call the event handler.
                this.OnCommandBeginInternal(command);

                // Add a new command info object to the commands set.
                this.commands.Add(command);

                // Beginn execute the command asynchronously.
                IAsyncResult asyncResult = command.BeginExecute(this.OnEndCommand, command);

                // Get the command data.
                ThreadPool.QueueUserWorkItem((object state) =>
                {
                    // Set the stream as blocking.
                    command.OutputStream.BlockLastReadBuffer = true;
                    // Read the command data.
                    using (PipeReader reader = new PipeReader(command.OutputStream))
                    {
                        // While the command is not completed.
                        while (!asyncResult.IsCompleted)
                        {
                            // Read all current data in a string.
                            string data = reader.ReadToEnd();
                            // If the string null or empty, continue.
                            if (string.IsNullOrEmpty(data))
                            {
                                continue;
                            }
                            // Call the event handler event handler.
                            this.OnCommandDataInternal(command, data);
                        }
                    }
                });

                // Return the command.
                return command;
            }
        }