Example #1
0
        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);
                }
            }
        }
Example #2
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 );
    }
	/// <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);
		}
	}
    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);
        }
    }
Example #5
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);
 }
Example #6
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);
     }
 }
Example #10
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;
     }
 }
Example #11
0
        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);
            }
        }
Example #12
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);
    }
Example #13
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);
        }
Example #14
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);
       }
 }
 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;
 }
	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);
		}
	}
Example #17
0
 public MyWebRequest(string url, string method, string data)
     : this(url, method)
 {
     string postData = data;
     byte[] byteArray = Encoding.UTF8.GetBytes(postData);
     request.ContentType = "application/x-www-form-urlencoded";
     request.ContentLength = byteArray.Length;
     dataStream = request.GetRequestStream();
     dataStream.Write(byteArray, 0, byteArray.Length);
     dataStream.Close();
 }
Example #18
0
    void PostData()
    {
        request = WebRequest.Create(ConfigurationManager.AppSettings["DIRECT_LINK_URL"]);
        request.Method = "POST";
        byte[] byteArray = Encoding.UTF8.GetBytes(data);
        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = byteArray.Length;

        dataStream = request.GetRequestStream();
        dataStream.Write(byteArray, 0, byteArray.Length);
        dataStream.Close();
    }
Example #19
0
        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;
            }
        }
Example #20
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);
        }
    }
Example #21
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;
    }
    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();
			}
		}
 /// <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;
 }
Example #25
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);
		}
	}
Example #26
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;
	}
Example #27
0
        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);
                }
            }
        }
    /// <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;
    }
		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);
        }
    }