Beispiel #1
0
    public static void WriteOutput(object data, Stream output, bool closeStreams )
    {
        if (data == output) return;

        XmlDocument xml = data as XmlDocument;
        if (xml != null)
        {
            XmlTextWriter xmlWriter = new XmlTextWriter(output, System.Text.Encoding.UTF8);
            xml.WriteTo(xmlWriter);
            xmlWriter.Flush();
        }

        Stream stream = data as Stream;
        if (stream != null)
        {
            stream.Seek(0, SeekOrigin.Begin);
            byte[] buffer = new byte[0x5000];
            int read;
            while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                output.Write(buffer, 0, read);

            if ( closeStreams ) stream.Close();
        }

        byte[] block = data as byte[];
        if ( block != null && block.Length > 0 )
            output.Write( block, 0, block.Length );
    }
Beispiel #2
0
        /// <summary>
        /// Returns the CRC32 for the specified stream, and writes the input into the
        /// output stream.
        /// </summary>
        /// <param name="input">The stream over which to calculate the CRC32</param>
        /// <param name="output">The stream into which to deflate the input</param>
        /// <returns>the CRC32 calculation</returns>
        public int GetCrc32AndCopy(Stream input, Stream?output)
        {
            if (input == null)
            {
                throw new Exception("The input stream must not be null.");
            }

            unchecked
            {
                TotalBytesRead = 0;
                Span <byte> buffer = stackalloc byte[4096];
                int         count  = input.Read(buffer);
                output?.Write(buffer.Slice(0, count));
                TotalBytesRead += count;
                while (count > 0)
                {
                    var slice = buffer.Slice(0, count);
                    SlurpBlock(slice);
                    count = input.Read(buffer);
                    output?.Write(slice);
                    TotalBytesRead += count;
                }
                return((int)~_register);
            }
        }
        public static void Write(Stream stream, byte type, Stream exportStream)
        {
            stream.WriteByte(type);
            stream.Write(NetworkConverter.GetBytes((int)exportStream.Length), 0, 4);

            byte[] buffer = null;

            try
            {

                buffer = _bufferManager.TakeBuffer(1024 * 4);
                int length = 0;

                while ((length = exportStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    stream.Write(buffer, 0, length);
                }
            }
            finally
            {
                if (buffer != null)
                {
                    _bufferManager.ReturnBuffer(buffer);
                }
            }
        }
Beispiel #4
0
        /// <summary>Returns the CRC32 for the specified stream, and writes the input into the output stream.</summary>
        /// <param name="input">The stream over which to calculate the CRC32</param>
        /// <param name="output">The stream into which to deflate the input</param>
        /// <returns>the CRC32 calculation</returns>
        public int GetCrc32AndCopy(Stream input, Stream output)
        {
            if (input == null)
            {
                throw new Exception("The input stream must not be null.");
            }

            unchecked
            {
                var buffer   = new byte[BufferSize];
                var readSize = BufferSize;

                TotalBytesRead = 0;
                var count = input.Read(buffer, 0, readSize);
                output?.Write(buffer, 0, count);
                TotalBytesRead += count;
                while (count > 0)
                {
                    SlurpBlock(buffer, 0, count);
                    count = input.Read(buffer, 0, readSize);
                    output?.Write(buffer, 0, count);
                    TotalBytesRead += count;
                }

                return((int)~_register);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Returns the CRC32 for the specified stream, and writes the input into the
        /// output stream.
        /// </summary>
        /// <param name="input">The stream over which to calculate the CRC32</param>
        /// <param name="output">The stream into which to deflate the input</param>
        /// <returns>the CRC32 calculation</returns>
        public int GetCrc32AndCopy(Stream input, Stream?output)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input), "The input stream must not be null.");
            }

            unchecked
            {
                Span <byte> buffer = stackalloc byte[BUFFER_SIZE];
                //const int readSize = BUFFER_SIZE;

                _TotalBytesRead = 0;
                int count = input.Read(buffer);
                output?.Write(buffer.Slice(0, count));

                _TotalBytesRead += count;
                while (count > 0)
                {
                    SlurpBlock(buffer, 0, count);
                    count = input.Read(buffer);
                    output?.Write(buffer.Slice(0, count));

                    _TotalBytesRead += count;
                }

                return((int)~_register);
            }
        }
Beispiel #6
0
 public static void CopyStream(Stream input, Stream output)
 {
     var buffer = new byte[1024];
     int bytes;
     while ((bytes = input.Read(buffer, 0, 1024)) > 0)
         output.Write(buffer, 0, bytes);
 }
    static void CompressStream(Stream from, Stream to)
    {
        byte[] src = new byte[from.Length];

        // read file
        if (from.Read(src, 0, src.Length) == src.Length)
        {
            int dstSize = DllInterface.aP_max_packed_size(src.Length);
            int wrkSize = DllInterface.aP_workmem_size(src.Length);

            // allocate mem
            byte[] dst = new byte[dstSize];
            byte[] wrk = new byte[wrkSize];

            // compress data
            int packedSize = DllInterface.aPsafe_pack(
                src,
                dst,
                src.Length,
                wrk,
                new DllInterface.CompressionCallback(ShowProgress),
                0
            );

            // write compressed data
            to.Write(dst, 0, packedSize);

            Console.WriteLine("compressed to {0} bytes", packedSize);
        }
    }
Beispiel #8
0
 private void DeliverSample(ComObject requestToken, IRtspSample packet)
 {
     using (var sample = MediaFactory.CreateSample()) {
         using (var buffer = MediaFactory.CreateMemoryBuffer(packet.Buffer.Length)) {
             int max, cur;
             var ptr = buffer.Lock(out max, out cur);
             Marshal.Copy(packet.Buffer, 0, ptr, packet.Buffer.Length);
             buffer.CurrentLength = packet.Buffer.Length;
             buffer.Unlock();
             sample.AddBuffer(buffer);
         }
         sample.SampleTime = packet.SampleTime;
         if (requestToken.NativePointer != IntPtr.Zero)
         {
             sample.Set(SampleAttributeKeys.Token, requestToken);
         }
         if (packet.IsKeyFrame)
         {
             sample.Set(SampleAttributeKeys.CleanPoint, true);
         }
         if (packet.Discontinuity)
         {
             sample.Set(SampleAttributeKeys.Discontinuity, true);
         }
         if (Type == StreamType.Video)
         {
             sample.Set(NaluAttributeKeys.LengthInformation, packet.LengthInfo.Select(BitConverter.GetBytes).SelectMany(b => b).ToArray());
         }
         //Trace.WriteLine($"RtspMediaStream<{Type}>::DeliverSample() SampleTime={packet.SampleTime / 10000}(ms) Length={packet.Buffer.Length}");
         _eventGenerator.QueueEventParamUnk(MediaEventTypes.MediaSample, Guid.Empty, Result.Ok, sample);
     }
     requestToken.Dispose();
     _debugSaveStream?.Write(packet.Buffer, 0, packet.Buffer.Length);
 }
Beispiel #9
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     lock (this) {
         BaseStream?.Write(buffer, offset, count);
         Buffer.Write(buffer, offset, count);
     }
 }
        private static void ReadResponseAsByte(WebResponse resp, CancellationToken token, Stream outputStream = null)
        {
            int bufSizeChunk = 30000;
            int totalBufSize = bufSizeChunk;

            byte[] fileBytes = new byte[totalBufSize];

            int totalBytesRead = 0;

            var responseStream = resp.GetResponseStream();

            if (responseStream != null)
            {
                using (var reader = new BinaryReader(responseStream))
                {
                    int bytesRead;
                    while ((bytesRead = reader.Read(fileBytes, totalBytesRead, totalBufSize - totalBytesRead)) > 0)
                    {
                        token.ThrowIfCancellationRequested();

                        outputStream?.Write(fileBytes, totalBytesRead, bytesRead);

                        totalBytesRead += bytesRead;

                        if (totalBufSize - totalBytesRead == 0)
                        {
                            totalBufSize += bufSizeChunk;
                            Array.Resize(ref fileBytes, totalBufSize);
                        }
                    }
                }
            }
        }
	/// <summary>
	/// Reads all the bytes from the current stream and writes them to the destination stream.
	/// </summary>
	/// <param name="original">The current stream.</param>
	/// <param name="destination">The stream that will contain the contents of the current stream.</param>
	/// <exception cref="System.ArgumentNullException">Destination is null.</exception>
	/// <exception cref="System.NotSupportedException">The current stream does not support reading.-or-destination does not support Writing.</exception>
	/// <exception cref="System.ObjectDisposedException">Either the current stream or destination were closed before the System.IO.Stream.CopyTo(System.IO.Stream) method was called.</exception>
	/// <exception cref="System.IO.IOException">An I/O error occurred.</exception>
	public static void CopyTo(this Stream original, Stream destination)
	{
		if (destination == null)
		{
			throw new ArgumentNullException("destination");
		}
		if (!original.CanRead && !original.CanWrite)
		{
			throw new ObjectDisposedException("ObjectDisposedException");
		}
		if (!destination.CanRead && !destination.CanWrite)
		{
			throw new ObjectDisposedException("ObjectDisposedException");
		}
		if (!original.CanRead)
		{
			throw new NotSupportedException("NotSupportedException source");
		}
		if (!destination.CanWrite)
		{
			throw new NotSupportedException("NotSupportedException destination");
		}
		
		byte[] array = new byte[4096];
		int count;
		while ((count = original.Read(array, 0, array.Length)) != 0)
		{
			destination.Write(array, 0, count);
		}
	}
Beispiel #12
0
        private void WriteLogLine(string text, Stream logStream, StringBuilder inMemoryLog)
        {
            var line = MakeLogLine(text);
            var buf  = Encoding.UTF8.GetBytes(line);

            logStream?.Write(buf, 0, buf.Length);
            inMemoryLog.Append(line);
        }
Beispiel #13
0
        internal void Write(byte[] data)
        {
            Stream?.Write(data, 0, data.Length);

            Data?.AddRange(data);

            DataWritten += data.Length;
        }
Beispiel #14
0
        /// <inheritdoc />
        public override void Write(byte[] buffer, int offset, int count)
        {
            if (_cutoff <= 0)
            {
                return;               // tripped already
            }
            if (_cutoff <= count)
            {
                // write less than the whole block
                _streamToWrap?.Write(buffer, offset, _cutoff);
                _cutoff = 0;
                return;
            }

            _streamToWrap?.Write(buffer, offset, count);
            _cutoff -= count;
        }
Beispiel #15
0
 private static void CopyStream(Stream source, Stream target)
 {
     const int bufSize = 0x1000;
     byte[] buf = new byte[bufSize];
     int bytesRead = 0;
     while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
         target.Write(buf, 0, bytesRead);
 }
	/// <summary>
	/// Writes the input stream to the target stream.
	/// </summary>
	/// <param name="source" this="true">The source stream to write to the target stream.</param>
	/// <param name="target">The target stream to write to.</param>
	/// <returns>The written <paramref name="target"/> stream.</returns>
	public static void WriteTo(this Stream source, Stream target)
	{
		var buffer = new byte[BufferSize];
		var read = 0;
		while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
		{
			target.Write(buffer, 0, read);
		}
	}
        // Summary:
        //     Reads all the bytes from the current stream and writes them to the destination
        //     stream.
        //
        // Parameters:
        //   destination:
        //     The stream that will contain the contents of the current stream.
        //
		// NOTE:
		//	This is a Stream member method in .NET 4
        public static void CopyTo(this Stream source, Stream destination)
		{
	       byte[] buffer = new byte[4096];
	       int n;
	       while ((n = source.Read(buffer, 0, buffer.Length)) != 0)
			{
	           destination.Write(buffer, 0, n);			
			}
		}
 static void CopyTo(Stream source, Stream destination)
 {
     var array = new byte[81920];
     int count;
     while ((count = source.Read(array, 0, array.Length)) != 0)
     {
         destination.Write(array, 0, count);
     }
 }
Beispiel #19
0
 /// <summary>
 /// Writes the given bytes into the inner (decorated) stream and handles them to update the SHA1
 /// computation state.
 /// This can be called only if this stream is a decorator initialized in write mode.
 /// </summary>
 /// <param name="buffer">
 /// An array of bytes.This method copies count bytes from buffer to the current
 /// stream.
 /// </param>
 /// <param name="offset">
 /// The zero-based byte offset in buffer at which to begin copying bytes to the current
 /// stream.
 /// </param>
 /// <param name="count">
 /// The number of bytes to be written to the current stream.
 /// </param>
 public override void Write(byte[] buffer, int offset, int count)
 {
     if (_reader != null)
     {
         throw new InvalidOperationException();
     }
     _sha1.TransformBlock(buffer, offset, count, null, 0);
     _writer?.Write(buffer, offset, count);
 }
Beispiel #20
0
        public void WriteToStream(Stream saveStream)
        {
            if (this.Deleted)
            {
                return;
            }

            saveStream?.Write(this.Data, 0, this.Data.Length);
        }
Beispiel #21
0
        public static void WriteLong(long value, Stream stream, bool isLittleEndian)
        {
            byte[] buffer = BitConverter.GetBytes(value);
            if (BitConverter.IsLittleEndian && !isLittleEndian)
            {
                Array.Reverse(buffer);
            }

            stream.Write(buffer, 0, buffer.Length);
        }
Beispiel #22
0
 public static void CopyToStream(Stream src, Stream dst, byte[] buffer, int numBytes)
 {
     while (numBytes > 0)
     {
         int req = Math.Min(buffer.Length, numBytes);
         int read = src.Read(buffer, 0, req);
         dst.Write(buffer, 0, read);
         numBytes -= read;
     }
 }
        public static void CopyTo(this Stream from, Stream dest, byte[] buffer = null)
        {
            buffer = buffer ?? new byte[DefaultCopyBufferSize];
            var bufferSize = buffer.Length;

            int read;
            while ((read = from.Read(buffer, 0, bufferSize)) > 0) {
                dest.Write(buffer, 0, read);
            }
        }
Beispiel #24
0
        public void WriteZString([NotNull] string str, bool withLength, StringEncoderMode mode = StringEncoderMode.Normal)
        {
            MaybeProcessEscapeChars(ref str);

            var zstr = StringEncoder.Encode(str, mode);

            if (FinalPass && AbbreviateMode)
            {
                AbbrevFinder.AddText(str);
            }

            if (withLength)
            {
                WriteByte((byte)(zstr.Length / 2));
            }

            position += zstr.Length;
            stream?.Write(zstr, 0, zstr.Length);
        }
Beispiel #25
0
    public static void writedouble(Stream output, double val)
    {
        byte[] bytes = System.BitConverter.GetBytes(val);
#if StandAlone
#else
		if (System.BitConverter.IsLittleEndian)
			System.Array.Reverse(bytes);
#endif
        output.Write(bytes, 0, DOUBLE_LEN);
    }
Beispiel #26
0
        public int GetCrc32AndCopy(Stream input, Stream output)
        {
            byte[] array = new byte[8192];
            int    count = 8192;

            _TotalBytesRead = 0L;
            int num = input.Read(array, 0, count);

            output?.Write(array, 0, num);
            _TotalBytesRead += num;
            while (num > 0)
            {
                SlurpBlock(array, 0, num);
                num = input.Read(array, 0, count);
                output?.Write(array, 0, num);
                _TotalBytesRead += num;
            }
            return((int)(~_RunningCrc32Result));
        }
	public void connect() {
		try {
			if (connected) {
				throw new SocketIoClientException("already connected");
			}
			
			socket = createSocket();
			stream = socket.GetStream();
			
			input = new StreamReader(stream);
			byte[] bytes = handshake.getHandshake();
			stream.Write(bytes, 0, bytes.Length);
			stream.Flush();
			
			bool handshakeComplete = false;
			List<string> handshakeLines = new List<string>();
			string line;
			
			while(!handshakeComplete) {
				line = input.ReadLine().Trim();
				if (line.Length>0) {
					handshakeLines.Add(line);
				} else {
					handshakeComplete = true;
				}
			}
			
			char[] response = new char[16];
			input.ReadBlock(response, 0, response.Length);
			
			handshake.verifyServerStatusLine(handshakeLines[0]);
			
			/* Verifying handshake fails... */
			//handshake.verifyServerResponse(response);
			
			handshakeLines.RemoveAt(0);
			
			Dictionary<string, string> headers = new Dictionary<string, string>();
			foreach (string l in handshakeLines) {
				string[] keyValue = l.Split(new char[] {':'},2);
				headers.Add(keyValue[0].Trim(), keyValue[1].Trim());
			}

			handshake.verifyServerHandshakeHeaders(headers);
			receiver = new SocketIoClientReceiver(this);
			connected = true;
			eventHandler.OnOpen();
			(new Thread(receiver.run)).Start();
		} catch (SocketIoClientException wse) {
			throw wse;
		} catch (IOException ioe) {
			throw new SocketIoClientException("error while connecting: " + ioe.StackTrace, ioe);
		}
	}
 public static bool WriteBeyondEndTest(Stream s)
 {
     Console.WriteLine("Write Beyond End test on "+s.GetType().Name);
     FileStream fs = s as FileStream;
     if (fs != null)
         Console.WriteLine("FileStream type is: "+(fs.IsAsync ? "asynchronous" : "synchronous"));
     long origLength = s.Length;        
     byte[] bytes = new byte[10];
     for(int i=0; i<bytes.Length; i++)
         bytes[i] = (byte) i;
     int spanPastEnd = 5;
     s.Seek(spanPastEnd, SeekOrigin.End);
     if (s.Position != s.Length + spanPastEnd)
         throw new Exception("Position is incorrect!  Seek(5, SeekOrigin.End) should leave us at s.Length + spanPastEnd ("+(s.Length + spanPastEnd)+"), but got: "+s.Position);
     Console.WriteLine("Original Length: "+origLength);
     s.Write(bytes, 0, bytes.Length);
     long pos = s.Position;
     if (pos != origLength + spanPastEnd + bytes.Length)
         throw new Exception(String.Format("After asynchronously writing beyond end of the stream, position is now incorrect!  origLength: {0}  pos: {1}", origLength, pos));
     if (s.Length != origLength + spanPastEnd + bytes.Length)
         throw new Exception(String.Format("After asynchronously writing beyond end of the stream, Length is now incorrect!  origLength: {0}  pos: {1}", origLength, pos));
     WritePastEndHelper(s, bytes, origLength, spanPastEnd, false);
     origLength = s.Length;
     s.Position = s.Length + spanPastEnd;
     s.WriteByte(0x42);
     long expected = origLength + spanPastEnd + 1;
     if (s.Position != expected)
     {
         iCountErrors++ ;
         throw new Exception("After WriteByte, Position was wrong!  got: "+s.Position+"  expected: "+expected);
     }
     if (s.Length != expected)
     {
         iCountErrors++ ;
         throw new Exception("After WriteByte, Length was wrong!  got: "+s.Length+"  expected: "+expected);
     }
     origLength = s.Length;
     s.Position = s.Length + spanPastEnd;
     IAsyncResult ar = s.BeginWrite(bytes, 0, bytes.Length, null, null);
     s.EndWrite(ar);
     pos = s.Position;
     if (pos != origLength + spanPastEnd + bytes.Length) 
     {
         iCountErrors++ ;
         throw new Exception(String.Format("After writing beyond end of the stream, position is now incorrect!  origLength: {0}  pos: {1}", origLength, pos));
     }
     if (s.Length != origLength + spanPastEnd + bytes.Length) 
     {
         iCountErrors++;
         throw new Exception(String.Format("After writing beyond end of the stream, Length is now incorrect!  origLength: {0}  pos: {1}", origLength, pos));
     }
     WritePastEndHelper(s, bytes, origLength, spanPastEnd, true);
     return true;
 }
Beispiel #29
0
 public static void CopyStream(Stream src, Stream dst)
 {
     byte[] buff = new byte[4096];
       while (true)
       {
     int read = src.Read(buff, 0, 4096);
     if (read == 0)
       break;
     dst.Write(buff, 0, read);
       }
 }
Beispiel #30
0
    public static void StreamCopyTo(this Stream srcStream, Stream dstStream)
    {
        if (srcStream == null) throw new ArgumentNullException("srcStream");
        if (dstStream == null) throw new ArgumentNullException("dstStream");

        var buffer = new byte[BufferSize];
        int readed;
        while ((readed = srcStream.Read(buffer, 0, BufferSize)) > 0)
        {
            dstStream.Write(buffer, 0, readed);
        }
    }
        public static void CopyTo(this Stream from, Stream dest, int length, byte[] buffer = null)
        {
            buffer = buffer ?? new byte[DefaultCopyBufferSize];
            var bufferSize = buffer.Length;

            int toRead, read, total = 0;
            while ((toRead = Math.Min(length - total, bufferSize)) > 0
                && (read = from.Read(buffer, 0, toRead)) > 0) {
                dest.Write(buffer, 0, read);
                total += read;
            }
        }
Beispiel #32
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="outputStream"></param>
        /// <param name="sequence"></param>
        /// <param name="maxReaded"></param>
        /// <returns></returns>
        public long CopyUpToSequence(Stream outputStream, byte[] sequence, long maxReaded = long.MaxValue)
        {
            long totalCopied = 0;

            void Consume(int length)
            {
                if (length <= 0)
                {
                    return;
                }
                var consumedBytes = _buffer.Consume(length);

                outputStream?.Write(consumedBytes, 0, consumedBytes.Length);
                totalCopied += consumedBytes.Length;
            }

            while (true)
            {
                var tempBufferReaded = InputStream.Read(TempBuffer, 0,
                                                        (int)Math.Min(TempBuffer.Length, maxReaded - totalCopied));
                if (tempBufferReaded > 0)
                {
                    _buffer.Produce(TempBuffer, 0, tempBufferReaded);
                }

                if (_buffer.ConsumeRemaining <= sequence.Length)
                {
                    break;
                }

                var foundIndex = _buffer.IndexOf(sequence);

                // Not Found
                if (foundIndex == -1)
                {
                    Consume(_buffer.ConsumeRemaining - sequence.Length);
                }
                // Found!
                else
                {
                    Consume(foundIndex);
                    // Remove Sequence.
                    _buffer.Consume(sequence.Length);

                    return(totalCopied);
                }
            }

            Consume(_buffer.ConsumeRemaining);

            return(totalCopied);
        }
Beispiel #33
0
    private static Stream CreateCryptoStreamAESWrite(string sharedSecret, Stream stream)
    {
        if (string.IsNullOrEmpty(sharedSecret))
            throw new ArgumentNullException("sharedSecret");

        // Генерация ключа
        Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

        // Создание объекта RijndaelManaged object
        RijndaelManaged aesAlg = new RijndaelManaged();
        aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

        // Создание дешифратора для выполнения потока преобразования
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        // Указать вначале IV
        stream.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));
        stream.Write(aesAlg.IV, 0, aesAlg.IV.Length);

        CryptoStream csEncrypt = new CryptoStream(stream, encryptor, CryptoStreamMode.Write);
        return csEncrypt;
    }
Beispiel #34
0
        static public void Write(this Stream destination, LogEntry entry)
        {
            var entrySerial = entry?.SerializeToUtf8();

            if (null == entrySerial)
            {
                return;
            }

            var entrySerialAndDelimiter = entrySerial.Concat(new byte[4]).ToArray();

            destination?.Write(entrySerialAndDelimiter, 0, entrySerialAndDelimiter.Length);
        }
Beispiel #35
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     if (IsHtmlResponse())
     {
         WebsocketScriptInjectionHelper.InjectLiveReloadScriptAsync(buffer, offset, count, _context, _baseStream)
         .GetAwaiter()
         .GetResult();
     }
     else
     {
         _baseStream?.Write(buffer, offset, count);
     }
 }
    public void Connect()
    {
        if(!IsInvoking("ParseData")){

            client = new TcpClient("127.0.0.1", 13854);
            stream = client.GetStream();
            buffer = new byte[1024];
            byte[] myWriteBuffer = Encoding.ASCII.GetBytes(@"{""enableRawOutput"": true, ""format"": ""Json""}");
            stream.Write(myWriteBuffer, 0, myWriteBuffer.Length);

            InvokeRepeating("ParseData",0.1f,0.02f);
        }
    }
		public static void CopyTo(this Stream source, Stream destination, byte[] buffer, Action chunkAction)
		{
			var length = buffer.Length;
			while (true)
			{
				int read = source.Read(buffer, 0, length);
				if (read <= 0)
					break;

				destination.Write(buffer, 0, read);
				chunkAction();
			}
		}
Beispiel #38
0
	/// <summary>
	/// Writes the input stream to the target stream.
	/// </summary>
	/// <param name="source" this="true">The source stream to write to the target stream.</param>
	/// <param name="target">The target stream to write to.</param>
	/// <returns>The written <paramref name="target"/> stream.</returns>
	public static Stream WriteTo(this Stream source, Stream target)
	{
		var buffer = new byte[BufferSize];
		var read = 0;
		while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
		{
			target.Write(buffer, 0, read);
		}

		if (target.CanSeek)
			target.Seek(0, SeekOrigin.Begin);

		return target;
	}
Beispiel #39
0
        public int GetCrc32AndCopy(Stream input, Stream output)
        {
            if (input == null)
            {
                throw new Exception("The input stream must not be null.");
            }
            byte[] array = new byte[8192];
            int    count = 8192;

            _TotalBytesRead = 0L;
            int num = input.Read(array, 0, count);

            output?.Write(array, 0, num);
            _TotalBytesRead += num;
            while (num > 0)
            {
                SlurpBlock(array, 0, num);
                num = input.Read(array, 0, count);
                output?.Write(array, 0, num);
                _TotalBytesRead += num;
            }
            return((int)(~_register));
        }
Beispiel #40
0
        public int GetCrc32AndCopy(Stream input, Stream output)
        {
            if (input == null)
            {
                throw new Exception("The input stream must not be null.");
            }
            byte[] buffer   = new byte[8192];
            int    readSize = 8192;

            _TotalBytesRead = 0L;
            int count = input.Read(buffer, 0, readSize);

            output?.Write(buffer, 0, count);
            _TotalBytesRead += count;
            while (count > 0)
            {
                SlurpBlock(buffer, 0, count);
                count = input.Read(buffer, 0, readSize);
                output?.Write(buffer, 0, count);
                _TotalBytesRead += count;
            }
            return((int)(~_register));
        }
        public static void Write(Stream stream, byte type, string value)
        {
            Encoding encoding = _threadLocalEncoding.Value;

            byte[] buffer = null;

            try
            {
                buffer = _bufferManager.TakeBuffer(encoding.GetMaxByteCount(value.Length));
                var length = encoding.GetBytes(value, 0, value.Length, buffer, 0);

                stream.WriteByte(type);
                stream.Write(NetworkConverter.GetBytes(length), 0, 4);
                stream.Write(buffer, 0, length);
            }
            finally
            {
                if (buffer != null)
                {
                    _bufferManager.ReturnBuffer(buffer);
                }
            }
        }
Beispiel #42
0
        public static byte[] WriteStruct <T>(T structure, Stream streamHandle = null, int writeOffset = 0) where T : struct
        {
            try
            {
                var buffer = structure.ToBytes() as byte[] ?? new byte[0];
                streamHandle?.Write(buffer, writeOffset, buffer.Length);

                return(buffer);
            }
            catch
            {
                return(null);
            }
        }
Beispiel #43
0
	public static void EncryptData(Stream inputStream, Stream outputStream)
	{
		byte[] buf = new byte[ENCRYPT_SIZE];
		while (true)
		{
			int bytesRead = ReadBlock(inputStream, buf);
			if (bytesRead == 0)
			{
				break;
			}
			byte[] reversedBuffer = ShiftByteArrayRight(buf, bytesRead);
			outputStream.Write(reversedBuffer, 0, bytesRead);
		}
	}
        private void Store(ref ZipFileEntry _zfe, Stream _source)
        {
            byte[] buffer    = new byte[16384];
            uint   num       = 0;
            Stream stream    = (Stream)null;
            long   position1 = this.ZipFileStream.Position;
            long   position2 = _source.Position;

            if (_zfe.Method == BlueStacks.BlueStacksUI.Compression.Store)
            {
                stream = this.ZipFileStream;
            }
            else if (_zfe.Method == BlueStacks.BlueStacksUI.Compression.Deflate)
            {
                stream = (Stream) new DeflateStream(this.ZipFileStream, CompressionMode.Compress, true);
            }
            _zfe.Crc32 = uint.MaxValue;
            int count;

            do
            {
                count = _source.Read(buffer, 0, buffer.Length);
                num  += (uint)count;
                if (count > 0)
                {
                    stream?.Write(buffer, 0, count);
                    for (uint index = 0; (long)index < (long)count; ++index)
                    {
                        _zfe.Crc32 = ZipStorer.CrcTable[((int)_zfe.Crc32 ^ (int)buffer[(int)index]) & (int)byte.MaxValue] ^ _zfe.Crc32 >> 8;
                    }
                }
            }while (count == buffer.Length);
            stream.Flush();
            if (_zfe.Method == BlueStacks.BlueStacksUI.Compression.Deflate)
            {
                stream.Dispose();
            }
            _zfe.Crc32         ^= uint.MaxValue;
            _zfe.FileSize       = num;
            _zfe.CompressedSize = (uint)(this.ZipFileStream.Position - position1);
            if (_zfe.Method != BlueStacks.BlueStacksUI.Compression.Deflate || this.ForceDeflating || (!_source.CanSeek || _zfe.CompressedSize <= _zfe.FileSize))
            {
                return;
            }
            _zfe.Method = BlueStacks.BlueStacksUI.Compression.Store;
            this.ZipFileStream.Position = position1;
            this.ZipFileStream.SetLength(position1);
            _source.Position = position2;
            this.Store(ref _zfe, _source);
        }
        private void ReadResponseAsByte(WebResponse resp, CancellationToken token, Stream outputStream = null)
        {
            using (Stream responseStream = resp.GetResponseStream())
            {
                var buffer = new byte[65536];
                int bytesRead;

                while (responseStream != null && (bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    token.ThrowIfCancellationRequested();
                    outputStream?.Write(buffer, 0, bytesRead);
                }
            }
        }
 /// <summary>
 /// CopyStream simply copies 'fromStream' to 'toStream'
 /// </summary>
 public static int CopyStream(Stream fromStream, Stream toStream)
 {
     byte[] buffer = new byte[8192];
     int totalBytes = 0;
     for (; ; )
     {
         int count = fromStream.Read(buffer, 0, buffer.Length);
         if (count == 0)
             break;
         toStream.Write(buffer, 0, count);
         totalBytes += count;
     }
     return totalBytes;
 }
Beispiel #47
0
		void LogEntryWrite(LogEntry entry)
		{
			try
			{
				lock (logStream)
				{
					logStream?.Write(entry);
					logStream?.Flush();
				}
			}
			catch (Exception e)
			{
				logEntryWriteException = e;
			}
		}
    /// <summary>
    /// Encodes a single uint data point.
    /// </summary>
    /// <param name="stream">Stream used to capture encoded bytes.</param>
    /// <param name="value">The value to encode.</param>
    /// <returns>Number of bytes used for encoding.</returns>
    public int Encode(Stream stream, uint value)
    {
        int count = 0, index = 0;
        byte[] buffer = new byte[8];

        do
        {
            buffer[index++] = (byte)((value & 0x7F) | 0x80);    // read first 7-bits, and check for MSB set
            value >>= 7;                                        // shift right 7 bits
            count++;                                            // increment bytes written counter
        } while (value != 0);

        buffer[index - 1] &= 0x7F;  // mark last byte MSB low since we're done

        // write data and return length
        stream.Write(buffer, 0, count);
        return count;
    }
Beispiel #49
0
        public void Send(Packet data)
        {
            if (Stream == null || !_socket.Connected)
            {
                return;
            }

            Task.Run( // Initiate the sender thread
                () => {
                try {
                    byte[] buffer = data.SerializePacket();
                    Stream?.Write(buffer, 0, buffer.Length);

                    DataSent?.Invoke(this, data);
                } catch (Exception ex) {
                    ConnectionLost?.Invoke(this, ex);
                }
            }
                );
        }
		public static void CopyTo(this Stream source, Stream destination, long start, long length, Action chunkAction)
		{
			var end = start + length;
			source.Seek(start, SeekOrigin.Begin);
			var bytesRemaining = end - source.Position;
			var buffer = new byte[ReadStreamBufferSize];

			while (bytesRemaining > 0)
			{
				var bytesRead = source.Read(buffer, 0, bytesRemaining > ReadStreamBufferSize ? ReadStreamBufferSize : (int) bytesRemaining);

				if (bytesRead == 0)
					break;

				destination.Write(buffer, 0, bytesRead);
				chunkAction();

				bytesRemaining = end - source.Position;
			}
		}
    static void DecompressStream(Stream from, Stream to)
    {
        byte[] src = new byte[from.Length];

        // read file
        if (from.Read(src, 0, src.Length) == src.Length)
        {
            int dstSize = DllInterface.aPsafe_get_orig_size(src);

            // allocate mem
            byte[] dst = new byte[dstSize];

            // decompress data
            int depackedSize = DllInterface.aPsafe_depack(src, src.Length, dst, dstSize);

            // write compressed data
            to.Write(dst, 0, depackedSize);

            Console.WriteLine("decompressed to {0} bytes", depackedSize);
        }
    }
Beispiel #52
0
        public void Write(
            byte[] buffer,
            int count)
        {
            _target?.Write(buffer, 0, count);

            if (_target is FileStream fs)
            {
                // force disk flush to better reflect
                // progress, esp across network shares
                // also caching here in the case of
                // device-to-device where the user is
                // likely to want to to remove the target
                // simply means having to wait for sync
                // at target dismount / eject
                fs.Flush(true);
            }
            else
            {
                _target?.Flush();
            }
        }
        public bool ReadResponse(Stream dataOut, out int bytesRead, ICallback callback)
        {
            callback.Dispose();

            var buffer = new byte[dataOut.Length];

            if (_resourceIsCached)
            {
                bytesRead = _fileReadStream.Read(buffer, 0, buffer.Length);

                dataOut.Write(buffer, 0, buffer.Length);

                return(bytesRead > 0);
            }


            bytesRead = _httpStream.Read(buffer, 0, buffer.Length);

            dataOut.Write(buffer, 0, buffer.Length);

            _fileWriteStream?.Write(buffer, 0, buffer.Length);

            return(bytesRead > 0);
        }
Beispiel #54
0
 static int writeAmfType(Stream stream, byte b)
 {
     byte[] bytes = new byte[] { b };
     stream?.Write(bytes, 0, bytes.Length);
     return(bytes.Length);
 }
Beispiel #55
0
        private void ReadResponseAsByte(WebResponse resp, CancellationToken token, Stream outputStream = null, long contentLength = 0, OperationType operation = OperationType.None)
        {
            if (!Enum.IsDefined(typeof(OperationType), operation))
            {
                throw new ArgumentOutOfRangeException(nameof(operation));
            }

            if (outputStream != null && (contentLength != 0 && outputStream.Position == 0))
            {
                //this.OnChangedProgressPercent(new ProgressChangedEventArgs(
                //                0,
                //                new ProgressChangeTaskState()
                //                {
                //                    Type = operation,
                //                    TotalBytes = new FileSize()
                //                    {
                //                        DefaultValue = contentLength
                //                    },
                //                    BytesInProgress = new FileSize()
                //                    {
                //                        DefaultValue = 0L
                //                    }
                //                }));
            }

            int bufSizeChunk = 30000;
            int totalBufSize = bufSizeChunk;

            byte[] fileBytes       = new byte[totalBufSize];
            double percentComplete = 0;

            int totalBytesRead = 0;

            using (var reader = new BinaryReader(resp.GetResponseStream()))
            {
                int bytesRead;
                while ((bytesRead = reader.Read(fileBytes, totalBytesRead, totalBufSize - totalBytesRead)) > 0)
                {
                    token.ThrowIfCancellationRequested();

                    outputStream?.Write(fileBytes, totalBytesRead, bytesRead);

                    totalBytesRead += bytesRead;

                    if ((totalBufSize - totalBytesRead) == 0)
                    {
                        totalBufSize += bufSizeChunk;
                        Array.Resize(ref fileBytes, totalBufSize);
                    }

                    if (outputStream != null && (contentLength != 0 && contentLength >= outputStream.Position))
                    {
                        var tempPercentComplete = 100.0 * outputStream.Position / contentLength;
                        if (tempPercentComplete - percentComplete >= 1)
                        {
                            //percentComplete = tempPercentComplete;
                            //this.OnChangedProgressPercent(new ProgressChangedEventArgs(
                            //    (int)percentComplete,
                            //    new ProgressChangeTaskState()
                            //    {
                            //        Type = operation,
                            //        TotalBytes = new FileSize()
                            //        {
                            //            DefaultValue = contentLength
                            //        },
                            //        BytesInProgress = new FileSize()
                            //        {
                            //            DefaultValue = outputStream.Position
                            //        }
                            //    }));
                        }
                    }
                }

                if (outputStream != null && (contentLength != 0 && outputStream.Position == contentLength))
                {
                    //this.OnChangedProgressPercent(new ProgressChangedEventArgs(
                    //            100,
                    //            new ProgressChangeTaskState()
                    //            {
                    //                Type = operation,
                    //                TotalBytes = new FileSize()
                    //                {
                    //                    DefaultValue = contentLength
                    //                },
                    //                BytesInProgress = new FileSize()
                    //                {
                    //                    DefaultValue = outputStream.Position
                    //                }
                    //            }));
                }
            }
        }
Beispiel #56
0
        public IList Write(IList content)
        {
            if (Stream == null)
            {
                CreateStreams();
            }

            if (content.Count <= 0)
            {
                return(content);
            }

            if (content[0] is PSObject)
            {
                content = content.BaseArray();
            }

            if (content[0] is string)
            {
                if (encoder == null)
                {
                    encoder = Encoding.UTF8.GetEncoder();
                }

                foreach (string str in content)
                {
                    var chars    = (str + "\n").ToCharArray();
                    var numBytes = encoder.GetByteCount(chars, 0, chars.Length, false);

                    var bytes          = new byte[Math.Min(numBytes, ByteBufferSize)];
                    var convertedChars = 0;

                    var completed = false;
                    while (!completed)
                    {
                        int charsUsed;
                        int bytesUsed;

                        encoder.Convert(chars, convertedChars, chars.Length - convertedChars, bytes, 0, bytes.Length, false, out charsUsed, out bytesUsed, out completed);
                        convertedChars += charsUsed;

                        Stream?.Write(bytes, 0, bytesUsed);
                    }
                }
            }
            else if (content[0] is byte)
            {
                var bytes = content as byte[] ?? content.Cast <byte>().ToArray();

                var bytesWritten = 0;
                while (bytesWritten < bytes.Length)
                {
                    var written = Math.Min(bytes.Length - bytesWritten, ByteBufferSize);
                    Stream?.Write(bytes, bytesWritten, written);
                    bytesWritten += written;
                }
            }
            else
            {
                throw new ArgumentOutOfRangeException(nameof(content));
            }

            return(content);
        }
Beispiel #57
0
 public override void Write(byte[] buffer, int offset, int count)
 {
     _stream?.Write(buffer, offset, count);
 }
Beispiel #58
0
        /// <summary>
        /// Writes a given <seealso cref="IHtmlContent"/> instance to another stream.
        /// </summary>
        /// <param name="htmlContent"></param>
        /// <param name="stream"></param>
        public static void WriteTo(this IHtmlContent htmlContent, Stream stream)
        {
            var bytes = Encoding.UTF8.GetBytes(htmlContent.Render());

            stream?.Write(bytes, 0, bytes.Length);
        }