EndRead() public method

public EndRead ( IAsyncResult asyncResult ) : int
asyncResult IAsyncResult
return int
Esempio n. 1
1
        public static void StreamReadAsync(
            Stream stream,
            byte[] buffer,
            int offset,
            int count,
            SynchronizationContextWrapper syncContext,
            Action<int, Exception> callback)
        {
            Exception error = null;
            int length = 0;
            try
            {
                stream.BeginRead(buffer, offset, count,
                    delegate(IAsyncResult ar)
                    {
                        try
                        {
                            length = stream.EndRead(ar);
                        }
                        catch (Exception e)
                        {
                            error = e;
                        }

                        callback(length, error);
                    },
                    null);
            }
            catch (Exception e)
            {
                error = e;
                callback(length, error);
            }
        }
Esempio n. 2
1
		private static Task<int> ReadTask(Stream stream, byte[] buffer, int offset, int count, object state)
		{
			var tcs = new TaskCompletionSource<int>();
			stream.BeginRead(buffer, offset, count, ar =>
			{
				try { tcs.SetResult(stream.EndRead(ar)); }
				catch (Exception exc) { tcs.SetException(exc); }
			}, state);
			return tcs.Task;
		}
Esempio n. 3
1
 public static int ReadStream(Stream stream, byte[] buffer, int offset, int count, int timeout)
 {
     if (stream == null || buffer == null || buffer.Length < (offset + count))
         return -1;
     IAsyncResult arRead = stream.BeginRead(buffer, offset, count, null, null);
     if (!arRead.AsyncWaitHandle.WaitOne(timeout))
     {
         throw new TimeoutException("Could not read within the timeout period.");
     }
     return stream.EndRead(arRead);
 }
Esempio n. 4
1
        public bool Connect()
        {
            try
            {
                //_socket.Connect(host, port);
                var connect_result = _socket.BeginConnect(host, port, null, null);
                if(!connect_result.AsyncWaitHandle.WaitOne(1500))
                {
                    throw new Exception();
                }
                _socket.EndConnect(connect_result);
            }
            catch
            {
                this.Destruct("Failed to connect.", true);
                return false;
            }
            _stream = _socket.GetStream();
            isConnected = true;
            Program._RconBox.SomethingToSend.Enabled = true;
            byte[] buff = new byte[1];
            AsyncCallback callback = null;
            callback = ar =>
            {
                try
                {
                    int bytes = _stream.EndRead(ar);

                    //Program._RconBox.OutputBox.Text += buff;
                    Program.wattosend.Add(buff[0]);
                    buff[0] = 0;

                    if (!this.isConnected || bytes == 0)
                    {
                        this.Destruct("Disconnected!");
                        return;
                    }

                    _stream.BeginRead(buff, 0, 1, callback, null);
                }
                catch
                {
                    this.Destruct("Reading has failed");
                }
            };
            _stream.BeginRead(buff, 0, 1, callback, null);
            this.Send("set redrawcmd false");
            this.Send("login " + this.pass);
            return true;
        }
        static IEnumerable<Task> CopyStream(Stream input, Stream output)
        {
            var buffer = new byte[0x2000];

            while (true)
            {
                // Create task to read from the input stream
                var read = Task<int>.Factory.FromAsync((buf, offset, count, callback, state) =>
                                                           {
                                                               Console.WriteLine("Issuing BeginRead");
                                                               return input.BeginRead(buf, offset, count, callback, state);
                                                           },
                                                           ar =>
                                                               {
                                                                   Console.WriteLine("Read completed");
                                                                   return input.EndRead(ar);
                                                               },
                                                               buffer, 0, buffer.Length, null);

                yield return read;

                // If we read no data, return
                if (read.Result == 0) break;

                // Create task to write to the output stream
                yield return Task.Factory.FromAsync((buf, offset, count, callback, state) =>
                                                           {
                                                               Console.WriteLine("Issuing BeginWrite");
                                                               return output.BeginWrite(buf, offset, count, callback, state);
                                                           },
                                                           ar =>
                                                               {
                                                                   Console.WriteLine("Write completed");
                                                                   output.EndWrite(ar);
                                                               }, buffer, 0, read.Result, null);
            }
        }
Esempio n. 6
0
 public override int EndRead(
     IAsyncResult asyncResult
     )
 {
     Trace.WriteLine("TraceStream", "EndRead()");
     return(m_in.EndRead(asyncResult));
 }
Esempio n. 7
0
        public override int EndRead(IAsyncResult ares)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(typeof(RequestStream).ToString());
            }

            if (ares == null)
            {
                throw new ArgumentNullException("async_result");
            }

            if (ares is HttpStreamAsyncResult)
            {
                HttpStreamAsyncResult r = (HttpStreamAsyncResult)ares;
                if (!ares.IsCompleted)
                {
                    ares.AsyncWaitHandle.WaitOne();
                }
                return(r.SynchRead);
            }

            // Close on exception?
            int nread = stream.EndRead(ares);

            if (remaining_body > 0 && nread > 0)
            {
                remaining_body -= nread;
            }
            return(nread);
        }
Esempio n. 8
0
        /// <summary>
        /// Pipes data from one stream to another
        /// </summary>
        /// <param name="input">Stream to read from</param>
        /// <param name="output">Stream to write to</param>
        /// <param name="MaxBufferSize">Size of buffer to use</param>
        /// <returns>Number of bytes piped</returns>
        public static int Pipe(Stream input, Stream output, int MaxBufferSize)
        {
            //Internal buffer are two buffers, each half of allowed buffer size, aligned to 1kb blocks
            int bufferSize = (MaxBufferSize / 2) & ~1023;
            if (bufferSize <= 0) throw new Exception("Specified buffer size to small");

            byte[][] buffer = new byte[2][];
            buffer[0] = new byte[bufferSize];
            buffer[1] = new byte[bufferSize];
            int currentBuffer = 0;

            int r, total=0;
            IAsyncResult asyncRead,asyncWrite;

            //Read first block
            r = input.Read(buffer[currentBuffer], 0, bufferSize);

            //Continue while we're getting data
            while (r > 0)
            {
                //read and write simultaneously
                asyncWrite = output.BeginWrite(buffer[currentBuffer], 0, r, null, null);
                asyncRead = input.BeginRead(buffer[1-currentBuffer], 0, bufferSize, null, null);
                //Wait for both
                output.EndWrite(asyncWrite);
                r = input.EndRead(asyncRead);
                //Switch buffers
                currentBuffer = 1 - currentBuffer;
                //Count bytes
                total += r;
            }

            //Return number of bytes piped
            return total;
        }
Esempio n. 9
0
    public bool VerifyEndReadException(System.IO.Stream serialStream, IAsyncResult asyncResult, Type expectedException)
    {
        bool retValue = true;

        try
        {
            serialStream.EndRead(asyncResult);

            if (null != expectedException)
            {
                Console.WriteLine("ERROR!!!: No Excpetion was thrown");
                retValue = false;
            }
        }
        catch (System.Exception e)
        {
            if (null == expectedException)
            {
                Console.WriteLine("ERROR!!!: Expected no exception to be thrown and {0} was thrown", e);
                retValue = false;
            }
            else if (e.GetType() != expectedException)
            {
                Console.WriteLine("ERROR!!!:  Expected {0} to be thrown and the following exception was thrown:\n{1}", expectedException, e);
                retValue = false;
            }
        }
        return(retValue);
    }
Esempio n. 10
0
        private static string ReadDataFromStream(Stream str)
        {
            var buff = new byte[10000];
            var asyncResult = str.BeginRead(buff, 0, buff.Length, null, null);

            var bytesRead = str.EndRead(asyncResult);
            return Encoding.UTF8.GetString(buff, 0, bytesRead);
        }
        private IAsyncResult OnEnter(Object sender, EventArgs e, AsyncCallback cb, Object state) {
            Debug.Assert(_inputStream == null);
            _app = (HttpApplication)sender;
            HttpContext context = _app.Context;
            HttpRequest request = context.Request;
            HttpWorkerRequest wr = context.WorkerRequest;
            HttpAsyncResult httpAsyncResult = new HttpAsyncResult(cb, state);
            AsyncPreloadModeFlags asyncPreloadMode = context.AsyncPreloadMode;
            int contentLength;
            bool isForm = false;
            bool isFormMultiPart = false;

            if (asyncPreloadMode == AsyncPreloadModeFlags.None
                || request.ReadEntityBodyMode != ReadEntityBodyMode.None
                || wr == null
                || !wr.SupportsAsyncRead
                || !wr.HasEntityBody()
                || wr.IsEntireEntityBodyIsPreloaded()
                || context.Handler == null
                || context.Handler is TransferRequestHandler
                || context.Handler is DefaultHttpHandler
                || (contentLength = request.ContentLength) > RuntimeConfig.GetConfig(context).HttpRuntime.MaxRequestLengthBytes
                || ((isForm = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "application/x-www-form-urlencoded"))
                    && (asyncPreloadMode & AsyncPreloadModeFlags.Form) != AsyncPreloadModeFlags.Form)
                || ((isFormMultiPart = StringUtil.StringStartsWithIgnoreCase(request.ContentType, "multipart/form-data"))
                    && (asyncPreloadMode & AsyncPreloadModeFlags.FormMultiPart) != AsyncPreloadModeFlags.FormMultiPart)
                || !isForm && !isFormMultiPart && (asyncPreloadMode & AsyncPreloadModeFlags.NonForm) != AsyncPreloadModeFlags.NonForm
                ) {
                Debug.Trace("AsyncPreload", " *** AsyncPreload skipped *** ");
                httpAsyncResult.Complete(true, null, null);
                return httpAsyncResult;
            }

            Debug.Trace("AsyncPreload", " *** AsyncPreload started *** ");
            try {
                if (_callback == null) {
                    _callback = new AsyncCallback(OnAsyncCompletion);
                }
                _inputStream = request.GetBufferedInputStream();
                byte[] buffer = _app.EntityBuffer;
                int bytesRead = 0;
                // loop to prevent recursive calls and potential stack overflow if/when it completes synchronously
                do {
                    IAsyncResult readAsyncResult = _inputStream.BeginRead(buffer, 0, buffer.Length, _callback, httpAsyncResult);
                    if (!readAsyncResult.CompletedSynchronously) {
                        return httpAsyncResult;
                    }
                    bytesRead = _inputStream.EndRead(readAsyncResult);
                } while (bytesRead != 0);
            }
            catch {
                Reset();
                throw;
            }
            httpAsyncResult.Complete(true, null, null);
            return httpAsyncResult;
        }
Esempio n. 12
0
            protected void RecvCallback(IAsyncResult ar)
            {
                ResultHandler rh     = (ResultHandler)ar.AsyncState;
                int           result = mStream.EndRead(ar);

                if (result == 0)
                {
                    result = MoSync.Constants.CONNERR_CLOSED;
                }
                rh(mHandle, MoSync.Constants.CONNOP_READ, result);
            }
Esempio n. 13
0
        void dataReceivedSsh(IAsyncResult i)
        {
            byte[] buffer = (byte[])i.AsyncState;
            int    nBytes = sshStreamRead.EndRead(i);

            if (nBytes != 0)
            {
                processBytes(buffer, nBytes);
            }
            startStreamAsyncRead();
        }
Esempio n. 14
0
 private static int EndRead(Stream stream, IAsyncResult ar, byte[] buffer)
 {
     try
     {
         return stream.EndRead(ar);
     }
     catch (Exception)
     {
         return stream.ReadAsync(buffer).Result;
     }
 }
Esempio n. 15
0
 private static void ReadUnsignedVarint(
     Stream stream,
     Bcp.ReadState readState,
     ProcessReadVarint processReadVarint,
     BcpDelegate.ExceptionHandler exceptionHandler)
 {
     var buffer = new byte[1];
     var i = 0;
     uint result = 0U;
     AsyncCallback asyncCallback = null;
     asyncCallback = asyncResult =>
     {
         try
         {
             int numBytesRead = stream.EndRead(asyncResult);
             if (numBytesRead != 1)
             {
                 exceptionHandler(new EndOfStreamException());
             }
             uint b = buffer[0];
             if (i < 32)
             {
                 if (b >= 0x80)
                 {
                     result |= ((b & 0x7f) << i);
                     i += 7;
                     stream.BeginRead(buffer, 0, 1, asyncCallback, readState);
                 }
                 else
                 {
                     result |= (b << i);
                     processReadVarint(result);
                 }
             }
             else
             {
                 exceptionHandler(new BcpException.VarintTooBig());
             }
         }
         catch (Exception e)
         {
             exceptionHandler(e);
         }
     };
     try
     {
         stream.BeginRead(buffer, 0, 1, asyncCallback, readState);
     }
     catch (Exception e)
     {
         exceptionHandler(e);
     }
 }
        private void SslRead(IAsyncResult ar)
        {
            if (m_IsDisposed)
            {
                return;
            }

            try
            {
                int byteCount  = -1;
                int bufferSize = m_Buffer.Length;

                m_LastRead   = DateTime.Now;
                byteCount    = m_NetworkStream.EndRead(ar);
                m_BytesRead += byteCount;

                if (!m_HasHeaders || m_RequestType == RequestType.GET)
                {
                    string sBuffer = Encoding.ASCII.GetString(m_Buffer, 0, byteCount);
                    m_ReadData += sBuffer;
                }

                AppendBuffer(m_Buffer, byteCount);
                m_HasHeaders = UpdateUniqueHeaders();

                if (!m_HasHeaders && m_BytesRead > 1024)
                {
                    Program.BlacklistIP(m_RemoteIP, m_ReadData, "No HTTP headers found in the first 1024 bytes");
                    return;
                }

                if (byteCount > 0)
                {
                    if (m_RequestType != RequestType.POST && m_RequestType != RequestType.None)
                    {
                        m_NetworkStream.BeginRead(m_Buffer, 0, bufferSize, new AsyncCallback(SslRead), m_NetworkStream);
                    }
                    else if (m_EndBoundaryIndex == -1)     // as long as we haven't found the end of the stream continue reading
                    {
                        m_NetworkStream.BeginRead(m_Buffer, 0, bufferSize, new AsyncCallback(SslRead), m_NetworkStream);
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                return;
            }

            ProcessRequest(m_ReadData);
        }
 public bool StreamContainsSeqeunce(Stream contentStream)
 {
     int num;
     if (contentStream == null)
     {
         throw new ArgumentNullException("contentStream");
     }
     if (this.FSequence == null)
     {
         throw new ArgumentNullException("sequence");
     }
     if (this.FSequence.Length == 0)
     {
         return false;
     }
     byte[] buffer = new byte[0x40000];
     byte[] buffer2 = new byte[0x40000];
     byte[] buffer3 = buffer;
     byte[] buffer4 = buffer2;
     int offset = 0;
     bool flag = false;
     IAsyncResult asyncResult = contentStream.BeginRead(buffer3, 0, buffer3.Length, null, null);
     do
     {
         if (!base.OnProgress(0))
         {
             break;
         }
         num = contentStream.EndRead(asyncResult);
         if (num > 0)
         {
             buffer3 = Interlocked.Exchange<byte[]>(ref buffer4, buffer3);
             int num3 = offset;
             offset = Math.Min(this.FSequence.Length - 1, num);
             asyncResult = contentStream.BeginRead(buffer3, offset, buffer3.Length - offset, null, null);
             flag = ByteArrayHelper.IndexOf(this.FSequence, buffer4, buffer4.Length) >= 0;
             Array.Copy(buffer4, (num + num3) - offset, buffer3, 0, offset);
         }
         else
         {
             asyncResult = null;
         }
     }
     while ((num > 0) && !flag);
     if (asyncResult != null)
     {
         contentStream.EndRead(asyncResult);
     }
     return flag;
 }
        private static AsyncEvent StreamCopy(Stream src, Stream dst, Func<bool> assertContinuation, Action onException = null, Action<int> onProgress = null)
        {
            var evt = new AsyncEvent(false, false);
            var exception = false;
            AsyncCallback cb = null;
            cb = (ar) =>
            {
                var count = src.EndRead(ar);
                var readed = (byte[])ar.AsyncState;
                if (exception) return;

                if (count != 0)
                {
                    lock (evt)
                    {
                        if (exception) return;
                        var newArray = new byte[BLOCK_SIZE];
                        if (!assertContinuation())
                         return;

                        if (onProgress != null)
                            onProgress(count);

                        src.BeginRead(newArray, 0, BLOCK_SIZE, cb, newArray);
                        try
                        {
                            dst.Write(readed, 0, count);
                        }
                        catch (Exception e)
                        {
                            exception = true;
                            if(onException != null)
                                onException();

                        }
                    }
                }
                else
                {
                    lock (evt)
                    {
                        src.Close();
                        evt.Set();
                    }
                }
            };
            var startBuffer = new byte[BLOCK_SIZE];
            src.BeginRead(startBuffer, 0, BLOCK_SIZE, cb, startBuffer);
            return evt;
        }
        /// <summary>
        /// Ends reading from stream
        /// </summary>
        /// <param name="stream">Stream to stop reading from</param>
        /// <param name="ar">Result of reading</param>
        /// <returns></returns>
        public Int32 EndReadFrom(Stream stream, IAsyncResult ar)
        {
            if (_connection.State == IrcConnectionState.Opened)
            {
                var read = stream.EndRead(ar);

                if (read > 0)
                {
                    _count += read;
                }

                var str = IrcDefinition.Encoding.GetString(_buffer, 0, _count);
                return read;
            }
            else
            {
                return 0;
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Read from a stream asynchronously.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="length">The number of bytes to read.</param>
        /// <param name="completed">The completed action.</param>
        /// <param name="error">The error action.</param>
        public static void ReadAsync(this System.IO.Stream stream, int length, Action <byte[]> completed, Action <Exception> error)
        {
            var buff = new byte[length];

            stream.BeginRead(
                buff,
                0,
                length,
                ar =>
            {
                try
                {
                    byte[] bytes = null;
                    try
                    {
                        var len = stream.EndRead(ar);
                        bytes   = len < 1
                                  ? new byte[0]
                                  : len < length
                                    ? stream.ReadBytes(buff, len, length - len)
                                    : buff;
                    }
                    catch
                    {
                        bytes = new byte[0];
                    }

                    if (completed != null)
                    {
                        completed(bytes);
                    }
                }
                catch (Exception ex)
                {
                    if (error != null)
                    {
                        error(ex);
                    }
                }
            },
                null);
        }
Esempio n. 21
0
        public static BodyAction FromStream(Stream stream)
        {
            return (next, error, complete) =>
            {
                var buffer = new byte[4096];
                var continuation = new AsyncCallback[1];
                bool[] stopped = {false};
                continuation[0] = result =>
                {
                    if (result != null && result.CompletedSynchronously) return;
                    try
                    {
                        for (;;)
                        {
                            if (result != null)
                            {
                                var count = stream.EndRead(result);
                                if (stopped[0]) return;
                                if (count <= 0)
                                {
                                    complete();
                                    return;
                                }
                                var data = new ArraySegment<byte>(buffer, 0, count);
                                if (next(data, () => continuation[0](null))) return;
                            }

                            if (stopped[0]) return;
                            result = stream.BeginRead(buffer, 0, buffer.Length, continuation[0], null);
                            if (!result.CompletedSynchronously) return;
                        }
                    }
                    catch (Exception ex)
                    {
                        error(ex);
                    }
                };
                continuation[0](null);
                return () => { stopped[0] = true; };
            };
        }
Esempio n. 22
0
      private static IEnumerator<Int32> CopyStream(AsyncEnumerator<Int64> ae, Stream source, Stream destination, Int32 bufferSize, Action<Int64> reportProgress) {
         Byte[] buffer = new Byte[bufferSize];
         Int64 totalBytesRead = 0;
         while (true) {
            ae.SetOperationTag("Reading from source stream");
            // Read whichever is smaller (number of bytes left to read OR the buffer size)
            source.BeginRead(buffer, 0, buffer.Length, ae.End(), null);
            yield return 1;
            Int32 bytesReadThisTime = source.EndRead(ae.DequeueAsyncResult());
            totalBytesRead += bytesReadThisTime;

            ae.SetOperationTag("Writing to destination stream");
            destination.BeginWrite(buffer, 0, bytesReadThisTime, ae.End(), null);
            yield return 1;
            destination.EndWrite(ae.DequeueAsyncResult());

            if (reportProgress != null) reportProgress(totalBytesRead);
            if (bytesReadThisTime < buffer.Length) break;
         }
         ae.Result = totalBytesRead;
      }
Esempio n. 23
0
        public static IEnumerable<CompletionPort> ReadBytesAsync(AsyncMachine<byte[]> machine, Stream stream, int length)
        {
            var attributeHelper = new AttributeHelper<VhdHeader>();
            var buffer = new byte[length];

            int readCount = 0;
            int remaining = length;
            while (remaining > 0)
            {
                stream.BeginRead(buffer, readCount, remaining, machine.CompletionCallback, null);
                yield return CompletionPort.SingleOperation;
                var currentRead = stream.EndRead(machine.CompletionResult);
                if (currentRead == 0)
                {
                    break;
                }
                readCount += currentRead;
                remaining -= currentRead;
            }
            machine.ParameterValue = buffer;
            yield break;
        }
Esempio n. 24
0
        public static IEnumerator<int> ReadBytes(
            byte[] buffer, Stream stream, AsyncEnumerator ae, string type, bool expectedToHaveNoData)
        {
            var totalBytesRead = 0;

            while (totalBytesRead < buffer.Length)
            {
                stream.BeginRead(buffer, totalBytesRead, buffer.Length - totalBytesRead, ae.End(), null);

                yield return 1;

                int bytesRead = stream.EndRead(ae.DequeueAsyncResult());

                if(bytesRead == 0)
                {
                    if (expectedToHaveNoData)
                        yield break;

                    throw new InvalidOperationException("Could not read value for " + type);
                }

                totalBytesRead += bytesRead;
            }
        }
 public override int EndRead(IAsyncResult asyncResult)
 {
     return(_innerStream.EndRead(asyncResult));
 }
Esempio n. 26
0
 private CopyItemAction CopyStreamAsync(Stream sourceStream, Stream destStream, IVirtualItem sourceItem, IVirtualItem destItem)
 {
     object obj2;
     lock ((obj2 = this.FSnapshotLock))
     {
         this.FCopyMode = CopyMode.Async;
     }
     if (this.Buffer2 == null)
     {
         this.Buffer2 = new byte[this.Buffer1.Length];
     }
     byte[] buffer = this.Buffer1;
     byte[] buffer2 = this.Buffer2;
     int count = 0;
     ProcessedSize processed = CreateFileProcessed(sourceStream, sourceItem);
     if (!((processed.Total <= buffer.Length) || this.RaiseFileProgress(ref processed)))
     {
         return CopyItemAction.SkipUndoDest;
     }
     IAsyncResult asyncResult = sourceStream.BeginRead(buffer, 0, buffer.Length, null, null);
     do
     {
         count = sourceStream.EndRead(asyncResult);
         if (base.CheckCancellationPending())
         {
             return CopyItemAction.SkipUndoDest;
         }
         IAsyncResult result2 = destStream.BeginWrite(buffer, 0, count, null, null);
         byte[] buffer3 = buffer;
         if (count > 0)
         {
             asyncResult = sourceStream.BeginRead(buffer2, 0, buffer2.Length, null, null);
             buffer2 = Interlocked.Exchange<byte[]>(ref buffer, buffer2);
         }
         try
         {
             destStream.EndWrite(result2);
         }
         catch (IOException exception)
         {
             CopyItemAction action = this.HandleCopyIOException(destItem, sourceItem, destItem, destStream, buffer3, count, exception);
             if (action != CopyItemAction.Next)
             {
                 return action;
             }
         }
         lock ((obj2 = this.FSnapshotLock))
         {
             this.FTotalProcessed.AddProcessedSize((long) count);
         }
         this.RaiseProgress();
         processed.AddProcessedSize((long) count);
         if (!this.RaiseFileProgress(ref processed))
         {
             return CopyItemAction.SkipUndoDest;
         }
     }
     while (count > 0);
     return CopyItemAction.Next;
 }
        private static int FileReadStreamSeekAndCompare(Stream fileStream, byte[] bufferToCompare, long offset, int readSize, int expectedReadCount, bool isAsync)
        {
            byte[] testBuffer = new byte[readSize];

            if (isAsync)
            {
                using (ManualResetEvent waitHandle = new ManualResetEvent(false))
                {
                    IAsyncResult result = fileStream.BeginRead(testBuffer, 0, readSize, ar => waitHandle.Set(), null);
                    waitHandle.WaitOne();
                    int readCount = fileStream.EndRead(result);
                    Assert.AreEqual(expectedReadCount, readCount);
                }
            }
            else
            {
                int readCount = fileStream.Read(testBuffer, 0, readSize);
                Assert.AreEqual(expectedReadCount, readCount);
            }

            for (int i = 0; i < expectedReadCount; i++)
            {
                Assert.AreEqual(bufferToCompare[i + offset], testBuffer[i]);
            }

            return expectedReadCount;
        }
Esempio n. 28
0
        private Result<int> Read(Action<string> activity, Stream stream, byte[] buffer, int offset, int count, Result<int> result)
        {
            // asynchronously execute read operation
            Result<IAsyncResult> inner = new Result<IAsyncResult>(TimeSpan.MaxValue);
            inner.WhenDone(delegate(Result<IAsyncResult> _unused) {
                try {
                    activity(string.Format("pre {0}!EndRead", stream.GetType().FullName));
                    int readCount = stream.EndRead(inner.Value);
                    activity("post EndRead");
                    result.Return(readCount);
                } catch(Exception e) {
                    activity("throw Read 1");
                    result.Throw(e);
                }
            });
            try {
                activity(string.Format("pre {0}!BeginRead", stream.GetType().FullName));
                stream.BeginRead(buffer, offset, count, inner.Return, stream);
                activity("post BeginRead");
            } catch(Exception e) {
                activity("throw Read 2");
                result.Throw(e);
            }

            // return yield handle
            return result;
        }
        public static void StreamReadAsync(
            Stream stream, 
            byte[] buffer, 
            int offset, 
            int count, 
            SynchronizationContextWrapper syncContext, 
            Action<int, Exception> callback)
        {
            Debug.Assert(syncContext != null);

            stream.BeginRead(
                buffer,
                offset,
                count,
                delegate(IAsyncResult ar)
                {
                    if (ar.IsCompleted)
                    {
                        int bytesRead = 0;
                        Exception error = null;

                        try
                        {
                            bytesRead = stream.EndRead(ar);
                        }
                        catch (IOException ioe)
                        {
                            error = ioe;
                        }
                        finally
                        {
                            syncContext.Post(() => callback(bytesRead, error));
                        }
                    }
                },
                null);
        }
        // All of this download code could be abstracted
        // and put in a helper class.
        private void Download (Stream st)
        {
            long cLength = (response.ContentLength + range);

            if (cLength == 0) {
                return;
            }

            int nread = -1;
            int offset = 0;

            int length = (cLength == -1 || cLength > 8192) ? 8192 : (int) cLength;

            Stream dest = null;
            readTimeoutHandle = new AutoResetEvent (false);

            byte[] buffer = null;

            bool dataDownload = false;
            bool writeToStream = false;

            if (type != DownloadType.String) {
                tsm.TotalBytes = cLength;
                tsm.BytesReceivedPreviously = range;
            }

            switch (type) {
                case DownloadType.String:
                case DownloadType.Data:
                    dataDownload = true;

                    if (cLength != -1) {
                        length = (int) cLength;
                        buffer = new byte[cLength];
                    } else {
                        writeToStream = true;
                        buffer = new byte[length];
                        dest = OpenMemoryStream ();
                    }
                    break;
                case DownloadType.File:
                    writeToStream = true;
                    buffer = new byte [length];
                    if (localFile == null) {
                        dest = OpenLocalFile (fileName);
                    } else {
                        dest = localFile;
                    }

                    break;
            }

            registeredTimeoutHandle = ThreadPool.RegisterWaitForSingleObject (
                readTimeoutHandle, new WaitOrTimerCallback (OnTimeout), null, timeout, false
            );

            IAsyncResult ar;

            while (nread != 0) {
                // <hack>
                // Yeah, Yeah, Yeah, I'll change this later,
                // it's here to get around abort issues.

                ar = st.BeginRead (buffer, offset, length, null, null);
                nread = st.EndRead (ar);

                // need an auxiliary downloader class to replace this.
                // </hack>

                readTimeoutHandle.Set ();

                if (writeToStream) {
                    dest.Write (buffer, 0, nread);
                } else {
                    offset += nread;
                    length -= nread;
                }

                if (type != DownloadType.String) {
                    tsm.AddBytes (nread);
                }
            }

            CleanUpHandles ();

            if (type != DownloadType.String) {
                if (tsm.TotalBytes == -1) {
                    tsm.TotalBytes = tsm.BytesReceived;
                }
            }

            if (dataDownload) {
                if (writeToStream) {
                    result = memoryStream.ToArray ();
                } else {
                    result = buffer;
                }
            }
        }
Esempio n. 31
0
        static string ReadLineWithTimeout(Stream strm, ref byte[] buffer, ref int filled, TimeSpan timeout)
        {
            if (buffer == null) buffer = new byte[8192];
            while (true) {
                for (int i = 0; i < filled; i++) {
                    if (buffer[i] == '\r' || buffer[i] == '\n') {
                        string ret = Encoding.UTF8.GetString (buffer, 0, i);
                        if (i + 1 < filled) {
                            Array.Copy (buffer, i + 1, buffer, 0, filled - i - 1);
                            filled -= i + 1;
                        } else {
                            filled = 0;
                        }
                        return ret.Trim ('\n', '\r', '\0');
                    }
                }

                IAsyncResult ar = strm.BeginRead (buffer, filled, buffer.Length - filled, null, null);
                if (!ar.AsyncWaitHandle.WaitOne (timeout))
                    throw new TimeoutException ();
                int read_size = strm.EndRead (ar);
                if (read_size <= 0)
                    throw new IOException ();
                filled += read_size;
                if (buffer.Length == filled)
                    Array.Resize<byte> (ref buffer, buffer.Length * 2);
            }
        }
Esempio n. 32
0
		public static string ReceiveWithTimeout (Stream stream, int size, int timeout, out bool timed_out)
		{
			byte [] bytes = new byte [size];
			IAsyncResult ares = stream.BeginRead (bytes, 0, size, null, null);
			timed_out = !ares.AsyncWaitHandle.WaitOne (timeout, false);
			if (timed_out)
				return null;
			int nread = stream.EndRead (ares);
			return Encoding.ASCII.GetString (bytes, 0, nread);
		}
Esempio n. 33
0
        public int RunCommand(string command, Stream stdoutOutput, TextWriter stderrOutput)
        {
            m_channel = GetChannelExec(command);

            System.IO.Stream stdout = m_channel.getInputStream();

            System.IO.Stream stderr = ((ChannelExec)m_channel).getErrStream();

            m_channel.connect();



            byte[] stdoutByteBuffer = new byte[1024];

            byte[] stderrByteBuffer = new byte[32];



            ////////////////////////////////////////////////////////////////////////////

            bool stdoutIsExhausted = false;

            AsyncCallback stdoutReadCallback = null;

            stdoutReadCallback = readResult =>
            {
                int bytesRead = stdout.EndRead(readResult);

                if (bytesRead > 0)
                {
                    stdoutOutput.Write(

                        stdoutByteBuffer,

                        0,

                        bytesRead

                        );

                    stdout.BeginRead(stdoutByteBuffer, 0, stdoutByteBuffer.Length, stdoutReadCallback, null);
                }

                else if (bytesRead < 0)
                {
                    stdoutOutput.Flush();

                    stdoutIsExhausted = true;
                }
            };

            ////////////////////////////////////////////////////////////////////////////

            bool stderrIsExhausted = false;

            AsyncCallback stderrReadCallback = null;

            stderrReadCallback = readResult =>
            {
                int bytesRead = stderr.EndRead(readResult);

                if (bytesRead > 0)
                {
                    string text = System.Text.ASCIIEncoding.ASCII.GetString(stderrByteBuffer, 0, bytesRead);

                    text = text.Replace("\n", Environment.NewLine);

                    stderrOutput.Write(text);

                    stderr.BeginRead(stderrByteBuffer, 0, stderrByteBuffer.Length, stderrReadCallback, null);
                }

                else if (bytesRead < 0)
                {
                    stderrIsExhausted = true;
                }
            };

            ////////////////////////////////////////////////////////////////////////////



            stdout.BeginRead(stdoutByteBuffer, 0, stdoutByteBuffer.Length, stdoutReadCallback, null);

            stderr.BeginRead(stderrByteBuffer, 0, stderrByteBuffer.Length, stderrReadCallback, null);



            while (!(stdoutIsExhausted && stderrIsExhausted))
            {
                // empty loop; wait until reads are complete before returning
            }



            m_channel.disconnect();

            return(m_channel.getExitStatus());
        }
 /// <summary>
 /// Ends to read bytes
 /// </summary>
 /// <param name="this">This Stream</param>
 /// <param name="result">The IAsyncResult representing the result of the Begin operation</param>
 public static void EndReadBytes(this Stream @this, IAsyncResult result)
 => @this.EndRead(result)
 ;
Esempio n. 35
0
 private void readComplete(IAsyncResult result, Stream stream)
 {
     int bytesRead = stream.EndRead(result);
     var chunk = _chunks[_chunks.Count - 1];
     chunk.Length += bytesRead;
     if (_dataEvent != null)
     {
         var newBytes = new byte[bytesRead];
         Array.Copy(chunk.Data, chunk.Length - bytesRead, newBytes, 0, bytesRead);
         _dataEvent(newBytes);
     }
     if (_textEvent != null)
     {
         var newChars = new char[bytesRead + 1]; // can have at most one char buffered up in the decoder, plus bytesRead new chars
         int bytesUsed, charsUsed;
         bool completed;
         _decoder.Convert(chunk.Data, chunk.Length - bytesRead, bytesRead, newChars, 0, newChars.Length, false, out bytesUsed, out charsUsed, out completed);
         Ut.Assert(completed); // it could still be halfway through a character; what this means is that newChars was large enough to accommodate everything
         _textEvent(new string(newChars, 0, charsUsed));
     }
     if (bytesRead > 0) // continue reading
         ReadBegin(stream);
     else
     {
         Ended = true;
         if (_textEvent != null)
         {
             var newChars = new char[1];
             int bytesUsed, charsUsed;
             bool completed;
             _decoder.Convert(new byte[0], 0, 0, newChars, 0, newChars.Length, true, out bytesUsed, out charsUsed, out completed);
             Ut.Assert(completed);
             if (charsUsed > 0)
                 _textEvent(new string(newChars, 0, charsUsed));
         }
     }
 }
Esempio n. 36
0
        private static MemoryStream ReadStreamToMemoryStream(Stream inputStream)
        {
            int bytesRead = 0;
            var buffer = new byte[4096];

            MemoryStream result = new MemoryStream();

            do
            {
                IAsyncResult asyncRead = inputStream.BeginRead(buffer, 0, buffer.Length, null, null);

                if (asyncRead.AsyncWaitHandle.WaitOne(250))
                {
                    bytesRead = inputStream.EndRead(asyncRead);
                    result.Write(buffer, 0, bytesRead);
                }
            } while (bytesRead == buffer.Length);
            return result;
        }
Esempio n. 37
0
        private static int SafeRead(Stream readStream, byte[] packet)
        {
            try {
                if (null == readStream)
                    return 0;

                var ar = readStream.BeginRead(packet, 0, packet.Length, null, null);
                int result = readStream.EndRead(ar);
                return result;
            }
            catch (IOException) {
                return 0;
            }
            catch (OperationCanceledException) {
                return 0;
            }
            catch (Exception ex) {
                return 0;
            }
        }
 private static int ReadBuffersAsync(Stream stream1, Stream stream2, Buffers buffers, int readSize)
 {
     int offset = 0;
     int num2 = 0;
     int num3 = 1;
     int num4 = 1;
     do
     {
         IAsyncResult asyncResult = null;
         IAsyncResult result2 = null;
         if (num3 > 0)
         {
             asyncResult = stream1.BeginRead(buffers.Buffer1, offset, readSize - offset, null, null);
         }
         if (num4 > 0)
         {
             result2 = stream2.BeginRead(buffers.Buffer2, num2, readSize - num2, null, null);
         }
         if (asyncResult != null)
         {
             num3 = stream1.EndRead(asyncResult);
         }
         if (result2 != null)
         {
             num4 = stream2.EndRead(result2);
         }
         offset += num3;
         num2 += num4;
     }
     while (((num3 != 0) || (num4 != 0)) && ((offset != readSize) || (num2 != readSize)));
     if (offset == num2)
     {
         return offset;
     }
     return -1;
 }
Esempio n. 39
0
        private static int SafeRead(Stream readStream, byte[] packet, TimeSpan waitSpan)
        {
            try {
                if (TimeSpan.Zero >= waitSpan)
                    return readStream.Read(packet, 0, packet.Length);

                var tempPacket = new byte[packet.Length];

                var ar = readStream.BeginRead(tempPacket, 0, tempPacket.Length, null, null);

                var waitInterval = MinReadTimeSpan > waitSpan ? waitSpan : MinReadTimeSpan;
                DateTime start = DateTime.Now;
                do {
                    Thread.Sleep(waitInterval);
                    if (ar.IsCompleted) {
                        break;
                    }
                } while ((DateTime.Now - start) <= waitInterval);

                if (ar.IsCompleted) {
                    var readLength = readStream.EndRead(ar);
                    Array.Copy(tempPacket, packet, readLength);
                    return readLength;
                }
                readStream.Close();
                readStream.Dispose();
                return -1;
            }
            catch (IOException) {
                return 0;
            }
            catch (OperationCanceledException) {
                return 0;
            }
            catch (Exception ex) {
                return 0;
            }
        }
Esempio n. 40
0
        private void CopyStreamAsync(Stream input, Stream output, bool flushInput, bool flushOutput, StreamCopyCompletedDelegate completed)
        {
            byte[] buffer = new byte[1024 * 4];
            var asyncOp = System.ComponentModel.AsyncOperationManager.CreateOperation(null);

            Action<Exception> done = e =>
            {
                if (completed != null) asyncOp.Post(delegate
                    {
                        completed(input, output, e);
                    }, null);
            };

            AsyncCallback rc = null;
            rc = readResult =>
            {
                try
                {
                    int read = input.EndRead(readResult);
                    if (read > 0)
                    {
                        if (flushInput) input.Flush();
                        output.BeginWrite(buffer, 0, read, writeResult =>
                        {
                            try
                            {
                                output.EndWrite(writeResult);
                                if (flushOutput) output.Flush();
                                input.BeginRead(buffer, 0, buffer.Length, rc, null);
                            }
                            catch (Exception exc) { done(exc); }
                        }, null);
                    }
                    else done(null);
                }
                catch (Exception exc) { done(exc); }
            };

            input.BeginRead(buffer, 0, buffer.Length, rc, null);
        }
Esempio n. 41
0
 public override int EndRead(IAsyncResult asyncResult)
 {
     lock (_stream)
         return(_stream.EndRead(asyncResult));
 }