PipeStream is a thread-safe read/write data stream for use between two threads in a single-producer/single-consumer type problem.
Update on 2008/10/9 1.1 - uses Monitor instead of Manual Reset events for more elegant synchronicity.
Inheritance: Stream
Exemple #1
0
 public void CanWriteTest()
 {
     PipeStream target = new PipeStream(); // TODO: Initialize to an appropriate value
     bool actual;
     actual = target.CanWrite;
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Exemple #2
0
        public void Read()
        {
            const int sleepTime = 100;

            var target = new PipeStream();
            target.WriteByte(0x0a);
            target.WriteByte(0x0d);
            target.WriteByte(0x09);

            var readBuffer = new byte[2];
            var bytesRead = target.Read(readBuffer, 0, readBuffer.Length);
            Assert.AreEqual(2, bytesRead);
            Assert.AreEqual(0x0a, readBuffer[0]);
            Assert.AreEqual(0x0d, readBuffer[1]);

            var writeToStreamThread = new Thread(
                () =>
                    {
                        Thread.Sleep(sleepTime);
                        var writeBuffer = new byte[] {0x05, 0x03};
                        target.Write(writeBuffer, 0, writeBuffer.Length);
                    });
            writeToStreamThread.Start();

            readBuffer = new byte[2];
            bytesRead = target.Read(readBuffer, 0, readBuffer.Length);
            Assert.AreEqual(2, bytesRead);
            Assert.AreEqual(0x09, readBuffer[0]);
            Assert.AreEqual(0x05, readBuffer[1]);
        }
Exemple #3
0
 public void LengthTest()
 {
     PipeStream target = new PipeStream(); // TODO: Initialize to an appropriate value
     long actual;
     actual = target.Length;
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
        /// <summary>
        /// Downloads the specified file from the remote host to local file.
        /// </summary>
        /// <param name="filename">Remote host file name.</param>
        /// <param name="fileInfo">Local file information.</param>
        /// <exception cref="ArgumentNullException"><paramref name="fileInfo"/> or <paramref name="filename"/> is null.</exception>
        public void Download(string filename, FileInfo fileInfo)
        {
            if (fileInfo == null)
                throw new ArgumentNullException("fileInfo");

            if (filename == null)
                throw new ArgumentNullException("filename"); //  TODO:   Should add IsNullOrWhitespace for this filename parameter?

            //  UNDONE:   EnsureConnection?

            using (var input = new PipeStream())
            using (var channel = this.Session.CreateChannel<ChannelSession>())
            {
                channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e)
                {
                    input.Write(e.Data, 0, e.Data.Length);
                    input.Flush();
                };

                channel.Open();

                //  Send channel command request
                channel.SendExecRequest(string.Format("scp -qpf \"{0}\"", filename));
                this.SendConfirmation(channel); //  Send reply

                this.InternalDownload(channel, input, fileInfo);

                channel.Close();
            }
        }
        /// <summary>
        /// Uploads the specified directory to the remote host.
        /// </summary>
        /// <param name="directoryInfo">The directory info.</param>
        /// <param name="path">The path.</param>
        /// <exception cref="ArgumentNullException">fileSystemInfo</exception>
        /// <exception cref="ArgumentException"><paramref name="path"/> is null or empty.</exception>
        public void Upload(DirectoryInfo directoryInfo, string path)
        {
            if (directoryInfo == null)
                throw new ArgumentNullException("directoryInfo");
            if (string.IsNullOrEmpty(path))
                throw new ArgumentException("path");

            using (var input = new PipeStream())
            using (var channel = Session.CreateChannelSession())
            {
                channel.DataReceived += delegate(object sender, ChannelDataEventArgs e)
                {
                    input.Write(e.Data, 0, e.Data.Length);
                    input.Flush();
                };

                channel.Open();

                //  Send channel command request
                channel.SendExecRequest(string.Format("scp -rt \"{0}\"", path));
                CheckReturnCode(input);

                InternalSetTimestamp(channel, input, directoryInfo.LastWriteTimeUtc, directoryInfo.LastAccessTimeUtc);
                SendData(channel, string.Format("D0755 0 {0}\n", Path.GetFileName(path)));
                CheckReturnCode(input);

                InternalUpload(channel, input, directoryInfo);

                SendData(channel, "E\n");
                CheckReturnCode(input);

                channel.Close();
            }
        }
        public void Init()
        {
            _pipeStream = new PipeStream {MaxBufferLength = 3};

            Action writeAction = () =>
                {
                    _pipeStream.WriteByte(10);
                    _pipeStream.WriteByte(13);
                    _pipeStream.WriteByte(25);

                    // attempting to write more bytes than the max. buffer length should block
                    // until bytes are read or the stream is closed
                    try
                    {
                        _pipeStream.WriteByte(35);
                    }
                    catch (Exception ex)
                    {
                        _writeException = ex;
                        throw;
                    }
                };
            _asyncWriteResult = writeAction.BeginInvoke(null, null);
            // ensure we've started writing
            _asyncWriteResult.AsyncWaitHandle.WaitOne(50);

            Act();
        }
Exemple #7
0
        /// <summary>
        /// Downloads the specified directory from the remote host to local directory.
        /// </summary>
        /// <param name="directoryName">Remote host directory name.</param>
        /// <param name="directoryInfo">Local directory information.</param>
        /// <exception cref="ArgumentNullException"><paramref name="directoryInfo"/> or <paramref name="directoryName"/> is null.</exception>
        public void Download(string directoryName, DirectoryInfo directoryInfo)
        {
            if (directoryInfo == null)
                throw new ArgumentNullException("directoryInfo");

            if (string.IsNullOrEmpty(directoryName))
                throw new ArgumentException("directoryName");

            using (var input = new PipeStream())
            using (var channel = this.Session.CreateChannel<ChannelSession>())
            {
                channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e)
                {
                    input.Write(e.Data, 0, e.Data.Length);
                    input.Flush();
                };

                channel.Open();

                //  Send channel command request
                channel.SendExecRequest(string.Format("scp -prf \"{0}\"", directoryName));
                this.SendConfirmation(channel); //  Send reply

                this.InternalDownload(channel, input, directoryInfo);

                channel.Close();
            }
        }
Exemple #8
0
        /// <summary>
        /// Uploads the specified file to the remote host.
        /// </summary>
        /// <param name="fileInfo">The file system info.</param>
        /// <param name="path">The path.</param>
        /// <exception cref="ArgumentNullException"><paramref name="fileInfo" /> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="path"/> is null or empty.</exception>
        public void Upload(FileInfo fileInfo, string path)
        {
            if (fileInfo == null)
                throw new ArgumentNullException("fileInfo");
            if (string.IsNullOrEmpty(path))
                throw new ArgumentException("path");

            using (var input = new PipeStream())
            using (var channel = this.Session.CreateClientChannel<ChannelSession>())
            {
                channel.DataReceived += delegate(object sender, ChannelDataEventArgs e)
                {
                    input.Write(e.Data, 0, e.Data.Length);
                    input.Flush();
                };

                channel.Open();

                //  Send channel command request
                channel.SendExecRequest(string.Format("scp -t \"{0}\"", path));
                this.CheckReturnCode(input);

                this.InternalUpload(channel, input, fileInfo, fileInfo.Name);

                channel.Close();
            }
        }
Exemple #9
0
 public void BlockLastReadBufferTest()
 {
     PipeStream target = new PipeStream(); // TODO: Initialize to an appropriate value
     bool expected = false; // TODO: Initialize to an appropriate value
     bool actual;
     target.BlockLastReadBuffer = expected;
     actual = target.BlockLastReadBuffer;
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Exemple #10
0
        public void Test_PipeStream_Write_Read_Byte()
        {
            var testBuffer = new byte[1024];
            new Random().NextBytes(testBuffer);

            using (var stream = new PipeStream())
            {
                stream.Write(testBuffer, 0, testBuffer.Length);
                Assert.AreEqual(stream.Length, testBuffer.Length);
                stream.ReadByte();
                Assert.AreEqual(stream.Length, testBuffer.Length - 1);
                stream.ReadByte();
                Assert.AreEqual(stream.Length, testBuffer.Length - 2);
            }
        }
        public void Init()
        {
            _pipeStream = new PipeStream();
            _pipeStream.WriteByte(10);
            _pipeStream.WriteByte(13);

            _bytesRead = 0;
            _readBuffer = new byte[4];

            Action readAction = () => _bytesRead = _pipeStream.Read(_readBuffer, 0, _readBuffer.Length);
            _asyncReadResult = readAction.BeginInvoke(null, null);
            _asyncReadResult.AsyncWaitHandle.WaitOne(50);

            Act();
        }
        public void Init()
        {
            _pipeStream = new PipeStream();

            _pipeStream.WriteByte(10);
            _pipeStream.WriteByte(13);
            _pipeStream.WriteByte(25);

            _bytesRead = 123;

            Action readAction = () => _bytesRead = _pipeStream.Read(new byte[4], 0, 4);
            _asyncReadResult = readAction.BeginInvoke(null, null);
            // ensure we've started reading
            _asyncReadResult.AsyncWaitHandle.WaitOne(50);

            Act();
        }
Exemple #13
0
        public void Test_PipeStream_Write_Read_Buffer()
        {
            var testBuffer = new byte[1024];
            new Random().NextBytes(testBuffer);

            var outputBuffer = new byte[1024];

            using (var stream = new PipeStream())
            {
                stream.Write(testBuffer, 0, testBuffer.Length);

                Assert.AreEqual(stream.Length, testBuffer.Length);

                stream.Read(outputBuffer, 0, outputBuffer.Length);

                Assert.AreEqual(stream.Length, 0);

                Assert.IsTrue(testBuffer.IsEqualTo(outputBuffer));
            }
        }
        /// <summary>
        /// Downloads the specified directory from the remote host to local directory.
        /// </summary>
        /// <param name="directoryName">Remote host directory name.</param>
        /// <param name="directoryInfo">Local directory information.</param>
        public void Download(string directoryName, DirectoryInfo directoryInfo)
        {
            using (var input = new PipeStream())
            using (var channel = this.Session.CreateChannel<ChannelSession>())
            {
                channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e)
                {
                    input.Write(e.Data, 0, e.Data.Length);
                    input.Flush();
                };

                channel.Open();

                //  Send channel command request
                channel.SendExecRequest(string.Format("scp -qprf {0}", directoryName));
                this.SendConfirmation(channel); //  Send reply

                this.InternalDownload(channel, input, directoryInfo);

                channel.Close();
            }
        }
        /// <summary>
        /// Uploads the specified file to the remote host.
        /// </summary>
        /// <param name="fileInfo">Local file to upload.</param>
        /// <param name="filename">Remote host file name.</param>
        public void Upload(FileInfo fileInfo, string filename)
        {
            using (var input = new PipeStream())
            using (var channel = this.Session.CreateChannel<ChannelSession>())
            {
                channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e)
                {
                    input.Write(e.Data, 0, e.Data.Length);
                    input.Flush();
                };

                channel.Open();

                //  Send channel command request
                channel.SendExecRequest(string.Format("scp -qt {0}", filename));
                this.CheckReturnCode(input);

                this.InternalUpload(channel, input, fileInfo, filename);

                channel.Close();
            }
        }
Exemple #16
0
        public void Position_GetterAlwaysReturnsZero()
        {
            var target = new PipeStream();

            Assert.AreEqual(0, target.Position);
            target.WriteByte(0x0a);
            Assert.AreEqual(0, target.Position);
            target.ReadByte();
            Assert.AreEqual(0, target.Position);
        }
Exemple #17
0
        /// <summary>
        /// Uploads the specified stream to the remote host.
        /// </summary>
        /// <param name="source">Stream to upload.</param>
        /// <param name="filename">Remote host file name.</param>
        public void Upload(Stream source, string path)
        {
            using (var input = new PipeStream())
            using (var channel = this.Session.CreateChannel<ChannelSession>())
            {
                channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e)
                {
                    input.Write(e.Data, 0, e.Data.Length);
                    input.Flush();
                };

                channel.Open();

                var pathParts = path.Split('\\', '/');

                //  Send channel command request
                channel.SendExecRequest(string.Format("scp -rt \"{0}\"", pathParts[0]));
                this.CheckReturnCode(input);

                //  Prepare directory structure
                for (int i = 0; i < pathParts.Length - 1; i++)
                {
                    this.InternalSetTimestamp(channel, input, DateTime.UtcNow, DateTime.UtcNow);
                    this.SendData(channel, string.Format("D0755 0 {0}\n", pathParts[i]));
                    this.CheckReturnCode(input);
                }

                this.InternalUpload(channel, input, source, pathParts.Last());

                //  Finish directory structure
                for (int i = 0; i < pathParts.Length - 1; i++)
                {
                    this.SendData(channel, "E\n");
                    this.CheckReturnCode(input);
                }

                channel.Close();
            }
        }
Exemple #18
0
        /// <summary>
        /// Downloads the specified file from the remote host to the stream.
        /// </summary>
        /// <param name="filename">Remote host file name.</param>
        /// <param name="destination">The stream where to download remote file.</param>
        /// <exception cref="ArgumentException"><paramref name="filename"/> is null or contains whitespace characters.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="destination"/> is null.</exception>
        /// <remarks>Method calls made by this method to <paramref name="destination"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>
        public void Download(string filename, Stream destination)
        {
            if (filename.IsNullOrWhiteSpace())
                throw new ArgumentException("filename");

            if (destination == null)
                throw new ArgumentNullException("destination");

            using (var input = new PipeStream())
            using (var channel = this.Session.CreateChannel<ChannelSession>())
            {
                channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e)
                {
                    input.Write(e.Data, 0, e.Data.Length);
                    input.Flush();
                };

                channel.Open();

                //  Send channel command request
                channel.SendExecRequest(string.Format("scp -f \"{0}\"", filename));
                this.SendConfirmation(channel); //  Send reply

                var message = ReadString(input);
                var match = _fileInfoRe.Match(message);

                if (match.Success)
                {
                    //  Read file
                    this.SendConfirmation(channel); //  Send reply

                    var mode = match.Result("${mode}");
                    var length = long.Parse(match.Result("${length}"));
                    var fileName = match.Result("${filename}");

                    this.InternalDownload(channel, input, destination, fileName, length);
                }
                else
                {
                    this.SendConfirmation(channel, 1, string.Format("\"{0}\" is not valid protocol message.", message));
                }

                channel.Close();
            }
        }
Exemple #19
0
        public void Position_SetterAlwaysThrowsNotSupportedException()
        {
            var target = new PipeStream();

            try
            {
                target.Position = 0;
                Assert.Fail();
            }
            catch (NotSupportedException)
            {
            }
        }
Exemple #20
0
 public void ReadTest()
 {
     PipeStream target = new PipeStream(); // TODO: Initialize to an appropriate value
     byte[] buffer = null; // TODO: Initialize to an appropriate value
     int offset = 0; // TODO: Initialize to an appropriate value
     int count = 0; // TODO: Initialize to an appropriate value
     int expected = 0; // TODO: Initialize to an appropriate value
     int actual;
     actual = target.Read(buffer, offset, count);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Exemple #21
0
        /// <summary>
        /// Uploads the specified file or directory to the remote host.
        /// </summary>
        /// <param name="fileInfo">Local file to upload.</param>
        /// <param name="filename">Remote host file name.</param>
        /// <exception cref="ArgumentNullException"><paramref name="fileInfo"/> or <paramref name="filename"/> is null.</exception>
        public void Upload(FileSystemInfo fileSystemInfo, string path)
        {
            if (fileSystemInfo == null)
                throw new ArgumentNullException("fileSystemInfo");

            if (string.IsNullOrEmpty(path))
                throw new ArgumentException("path");

            using (var input = new PipeStream())
            using (var channel = this.Session.CreateChannel<ChannelSession>())
            {
                channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e)
                {
                    input.Write(e.Data, 0, e.Data.Length);
                    input.Flush();
                };

                channel.Open();

                var pathParts = path.Split('\\', '/');

                //  Send channel command request
                channel.SendExecRequest(string.Format("scp -rt \"{0}\"", pathParts[0]));
                this.CheckReturnCode(input);

                //  Prepare directory structure
                for (int i = 0; i < pathParts.Length - 1; i++)
                {
                    this.InternalSetTimestamp(channel, input, fileSystemInfo.LastWriteTimeUtc, fileSystemInfo.LastAccessTimeUtc);
                    this.SendData(channel, string.Format("D0755 0 {0}\n", pathParts[i]));
                    this.CheckReturnCode(input);
                }

                if (fileSystemInfo is FileInfo)
                {
                    this.InternalUpload(channel, input, fileSystemInfo as FileInfo, pathParts.Last());
                }
                else if (fileSystemInfo is DirectoryInfo)
                {
                    this.InternalUpload(channel, input, fileSystemInfo as DirectoryInfo, pathParts.Last());
                }
                else
                {
                    throw new NotSupportedException(string.Format("Type '{0}' is not supported.", fileSystemInfo.GetType().FullName));
                }

                //  Finish directory structure
                for (int i = 0; i < pathParts.Length - 1; i++)
                {
                    this.SendData(channel, "E\n");
                    this.CheckReturnCode(input);
                }

                channel.Close();
            }
        }
Exemple #22
0
        public void SeekShouldThrowNotSupportedException()
        {
            const long offset = 0;
            const SeekOrigin origin = new SeekOrigin();
            var target = new PipeStream();

            try
            {
                target.Seek(offset, origin);
                Assert.Fail();
            }
            catch (NotSupportedException)
            {
            }

        }
Exemple #23
0
 public void FlushTest()
 {
     PipeStream target = new PipeStream(); // TODO: Initialize to an appropriate value
     target.Flush();
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
Exemple #24
0
        /// <summary>
        /// Uploads the specified stream to the remote host.
        /// </summary>
        /// <param name="source">Stream to upload.</param>
        /// <param name="path">Remote host file name.</param>
        public void Upload(Stream source, string path)
        {
            using (var input = new PipeStream())
            using (var channel = this.Session.CreateClientChannel<ChannelSession>())
            {
                channel.DataReceived += delegate(object sender, ChannelDataEventArgs e)
                {
                    input.Write(e.Data, 0, e.Data.Length);
                    input.Flush();
                };

                channel.Open();

                int pathEnd = path.LastIndexOfAny(new[] { '\\', '/' });
                if (pathEnd != -1)
                {
                    // split the path from the file
                    string pathOnly = path.Substring(0, pathEnd);
                    string fileOnly = path.Substring(pathEnd + 1);
                    //  Send channel command request
                    channel.SendExecRequest(string.Format("scp -t \"{0}\"", pathOnly));
                    this.CheckReturnCode(input);

                    path = fileOnly;
                }

                this.InternalUpload(channel, input, source, path);

                channel.Close();
            }
        }
Exemple #25
0
 public void SeekTest()
 {
     PipeStream target = new PipeStream(); // TODO: Initialize to an appropriate value
     long offset = 0; // TODO: Initialize to an appropriate value
     SeekOrigin origin = new SeekOrigin(); // TODO: Initialize to an appropriate value
     long expected = 0; // TODO: Initialize to an appropriate value
     long actual;
     actual = target.Seek(offset, origin);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Exemple #26
0
        private void InternalUpload(ChannelSession channel, PipeStream input, DirectoryInfo directoryInfo, string directoryName)
        {
            this.InternalSetTimestamp(channel, input, directoryInfo.LastWriteTimeUtc, directoryInfo.LastAccessTimeUtc);
            this.SendData(channel, string.Format("D0755 0 {0}\n", directoryName));
            this.CheckReturnCode(input);

            //  Upload files
            var files = directoryInfo.GetFiles();
            foreach (var file in files)
            {
                this.InternalUpload(channel, input, file, file.Name);
            }

            //  Upload directories
            var directories = directoryInfo.GetDirectories();
            foreach (var directory in directories)
            {
                this.InternalUpload(channel, input, directory, directory.Name);
            }

            this.SendData(channel, "E\n");
            this.CheckReturnCode(input);
        }
Exemple #27
0
 public void MaxBufferLengthTest()
 {
     PipeStream target = new PipeStream(); // TODO: Initialize to an appropriate value
     long expected = 0; // TODO: Initialize to an appropriate value
     long actual;
     target.MaxBufferLength = expected;
     actual = target.MaxBufferLength;
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
 private void Arrange()
 {
     _pipeStream = new PipeStream();
 }
Exemple #29
0
 public void WriteTest()
 {
     PipeStream target = new PipeStream(); // TODO: Initialize to an appropriate value
     byte[] buffer = null; // TODO: Initialize to an appropriate value
     int offset = 0; // TODO: Initialize to an appropriate value
     int count = 0; // TODO: Initialize to an appropriate value
     target.Write(buffer, offset, count);
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
Exemple #30
0
 public void PipeStreamConstructorTest()
 {
     PipeStream target = new PipeStream();
     Assert.Inconclusive("TODO: Implement code to verify target");
 }