Example #1
0
 void writeHeader(MemoryStream stream)
 {
     stream.WriteByte(byCmd);
     stream.WriteByte(byParam);
     byte[] bpara = BitConverter.GetBytes(dwTimestamp);
     stream.Write(bpara, 0, bpara.Length);
     //Debug.Log("byCmd=" + byCmd + " byParam" + byParam + " dwTimestamp" + dwTimestamp + " length" + bpara.Length + " bpara" + bpara.ToString());
 }
    public GamePacketStream(short message_id)
    {
        stream = new MemoryStream();

        stream.WriteByte(0xff);
        stream.WriteByte(0xff);

        add(message_id);
    }
Example #3
0
 static void CompressProfile(string srcfile, string dstfile)
 {
     try
     {
         Console.WriteLine("Reading source...");
         byte[] x = File.ReadAllBytes(srcfile);
         int usize = x.Length;
         Console.WriteLine("Initializing memory stream...");
         MemoryStream ms = new MemoryStream();
         // write uncompressed size as big endian
         ms.WriteByte((byte)((usize>>24) & 0xFF));
         ms.WriteByte((byte)((usize>>16) & 0xFF));
         ms.WriteByte((byte)((usize>>8) & 0xFF));
         ms.WriteByte((byte)(usize & 0xFF));
         // then, compressed data
         // these two bytes are part of zlib standard, but aren't supported by DeflateStream
         ms.WriteByte(0x78);
         ms.WriteByte(0x9C);
         Console.WriteLine("Compressing data...");
         MemoryStream compData = new MemoryStream();
         DeflateStream ds = new DeflateStream(compData, CompressionMode.Compress);
         ds.Write(x, 0, x.Length);
         ds.Close();
         ms.Write(compData.ToArray(), 0, compData.ToArray().Length);
         // Adler32 checksum as big endian - also not supported by DeflateStream, but required by zlib standard
         int checksum = GetAdler32(x);
         ms.WriteByte((byte)((checksum>>24) & 0xFF));
         ms.WriteByte((byte)((checksum>>16) & 0xFF));
         ms.WriteByte((byte)((checksum>>8) & 0xFF));
         ms.WriteByte((byte)(checksum & 0xFF));
         // start filestream
         Console.WriteLine("Creating file stream...");
         FileStream fs = File.Create(dstfile);
         // write hash
         fs.Write(new SHA1CryptoServiceProvider().ComputeHash(ms.ToArray()), 0, 0x14);
         // write usize + compressed data
         fs.Write(ms.ToArray(), 0, ms.ToArray().Length);
         Console.WriteLine("Compression done.\n" + dstfile);
         fs.Close();
         ms.Close();
         compData.Close();
     }
     catch(Exception ex)
     {
         Console.WriteLine(ex.GetType().Name + " | " + ex.Message);
         Console.Beep();
     }
     return;
 }
Example #4
0
        /// <summary>
        ///  shifts the values of the target array to make place for the
        ///  values of the source array at the end.
        ///  values that fall out of the target array are written to the end of
        ///  the stream if the stream is not null
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <param name="stream"></param>
        /// <returns>the modified target array</returns>
        private byte[] CopyInEnd(byte[] source, byte[] target, MemoryStream stream)
        {
            if (source.Length > target.Length)
            {
                throw new ArgumentOutOfRangeException("source", "source cannot be longer than target");
            }
            var d = target.Length - source.Length;
            var s = source.Length;

            for (var i = 0; i < target.Length; i++)
            {
                if (i >= s)
                {
                    target[i - s] = target[i];
                }
                else
                {
                    stream?.WriteByte(target[i]);
                }
                if (i >= d)
                {
                    target[i] = source[i - d];
                }
            }
            return(target);
        }
Example #5
0
	//public static string Unscramble(string text ) {
	//	byte[] clear = Encoding.UTF8.GetBytes (text);
	//	return Encoding.UTF8.GetString( Xor( clear) );
	//}

	public static byte[] Xor(byte[] clearTextBytes )
	{

		byte[] key = GenKey (clearTextBytes.Length);

		//Debug.Log ("KEY : " + Encoding.Unicode.GetString (key));

		MemoryStream ms = new MemoryStream();
	
		for (int i = 0; i < clearTextBytes.Length; i++) {

			byte b = (byte)(  (clearTextBytes [i] ^ key [i]) );

			//if (b == 0 ) {
			//	b = key [i];
				//Debug.Log ("GOt NULL BYTE FROM KEY: " + key [i] + ", BYTE: " + clearTextBytes [i]);
			//}

			ms.WriteByte ( b );
		}

		byte[] output =  ms.ToArray();
		//Debug.Log ("SCRAM OUT: " + output.Length);
		return output;

	}
Example #6
0
    public bool NegTest2() 
    {
        bool retVal = true;
        TestLibrary.TestFramework.BeginScenario("Verify InvalidOperationException is thrown when set ReadTimeOut property...");

        try
        {
            Stream s = new MemoryStream();
            for (int i = 0; i < 100; i++)
                s.WriteByte((byte)i);
            s.Position = 0;

            s.ReadTimeout = 10;

            TestLibrary.TestFramework.LogError("001", "No exception occurs!");
            retVal = false;
        }
        catch (InvalidOperationException)
        {
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception occurs: " + e);
            retVal = false;
        }

        return retVal;
    }
Example #7
0
 public static bool MemStreamClearWriteByteTest()
 {
     Console.WriteLine("Ensuring that we clear data > Length in a MemoryStream when we write past the end via WriteByte");
     const int len = 10;
     const int spanPastEnd = 5;
     MemoryStream ms = new MemoryStream(3*len);
     byte[] bytes = new byte[len];
     for(int i=0; i<bytes.Length; i++)
         bytes[i] = (byte) i;
     ms.Write(bytes, 0, bytes.Length);
     for(int i=0; i<2*len; i++)
         ms.WriteByte((byte)255);
     ms.SetLength(len);
     ms.Seek(spanPastEnd, SeekOrigin.End);
     for(int i=0; i<bytes.Length; i++)
         ms.WriteByte(bytes[i]);
     ms.Position = bytes.Length;
     byte[] newData = new byte[bytes.Length + spanPastEnd];
     int n = ms.Read(newData, 0, newData.Length);
     if (n != newData.Length) 
     {
         iCountErrors++ ;
         throw new Exception("Hmmm, maybe a bug in the stream.  Asked to read "+newData.Length+", but got back "+n+" bytes.");
     }
     for(int i=0; i<spanPastEnd; i++)
     {
         if (newData[i] != 0)
         {
             iCountErrors++ ;
             throw new Exception(String.Format("New data in the middle of the stream should have been all 0's, but at position {0} I got a wrong byte: {1} [0x{1:x}]!", i+bytes.Length, newData[i]));
         }
     }
     for(int i=0; i<bytes.Length; i++)
     {
         if (newData[i+spanPastEnd] != bytes[i])
         {
             iCountErrors++ ;
             throw new Exception(String.Format("New data at the end of the stream should have been equal to our byte[], but the {0}'th new byte was a wrong byte: {1} [0x{1:x}]!", i, newData[i+spanPastEnd]));
         }
     }
     ms.Flush();
     ms.Close();
     return true;
 }    
Example #8
0
    // Use this for initialization
    private void Start()
    {
        int count;
        byte[] byteArray;
        char[] charArray;
        UnicodeEncoding uniEncoding = new UnicodeEncoding();

        // Create the data to write to the stream. 
        byte[] firstString = uniEncoding.GetBytes(
            "Invalid file path characters are: ");
        byte[] secondString = uniEncoding.GetBytes(
            "123456789");

        using (MemoryStream memStream = new MemoryStream(100))
        {
            // Write the first string to the stream.
            memStream.Write(firstString, 0, firstString.Length);

            // Write the second string to the stream, byte by byte.
            count = 0;
            while (count < secondString.Length)
            {
                memStream.WriteByte(secondString[count++]);
            }

            // Write the stream properties to the console.
            Debug.Log(String.Format(
                "Capacity = {0}, Length = {1}, Position = {2}\n",
                memStream.Capacity.ToString(),
                memStream.Length.ToString(),
                memStream.Position.ToString()));

            // Set the position to the beginning of the stream.
            memStream.Seek(0, SeekOrigin.Begin);

            // Read the first 20 bytes from the stream.
            byteArray = new byte[memStream.Length];
            count = memStream.Read(byteArray, 0, 20);

            // Read the remaining bytes, byte by byte. 
            while (count < memStream.Length)
            {
                byteArray[count++] =
                    Convert.ToByte(memStream.ReadByte());
            }

            // Decode the byte array into a char array 
            // and write it to the console.
            charArray = new char[uniEncoding.GetCharCount(
                byteArray, 0, count)];
            uniEncoding.GetDecoder().GetChars(
                byteArray, 0, count, charArray, 0);
            Debug.Log(charArray);
        }
    }
    public byte[] Compress(byte[] data)
    {
        using (var stream = new MemoryStream())
        {
            int len = data.Length;
            int source = 0;

            while (len > 0)
            {
                long flagdest = stream.Position;
                stream.WriteByte(0);

                byte flags = 0; /* All guess wrong initially */

                for (int bitmask = 1, i = 0; i < 8 && len > 0; i++, bitmask <<= 1)
                {
                    if (_guessTable[_hash] == data[source])
                    {
                        flags |= (byte)bitmask;  /* Guess was right - don't output */
                    }
                    else
                    {
                        _guessTable[_hash] = data[source];
                        stream.WriteByte(data[source]); /* Guess wrong, output char */
                    }

                    Hash(data[source++]);
                    len--;
                }

                long dest = stream.Position;
                stream.Position = flagdest;
                stream.WriteByte(flags);
                stream.Position = dest;
            }

            return stream.ToArray();
        }
    }
    //将Stream流转换为byte数组的方法。   
    public byte[] ConvertStreamToByteBuffer(Stream s)
    {
        if (!CheckUserRight(null, null))
        {
            throw new Exception("invalid user");
        }


        MemoryStream ms = new MemoryStream();
        int b;
        while ((b = s.ReadByte()) != -1)
        {
            ms.WriteByte((byte)b);
        }
        return ms.ToArray();
    }
Example #11
0
        public static void MemoryStream_WriteByte_BeyondCapacity()
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                long origLength = memoryStream.Length;
                byte[] bytes = new byte[10];
                for (int i = 0; i < bytes.Length; i++)
                    bytes[i] = (byte)i;
                int spanPastEnd = 5;
                memoryStream.Seek(spanPastEnd, SeekOrigin.End);
                Assert.Equal(memoryStream.Length + spanPastEnd, memoryStream.Position);

                // Test WriteByte
                origLength = memoryStream.Length;
                memoryStream.Position = memoryStream.Length + spanPastEnd;
                memoryStream.WriteByte(0x42);
                long expected = origLength + spanPastEnd + 1;
                Assert.Equal(expected, memoryStream.Position);
                Assert.Equal(expected, memoryStream.Length);
            }
        }
Example #12
0
        public async Task CopyToAsyncTest_RequiresAsyncFlushingOfWrites()
        {
            byte[] data = Enumerable.Range(0, 1000).Select(i => (byte)(i % 256)).ToArray();

            var manualReleaseStream = new ManuallyReleaseAsyncOperationsStream();
            var src = new BufferedStream(manualReleaseStream);
            src.Write(data, 0, data.Length);
            src.Position = 0;

            var dst = new MemoryStream();

            data[0] = 42;
            src.WriteByte(42);
            dst.WriteByte(42);

            Task copyTask = src.CopyToAsync(dst);
            manualReleaseStream.Release();
            await copyTask;

            Assert.Equal(data, dst.ToArray());
        }
Example #13
0
    public static byte[] UrlDecodeToBytes(byte [] bytes, int offset, int count)
    {
        if (bytes == null)
                return null;
            if (count == 0)
                return new byte [0];

            MemoryStream result = new MemoryStream ();
            int end = offset + count;
            for (int i = offset; i < end; i++){
                char c = (char) bytes [i];
                if (c == '+') {
                    c = ' ';
                } else if (c == '%' && i < end - 2) {
                    int xchar = GetChar (bytes, i + 1, 2);
                    if (xchar != -1) {
                        c = (char) xchar;
                        i += 2;
                    }
                }
                result.WriteByte ((byte) c);
            }

            return result.ToArray ();
    }
Example #14
0
    public static string UrlDecode(string s, Encoding e)
    {
        if (null == s)
                return null;

            if (s.IndexOf ('%') == -1 && s.IndexOf ('+') == -1)
                return s;

            if (e == null)
                e = Encoding.UTF8;

            StringBuilder output = new StringBuilder ();
            long len = s.Length;
            MemoryStream bytes = new MemoryStream ();
            int xchar;

            for (int i = 0; i < len; i++) {
                if (s [i] == '%' && i + 2 < len && s [i + 1] != '%') {
                    if (s [i + 1] == 'u' && i + 5 < len) {
                        if (bytes.Length > 0) {
                            output.Append (GetChars (bytes, e));
                            bytes.SetLength (0);
                        }

                        xchar = GetChar (s, i + 2, 4);
                        if (xchar != -1) {
                            output.Append ((char) xchar);
                            i += 5;
                        } else {
                            output.Append ('%');
                        }
                    } else if ((xchar = GetChar (s, i + 1, 2)) != -1) {
                        bytes.WriteByte ((byte) xchar);
                        i += 2;
                    } else {
                        output.Append ('%');
                    }
                    continue;
                }

                if (bytes.Length > 0) {
                    output.Append (GetChars (bytes, e));
                    bytes.SetLength (0);
                }

                if (s [i] == '+') {
                    output.Append (' ');
                } else {
                    output.Append (s [i]);
                }
            }

            if (bytes.Length > 0) {
                output.Append (GetChars (bytes, e));
            }

            bytes = null;
            return output.ToString ();
    }
Example #15
0
        private byte[] DecodePredictor(
            byte[] data,
            PdfDictionary parameters
            )
        {
            if (parameters == null)
            {
                return(data);
            }

            int predictor = (parameters.ContainsKey(PdfName.Predictor) ? ((PdfInteger)parameters[PdfName.Predictor]).RawValue : 1);

            if (predictor == 1) // No predictor was applied during data encoding.
            {
                return(data);
            }

            int sampleComponentBitsCount = (parameters.ContainsKey(PdfName.BitsPerComponent) ? ((PdfInteger)parameters[PdfName.BitsPerComponent]).RawValue : 8);
            int sampleComponentsCount    = (parameters.ContainsKey(PdfName.Colors) ? ((PdfInteger)parameters[PdfName.Colors]).RawValue : 1);
            int rowSamplesCount          = (parameters.ContainsKey(PdfName.Columns) ? ((PdfInteger)parameters[PdfName.Columns]).RawValue : 1);

            MemoryStream input  = new MemoryStream(data);
            MemoryStream output = new MemoryStream();

            switch (predictor)
            {
            case 2: // TIFF Predictor 2 (component-based).
            {
                int[] sampleComponentPredictions = new int[sampleComponentsCount];
                int   sampleComponentDelta       = 0;
                int   sampleComponentIndex       = 0;
                while ((sampleComponentDelta = input.ReadByte()) != -1)
                {
                    int sampleComponent = sampleComponentDelta + sampleComponentPredictions[sampleComponentIndex];
                    output.WriteByte((byte)sampleComponent);

                    sampleComponentPredictions[sampleComponentIndex] = sampleComponent;

                    sampleComponentIndex = ++sampleComponentIndex % sampleComponentsCount;
                }
                break;
            }

            default:                                                                                                                                              // PNG Predictors [RFC 2083] (byte-based).
            {
                int   sampleBytesCount           = (int)Math.Ceiling(sampleComponentBitsCount * sampleComponentsCount / 8d);                                      // Number of bytes per pixel (bpp).
                int   rowSampleBytesCount        = (int)Math.Ceiling(sampleComponentBitsCount * sampleComponentsCount * rowSamplesCount / 8d) + sampleBytesCount; // Number of bytes per row (comprising a leading upper-left sample (see Paeth method)).
                int[] previousRowBytePredictions = new int[rowSampleBytesCount];
                int[] currentRowBytePredictions  = new int[rowSampleBytesCount];
                int[] leftBytePredictions        = new int[sampleBytesCount];
                int   predictionMethod;
                while ((predictionMethod = input.ReadByte()) != -1)
                {
                    Array.Copy(currentRowBytePredictions, 0, previousRowBytePredictions, 0, currentRowBytePredictions.Length);
                    Array.Clear(leftBytePredictions, 0, leftBytePredictions.Length);
                    for (
                        int rowSampleByteIndex = sampleBytesCount; // Starts after the leading upper-left sample (see Paeth method).
                        rowSampleByteIndex < rowSampleBytesCount;
                        rowSampleByteIndex++
                        )
                    {
                        int byteDelta = input.ReadByte();

                        int sampleByteIndex = rowSampleByteIndex % sampleBytesCount;

                        int sampleByte;
                        switch (predictionMethod)
                        {
                        case 0: // None (no prediction).
                            sampleByte = byteDelta;
                            break;

                        case 1: // Sub (predicts the same as the sample to the left).
                            sampleByte = byteDelta + leftBytePredictions[sampleByteIndex];
                            break;

                        case 2: // Up (predicts the same as the sample above).
                            sampleByte = byteDelta + previousRowBytePredictions[rowSampleByteIndex];
                            break;

                        case 3: // Average (predicts the average of the sample to the left and the sample above).
                            sampleByte = byteDelta + (int)Math.Floor(((leftBytePredictions[sampleByteIndex] + previousRowBytePredictions[rowSampleByteIndex])) / 2d);
                            break;

                        case 4: // Paeth (a nonlinear function of the sample above, the sample to the left, and the sample to the upper left).
                        {
                            int paethPrediction;
                            {
                                int leftBytePrediction    = leftBytePredictions[sampleByteIndex];
                                int topBytePrediction     = previousRowBytePredictions[rowSampleByteIndex];
                                int topLeftBytePrediction = previousRowBytePredictions[rowSampleByteIndex - sampleBytesCount];
                                int initialPrediction     = leftBytePrediction + topBytePrediction - topLeftBytePrediction;
                                int leftPrediction        = Math.Abs(initialPrediction - leftBytePrediction);
                                int topPrediction         = Math.Abs(initialPrediction - topBytePrediction);
                                int topLeftPrediction     = Math.Abs(initialPrediction - topLeftBytePrediction);
                                if (leftPrediction <= topPrediction &&
                                    leftPrediction <= topLeftPrediction)
                                {
                                    paethPrediction = leftBytePrediction;
                                }
                                else if (topPrediction <= topLeftPrediction)
                                {
                                    paethPrediction = topBytePrediction;
                                }
                                else
                                {
                                    paethPrediction = topLeftBytePrediction;
                                }
                            }
                            sampleByte = byteDelta + paethPrediction;
                            break;
                        }

                        default:
                            throw new NotSupportedException("Prediction method " + predictionMethod + " unknown.");
                        }
                        output.WriteByte((byte)sampleByte);

                        leftBytePredictions[sampleByteIndex] = currentRowBytePredictions[rowSampleByteIndex] = sampleByte;
                    }
                }
                break;
            }
            }
            return(output.ToArray());
        }
Example #16
0
 // <tag_encoding> ==
 //       <tag_key_len><tag_key><tag_val_len><tag_val>
 //         <tag_key_len> == varint encoded integer
 //         <tag_key> == tag_key_len bytes comprising tag key name
 //         <tag_val_len> == varint encoded integer
 //         <tag_val> == tag_val_len bytes comprising UTF-8 string
 private static void EncodeTagToOutPut(String key, String value, MemoryStream output)
 {
     output.WriteByte(SerializationUtils.TagFieldId);
     EncodeString(key, output);
     EncodeString(value, output);
 }
Example #17
0
 private static void WriteInteger(MemoryStream stream, byte[] i)
 {
     stream.WriteByte(__i);
     stream.WriteByte(__Colon);
     stream.Write(i, 0, i.Length);
     stream.WriteByte(__Semicolon);
 }
Example #18
0
 private static void WriteArrayList(MemoryStream stream, ArrayList a, Hashtable ht, ref int hv, Encoding encoding)
 {
     int len = a.Count;
     byte[] alen = Encoding.ASCII.GetBytes(len.ToString());
     stream.WriteByte(__a);
     stream.WriteByte(__Colon);
     stream.Write(alen, 0, alen.Length);
     stream.WriteByte(__Colon);
     stream.WriteByte(__LeftB);
     for (int i = 0; i < len; i++)
     {
         WriteInteger(stream, Encoding.ASCII.GetBytes(i.ToString()));
         Serialize(stream, a[i], ht, ref hv, encoding);
     }
     stream.WriteByte(__RightB);
 }
Example #19
0
 private static void WriteRef(MemoryStream stream, byte[] r)
 {
     stream.WriteByte(__r);
     stream.WriteByte(__Colon);
     stream.Write(r, 0, r.Length);
     stream.WriteByte(__Semicolon);
 }
Example #20
0
        public static string UrlDecode(byte [] bytes, int offset, int count, Encoding e)
        {
            if (bytes == null)
            {
                return(null);
            }
            if (count == 0)
            {
                return(String.Empty);
            }

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

            if (offset < 0 || offset > bytes.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }

            if (count < 0 || offset + count > bytes.Length)
            {
                throw new ArgumentOutOfRangeException("count");
            }

            StringBuilder output = new StringBuilder();
            MemoryStream  acc    = new MemoryStream();

            int end = count + offset;
            int xchar;

            for (int i = offset; i < end; i++)
            {
                if (bytes [i] == '%' && i + 2 < count && bytes [i + 1] != '%')
                {
                    if (bytes [i + 1] == (byte)'u' && i + 5 < end)
                    {
                        if (acc.Length > 0)
                        {
                            output.Append(GetChars(acc, e));
                            acc.SetLength(0);
                        }
                        xchar = GetChar(bytes, i + 2, 4);
                        if (xchar != -1)
                        {
                            output.Append((char)xchar);
                            i += 5;
                            continue;
                        }
                    }
                    else if ((xchar = GetChar(bytes, i + 1, 2)) != -1)
                    {
                        acc.WriteByte((byte)xchar);
                        i += 2;
                        continue;
                    }
                }

                if (acc.Length > 0)
                {
                    output.Append(GetChars(acc, e));
                    acc.SetLength(0);
                }

                if (bytes [i] == '+')
                {
                    output.Append(' ');
                }
                else
                {
                    output.Append((char)bytes [i]);
                }
            }

            if (acc.Length > 0)
            {
                output.Append(GetChars(acc, e));
            }

            acc = null;
            return(output.ToString());
        }
Example #21
0
        SmtpResponse ReadResponse(CancellationToken cancellationToken)
        {
            using (var memory = new MemoryStream()) {
                bool complete = false;
                bool newLine  = true;
                bool more     = true;
                int  code     = 0;
                int  nread;

                do
                {
                    if (memory.Length > 0 || inputIndex == inputEnd)
                    {
                        // make room for the next read by moving the remaining data to the beginning of the buffer
                        int left = inputEnd - inputIndex;

                        for (int i = 0; i < left; i++)
                        {
                            input[i] = input[inputIndex + i];
                        }

                        inputEnd   = left;
                        inputIndex = 0;

                        cancellationToken.ThrowIfCancellationRequested();

                        if ((nread = stream.Read(input, inputEnd, input.Length - inputEnd)) == 0)
                        {
                            throw new SmtpProtocolException("The server replied with an incomplete response.");
                        }

                        logger.LogServer(input, inputEnd, nread);
                        inputEnd += nread;
                    }

                    complete = false;

                    do
                    {
                        int startIndex = inputIndex;

                        if (newLine && inputIndex < inputEnd)
                        {
                            int value;

                            if (!TryParseInt32(input, ref inputIndex, inputEnd, out value))
                            {
                                throw new SmtpProtocolException("Unable to parse status code returned by the server.");
                            }

                            if (inputIndex == inputEnd)
                            {
                                inputIndex = startIndex;
                                break;
                            }

                            if (code == 0)
                            {
                                code = value;
                            }
                            else if (value != code)
                            {
                                throw new SmtpProtocolException("The status codes returned by the server did not match.");
                            }

                            newLine = false;

                            if (input[inputIndex] != (byte)'\r' && input[inputIndex] != (byte)'\n')
                            {
                                more = input[inputIndex++] == (byte)'-';
                            }
                            else
                            {
                                more = false;
                            }

                            startIndex = inputIndex;
                        }

                        while (inputIndex < inputEnd && input[inputIndex] != (byte)'\r' && input[inputIndex] != (byte)'\n')
                        {
                            inputIndex++;
                        }

                        memory.Write(input, startIndex, inputIndex - startIndex);

                        if (inputIndex < inputEnd && input[inputIndex] == (byte)'\r')
                        {
                            inputIndex++;
                        }

                        if (inputIndex < inputEnd && input[inputIndex] == (byte)'\n')
                        {
                            if (more)
                            {
                                memory.WriteByte(input[inputIndex]);
                            }
                            complete = true;
                            newLine  = true;
                            inputIndex++;
                        }
                    } while (more && inputIndex < inputEnd);
                } while (more || !complete);

                string message = null;

                try {
                    message = Encoding.UTF8.GetString(memory.GetBuffer(), 0, (int)memory.Length);
                } catch {
                    message = Latin1.GetString(memory.GetBuffer(), 0, (int)memory.Length);
                }

                return(new SmtpResponse((SmtpStatusCode)code, message));
            }
        }
Example #22
0
        private void WriteDataChunksFast()
        {
            byte[] pixels = _image.Pixels;

            // Convert the pixel array to a new array for adding
            // the filter byte.
            // --------------------------------------------------
            byte[] data = new byte[_image.PixelWidth * _image.PixelHeight * 4 + _image.PixelHeight];

            int rowLength = _image.PixelWidth * 4 + 1;

            for (int y = 0; y < _image.PixelHeight; y++)
            {
                data[y * rowLength] = 0;

                Array.Copy(pixels, y * _image.PixelWidth * 4, data, y * rowLength + 1, _image.PixelWidth * 4);
            }
            // --------------------------------------------------

            Adler32 adler32 = new Adler32();

            adler32.Update(data);

            using (MemoryStream tempStream = new MemoryStream())
            {
                int remainder = data.Length;

                int blockCount;
                if ((data.Length % MaxBlockSize) == 0)
                {
                    blockCount = data.Length / MaxBlockSize;
                }
                else
                {
                    blockCount = (data.Length / MaxBlockSize) + 1;
                }

                // Write headers
                tempStream.WriteByte(0x78);
                tempStream.WriteByte(0xDA);

                for (int i = 0; i < blockCount; i++)
                {
                    // Write the length
                    ushort length = (ushort)((remainder < MaxBlockSize) ? remainder : MaxBlockSize);

                    if (length == remainder)
                    {
                        tempStream.WriteByte(0x01);
                    }
                    else
                    {
                        tempStream.WriteByte(0x00);
                    }

                    tempStream.Write(BitConverter.GetBytes(length), 0, 2);

                    // Write one's compliment of length
                    tempStream.Write(BitConverter.GetBytes((ushort)~length), 0, 2);

                    // Write blocks
                    tempStream.Write(data, (int)(i * MaxBlockSize), length);

                    // Next block
                    remainder -= MaxBlockSize;
                }

                WriteInteger(tempStream, (int)adler32.Value);

                tempStream.Seek(0, SeekOrigin.Begin);

                byte[] zipData = new byte[tempStream.Length];
                tempStream.Read(zipData, 0, (int)tempStream.Length);

                WriteChunk(PngChunkTypes.Data, zipData);
            }
        }
Example #23
0
            public byte[] GetByte()
            {
                MemoryStream ms = new MemoryStream();

                ms.Write(Form1.PublicHead, 0, 10);
                ms.Write(DestAddr, 0, 6);
                ms.Write(SourceAddr, 0, 6);
                ms.WriteByte(Type);
                ms.WriteByte(Fomat);
                ms.WriteByte((byte)(Frameno & 0xff));
                ms.WriteByte((byte)(Frameno >> 8));
                ms.WriteByte((byte)(Framelen & 0xff));
                ms.WriteByte((byte)(Framelen >> 8));
                ms.WriteByte((byte)(Framelen >> 16));
                ms.WriteByte((byte)(Framelen >> 24));
                ms.WriteByte((byte)(TotalPackage & 0xff));
                ms.WriteByte((byte)(TotalPackage >> 8));
                ms.WriteByte((byte)(CurrPackage & 0xff));
                ms.WriteByte((byte)(CurrPackage >> 8));
                ms.WriteByte((byte)(Datalen & 0xff));
                ms.WriteByte((byte)(Datalen >> 8));
                ms.WriteByte((byte)(PackLen & 0xff));
                ms.WriteByte((byte)(PackLen >> 8));
                ms.WriteByte((byte)(Half_duplex_arg & 0xff));
                ms.WriteByte((byte)(Half_duplex_arg >> 8));
                ms.WriteByte((byte)(Half_duplex_arg2 & 0xff));
                ms.WriteByte((byte)(Half_duplex_arg2 >> 8));
                if (audioData != null)
                {
                    ms.Write(audioData, 0, audioData.Length);
                }
                ms.Position = 0;
                byte[] d = new byte[ms.Length];
                ms.Read(d, 0, (int)ms.Length);
                ms.Close();
                return(d);
            }
Example #24
0
 public void WriteByte(byte b)
 {
     stream.WriteByte(b);
 }
Example #25
0
        protected override MemoryStream EncodeTexture()
        {
            // Calculate what the length of the texture will be
            int textureLength = 16 + (textureWidth * textureHeight * dataCodec.Bpp / 8);

            if (hasGlobalIndex)
            {
                textureLength += 16;
            }
            if (dataCodec.PaletteEntries != 0 && !dataCodec.NeedsExternalPalette)
            {
                textureLength += (dataCodec.PaletteEntries * pixelCodec.Bpp / 8);
            }

            // Calculate the mipmap padding (if the texture contains mipmaps)
            int mipmapPadding = 0;

            if (dataCodec.HasMipmaps)
            {
                if (dataFormat == PvrDataFormat.SquareTwiddledMipmaps)
                {
                    // A 1x1 mipmap takes up as much space as a 2x1 mipmap
                    // There are also 4 extra bytes at the end of the file
                    mipmapPadding  = (dataCodec.Bpp) >> 3;
                    textureLength += 4;
                }
                else if (dataFormat == PvrDataFormat.SquareTwiddledMipmapsAlt)
                {
                    // A 1x1 mipmap takes up as much space as a 2x2 mipmap
                    mipmapPadding = (3 * dataCodec.Bpp) >> 3;
                }

                textureLength += mipmapPadding;

                for (int size = 1; size < textureWidth; size <<= 1)
                {
                    textureLength += Math.Max((size * size * dataCodec.Bpp) >> 3, 1);
                }
            }

            MemoryStream destination = new MemoryStream(textureLength);

            // Write out the GBIX header (if we are including one)
            if (hasGlobalIndex)
            {
                destination.WriteByte((byte)'G');
                destination.WriteByte((byte)'B');
                destination.WriteByte((byte)'I');
                destination.WriteByte((byte)'X');

                PTStream.WriteUInt32(destination, 8);
                PTStream.WriteUInt32(destination, globalIndex);
                PTStream.WriteUInt32(destination, 0);
            }

            // Write out the PVRT header
            destination.WriteByte((byte)'P');
            destination.WriteByte((byte)'V');
            destination.WriteByte((byte)'R');
            destination.WriteByte((byte)'T');

            if (hasGlobalIndex)
            {
                PTStream.WriteInt32(destination, textureLength - 24);
            }
            else
            {
                PTStream.WriteInt32(destination, textureLength - 8);
            }

            destination.WriteByte((byte)pixelFormat);
            destination.WriteByte((byte)dataFormat);
            PTStream.WriteUInt16(destination, 0);

            PTStream.WriteUInt16(destination, textureWidth);
            PTStream.WriteUInt16(destination, textureHeight);

            // If we have an internal palette, write it
            if (dataCodec.PaletteEntries != 0 && !dataCodec.NeedsExternalPalette)
            {
                byte[] palette = pixelCodec.EncodePalette(texturePalette, dataCodec.PaletteEntries);
                destination.Write(palette, 0, palette.Length);
            }

            // Write out any mipmaps
            if (dataCodec.HasMipmaps)
            {
                // Write out any padding bytes before the 1x1 mipmap
                for (int i = 0; i < mipmapPadding; i++)
                {
                    destination.WriteByte(0);
                }

                for (int size = 1; size < textureWidth; size <<= 1)
                {
                    byte[] mipmapDecodedData = BitmapToRawResized(decodedBitmap, size, 1);
                    byte[] mipmapTextureData = dataCodec.Encode(mipmapDecodedData, 0, size, size);
                    destination.Write(mipmapTextureData, 0, mipmapTextureData.Length);
                }
            }

            // Write the texture data
            byte[] textureData = dataCodec.Encode(decodedData, textureWidth, textureHeight, null);
            destination.Write(textureData, 0, textureData.Length);

            // If the data format is square twiddled with mipmaps, write out the extra bytes.
            if (dataFormat == PvrDataFormat.SquareTwiddledMipmaps)
            {
                destination.Write(new byte[] { 0, 0, 0, 0 }, 0, 4);
            }

            // Compress the texture
            if (compressionFormat != PvrCompressionFormat.None)
            {
                compressionCodec = PvrCompressionCodec.GetCompressionCodec(compressionFormat);

                if (compressionCodec != null)
                {
                    // Ok, we need to convert the current stream to an array, compress it, then write it back to a new stream
                    byte[] buffer = destination.ToArray();
                    buffer = compressionCodec.Compress(buffer, (hasGlobalIndex ? 0x20 : 0x10), pixelCodec, dataCodec);

                    destination = new MemoryStream();
                    destination.Write(buffer, 0, buffer.Length);
                }
            }

            return(destination);
        }
Example #26
0
 public override void serialize(MemoryStream stream)
 {
     base.serialize(stream);
     stream.Write(name,0,name.Length);
     stream.WriteByte(err_code);
 }
Example #27
0
        private void writeToStream(Stream writeStream)
        {
            fireDebug("Writing Ticket...");

            fireDebug("   Encrypting Title Key...");
            encryptTitleKey();
            fireDebug("    -> Decrypted Title Key: {0}", Shared.ByteArrayToString(decryptedTitleKey));
            fireDebug("    -> Encrypted Title Key: {0}", Shared.ByteArrayToString(encryptedTitleKey));

            if (fakeSign)
            {
                fireDebug("   Clearing Signature..."); signature = new byte[256];
            }                                                                     //Clear Signature if we fake Sign

            MemoryStream ms = new MemoryStream();

            ms.Seek(0, SeekOrigin.Begin);

            fireDebug("   Writing Signature Exponent... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(BitConverter.GetBytes(Shared.Swap(signatureExponent)), 0, 4);

            fireDebug("   Writing Signature... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(signature, 0, signature.Length);

            fireDebug("   Writing Padding... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(padding, 0, padding.Length);

            fireDebug("   Writing Issuer... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(issuer, 0, issuer.Length);

            fireDebug("   Writing Unknown... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(unknown, 0, unknown.Length);

            fireDebug("   Writing Title Key... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(encryptedTitleKey, 0, encryptedTitleKey.Length);

            fireDebug("   Writing Unknown2... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.WriteByte(unknown2);

            fireDebug("   Writing Ticket ID... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(BitConverter.GetBytes(Shared.Swap(ticketId)), 0, 8);

            fireDebug("   Writing Console ID... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(BitConverter.GetBytes(Shared.Swap(consoleId)), 0, 4);

            fireDebug("   Writing Title ID... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(BitConverter.GetBytes(Shared.Swap(titleId)), 0, 8);

            fireDebug("   Writing Unknwon3... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(BitConverter.GetBytes(Shared.Swap(unknown3)), 0, 2);

            fireDebug("   Writing NumOfDLC... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(BitConverter.GetBytes(Shared.Swap(numOfDlc)), 0, 2);

            fireDebug("   Writing Unknwon4... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(BitConverter.GetBytes(Shared.Swap(unknown4)), 0, 8);

            fireDebug("   Writing Padding2... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.WriteByte(padding2);

            fireDebug("   Writing Common Key Index... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.WriteByte(commonKeyIndex);

            fireDebug("   Writing Unknown5... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(unknown5, 0, unknown5.Length);

            fireDebug("   Writing Unknown6... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(unknown6, 0, unknown6.Length);

            fireDebug("   Writing Padding3... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(BitConverter.GetBytes(Shared.Swap(padding3)), 0, 2);

            fireDebug("   Writing Enable Time Limit... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(BitConverter.GetBytes(Shared.Swap(enableTimeLimit)), 0, 4);

            fireDebug("   Writing Time Limit... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(BitConverter.GetBytes(Shared.Swap(timeLimit)), 0, 4);

            fireDebug("   Writing Padding4... (Offset: 0x{0})", ms.Position.ToString("x8").ToUpper());
            ms.Write(padding4, 0, padding4.Length);

            byte[] tik = ms.ToArray();
            ms.Dispose();

            //fake Sign
            if (fakeSign)
            {
                fireDebug("   Fakesigning Ticket...");

                byte[] hash = new byte[20];
                SHA1   s    = SHA1.Create();

                for (ushort i = 0; i < 0xFFFF; i++)
                {
                    byte[] bytes = BitConverter.GetBytes(i);
                    tik[498] = bytes[1]; tik[499] = bytes[0];

                    hash = s.ComputeHash(tik);
                    if (hash[0] == 0x00)
                    {
                        fireDebug("   -> Signed ({0})", i); break;
                    }                                              //Win! It's signed...

                    if (i == 0xFFFF - 1)
                    {
                        fireDebug("    -> Signing Failed..."); throw new Exception("Fakesigning failed...");
                    }
                }

                s.Clear();
            }

            writeStream.Seek(0, SeekOrigin.Begin);
            writeStream.Write(tik, 0, tik.Length);

            fireDebug("Writing Ticket Finished...");
        }
        public void Wrap(FileInfo file)
        {
            //判断是否为需要处理的文本文件
            if (!Regex.IsMatch(file.Name, "_text_ja"))
            {
                Console.WriteLine("跳过文件:{0}", file.FullName);
                return;
            }
            string currentFileName = file.FullName;
            string originFileName  = currentFileName.Remove(currentFileName.Length - file.Extension.Length);//txt对应的原始文件名称

            Console.WriteLine("正在处理:{0}", currentFileName);
            //读取所有的句子
            string[] sentences = File.ReadAllLines(currentFileName);
            sentences = RemoveEmptyString(sentences);

            FileHeader header = new FileHeader();

            header.SentenceCount = (uint)sentences.Length;

            byte[] textData = null;
            using (MemoryStream textMemory = new MemoryStream())
            {
                foreach (string single in sentences)
                {
                    byte[] singleData = Encoding.UTF8.GetBytes(single);
                    textMemory.Write(singleData, 0, singleData.Length);
                    textMemory.WriteByte(0);//以0做结尾
                }

                header.Length = (uint)textMemory.Length;
                uint writeLength = header.Length;
                if (writeLength % 16 != 0)
                {
                    writeLength = (writeLength / 16 + 1) * 16;
                }
                uint space = writeLength - header.Length;
                for (uint i = 0; i < space; i++)//填充FF
                {
                    textMemory.WriteByte(0xff);
                }

                textData = textMemory.ToArray();
            }

            //通过原始文件来生成新的文件
            using (MemoryStream fileMemory = new MemoryStream())
            {
                using (FileStream originReader = new FileStream(originFileName, FileMode.Open, FileAccess.Read))
                {
                    byte[] fixData = new byte[8];
                    originReader.Read(fixData, 0, 8);
                    fileMemory.Write(fixData, 0, 8);

                    //写入译文文本长度
                    fileMemory.Write(DataConverter.BigEndian.GetBytes(header.Length), 0, 4);
                    //写入句子的数量
                    fileMemory.Write(DataConverter.BigEndian.GetBytes(header.SentenceCount), 0, 4);

                    //处理头部索引
                    uint   offset      = DataConverter.BigEndian.GetUInt32(fixData, 4);
                    uint   indexLength = offset - HeaderLength;
                    byte[] hIndex      = new byte[indexLength];
                    originReader.Seek(HeaderLength, SeekOrigin.Begin);
                    originReader.Read(hIndex, 0, hIndex.Length);

                    fileMemory.Write(hIndex, 0, hIndex.Length);     //写入索引

                    fileMemory.Write(textData, 0, textData.Length); //写入文本

                    //处理尾部索引
                    //获取原始文本长度
                    originReader.Seek(8, SeekOrigin.Begin);
                    byte[] bLength = new byte[4];
                    originReader.Read(bLength, 0, 4);
                    uint originLength = DataConverter.BigEndian.GetUInt32(bLength, 0);

                    uint skipLength = originLength + offset;
                    if (skipLength % 16 != 0)
                    {
                        skipLength = (skipLength / 16 + 1) * 16;
                    }

                    originReader.Seek(skipLength, SeekOrigin.Begin);
                    uint   readLength = (uint)(originReader.Length - skipLength);
                    byte[] fIndex     = new byte[readLength];
                    originReader.Read(fIndex, 0, (int)readLength);

                    //写入尾索引
                    fileMemory.Write(fIndex, 0, fIndex.Length);
                }
                //覆盖原始文件
                File.WriteAllBytes(originFileName, fileMemory.ToArray());
            }

            file.Delete();
        }
Example #29
0
 private static void WriteArray(MemoryStream stream, Array a, Hashtable ht, ref int hv, Encoding encoding)
 {
     if (a.Rank == 1)
     {
         int len = a.GetLength(0);
         byte[] alen = Encoding.ASCII.GetBytes(len.ToString());
         int lb = a.GetLowerBound(0);
         int ub = a.GetUpperBound(0);
         stream.WriteByte(__a);
         stream.WriteByte(__Colon);
         stream.Write(alen, 0, alen.Length);
         stream.WriteByte(__Colon);
         stream.WriteByte(__LeftB);
         for (int i = lb; i <= ub; i++)
         {
             WriteInteger(stream, Encoding.ASCII.GetBytes(i.ToString()));
             Serialize(stream, a.GetValue(i), ht, ref hv, encoding);
         }
         stream.WriteByte(__RightB);
     }
     else
     {
         WriteArray(stream, a, new int[] { 0 }, ht, ref hv, encoding);
     }
 }
 public override void WriteByte(byte value)
 {
     stream.WriteByte(value);
 }
Example #31
0
 private static void WriteDouble(MemoryStream stream, byte[] d)
 {
     stream.WriteByte(__d);
     stream.WriteByte(__Colon);
     stream.Write(d, 0, d.Length);
     stream.WriteByte(__Semicolon);
 }
Example #32
0
        private static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Usage: ScriptEncoder.exe <input_file.txt>");
                Console.ReadKey();
                return;
            }

            string fileInput = args[0];

            // Load script file.
            var br = new BinaryReader(new FileStream(fileInput.Replace(".txt", ""), FileMode.Open));

            var scriptBuffer = br.ReadBytes((int)br.BaseStream.Length);

            br.Close();

            // Load translation file.
            var sr    = new StreamReader(fileInput, Encoding.UTF8, true);
            var lines = sr.ReadToEnd().Replace("\r\n", "\n").Split('\n');

            sr.Close();
            if (lines.Length == 0)
            {
                return;
            }

            // headerLength includes MAGIC and @[0x1C].
            int headerLength = 0;

            // Check whether the file is in new format.
            // The most significant thing is the new format have the magic "BurikoCompiledScriptVer1.00\x00".
            // The difference between old and new is that, the old one DOES NOT have the HEADER which has
            // the length discribed at [0x1C] as a DWORD.
            if (
                scriptBuffer.Slice(0, 0x1C)
                .EqualWith(new byte[]
            {
                0x42, 0x75, 0x72, 0x69, 0x6B,
                0x6F, 0x43, 0x6F, 0x6D, 0x70,
                0x69, 0x6C, 0x65, 0x64, 0x53,
                0x63, 0x72, 0x69, 0x70, 0x74,
                0x56, 0x65, 0x72, 0x31, 0x2E,
                0x30, 0x30, 0x00
            }))
            {
                headerLength = 0x1C + BitConverter.ToInt32(scriptBuffer, 0x1C);
            }
            // else headerLength = 0;


            // Get control bytes from original buffer.
            var controlStream =
                new MemoryStream(scriptBuffer.Slice(headerLength, GetSmallestOffset(lines) + headerLength));

            // Let's begin.
            var textStream = new MemoryStream();

            foreach (var line in lines)
            {
                if (String.IsNullOrEmpty(line))
                {
                    continue;
                }

                var info = GetLineInfo(line);
                controlStream.WriteInt32(info[0], (int)(controlStream.Length + textStream.Length));
                textStream.WriteBytes(Encoding.GetEncoding(936).GetBytes(GetText(line)));
                textStream.WriteByte(0x00);
            }

            // Build new script file.
            var bw = new BinaryWriter(new FileStream(fileInput + ".new", FileMode.Create));

            // Write HEADER.
            if (headerLength != 0)
            {
                bw.Write(scriptBuffer.Slice(0, headerLength));
            }
            // Control bytes.
            bw.Write(controlStream.ToArray());
            // Text bytes.
            bw.Write(textStream.ToArray());
            bw.Close();
        }
Example #33
0
 private static void WriteObject(MemoryStream stream, object obj, Hashtable ht, ref int hv, Encoding encoding)
 {
     Type type = obj.GetType();
     if (type.IsSerializable)
     {
         byte[] typename = encoding.GetBytes(type.Name);
         byte[] typenamelen = Encoding.ASCII.GetBytes(typename.Length.ToString());
         if (obj is Serializable)
         {
             byte[] cs = ((Serializable)obj).Serialize();
             byte[] cslen = Encoding.ASCII.GetBytes(cs.Length.ToString());
             stream.WriteByte(__C);
             stream.WriteByte(__Colon);
             stream.Write(typenamelen, 0, typenamelen.Length);
             stream.WriteByte(__Colon);
             stream.WriteByte(__Quote);
             stream.Write(typename, 0, typename.Length);
             stream.WriteByte(__Quote);
             stream.WriteByte(__Colon);
             stream.Write(cslen, 0, cslen.Length);
             stream.WriteByte(__Colon);
             stream.WriteByte(__LeftB);
             stream.Write(cs, 0, cs.Length);
             stream.WriteByte(__RightB);
         }
         else
         {
             MethodInfo __sleep = null;
             try
             {
                 __sleep = type.GetMethod("__sleep", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.IgnoreCase, null, new Type[0], new ParameterModifier[0]);
             }
             catch { }
             int fl = 0;
             FieldInfo[] f;
             if (__sleep != null)
             {
                 string[] fns = (string[])__sleep.Invoke(obj, null);
                 f = new FieldInfo[fns.Length];
                 for (int i = 0, len = f.Length; i < len; i++)
                 {
                     f[i] = type.GetField(fns[i], BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
                 }
             }
             else
             {
                 f = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
             }
             for (int i = 0, len = f.Length; i < len; i++)
             {
                 if (f[i] != null && !(f[i].IsNotSerialized || f[i].IsInitOnly || f[i].IsLiteral))
                 {
                     fl++;
                 }
             }
             byte[] flen = Encoding.ASCII.GetBytes(fl.ToString());
             stream.WriteByte(__O);
             stream.WriteByte(__Colon);
             stream.Write(typenamelen, 0, typenamelen.Length);
             stream.WriteByte(__Colon);
             stream.WriteByte(__Quote);
             stream.Write(typename, 0, typename.Length);
             stream.WriteByte(__Quote);
             stream.WriteByte(__Colon);
             stream.Write(flen, 0, flen.Length);
             stream.WriteByte(__Colon);
             stream.WriteByte(__LeftB);
             for (int i = 0, len = f.Length; i < len; i++)
             {
                 if (f[i] != null && !(f[i].IsNotSerialized || f[i].IsInitOnly || f[i].IsLiteral))
                 {
                     if (f[i].IsPublic)
                     {
                         WriteString(stream, encoding.GetBytes(f[i].Name));
                     }
                     else if (f[i].IsPrivate)
                     {
                         WriteString(stream, encoding.GetBytes("\0" + f[i].DeclaringType.Name + "\0" + f[i].Name));
                     }
                     else
                     {
                         WriteString(stream, encoding.GetBytes("\0*\0" + f[i].Name));
                     }
                     Serialize(stream, f[i].GetValue(obj), ht, ref hv, encoding);
                 }
             }
             stream.WriteByte(__RightB);
         }
     }
     else
     {
         WriteNull(stream);
     }
 }
        public async Task GetAsync_CancelPendingRequests_DoesntCancelReadAsyncOnResponseStream(CancellationMode mode, bool copyToAsync)
        {
            if (IsWinHttpHandler && UseVersion >= HttpVersion20.Value)
            {
                return;
            }

            using (HttpClient client = CreateHttpClient())
            {
                client.Timeout = Timeout.InfiniteTimeSpan;

                await LoopbackServerFactory.CreateServerAsync(async (server, url) =>
                {
                    var clientReadSomeBody = new TaskCompletionSource <bool>();
                    var clientFinished     = new TaskCompletionSource <bool>();

                    var responseContentSegment = new string('s', 3000);
                    int responseSegments       = 4;
                    int contentLength          = responseContentSegment.Length * responseSegments;

                    Task serverTask = server.AcceptConnectionAsync(async connection =>
                    {
                        await connection.ReadRequestDataAsync();
                        await connection.SendResponseAsync(HttpStatusCode.OK, headers: new HttpHeaderData[] { new HttpHeaderData("Content-Length", contentLength.ToString()) }, isFinal: false);
                        for (int i = 0; i < responseSegments; i++)
                        {
                            await connection.SendResponseBodyAsync(responseContentSegment, isFinal: i == responseSegments - 1);
                            if (i == 0)
                            {
                                await clientReadSomeBody.Task;
                            }
                        }

                        await clientFinished.Task;
                    });


                    using (HttpResponseMessage resp = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
                        using (Stream respStream = await resp.Content.ReadAsStreamAsync(TestAsync))
                        {
                            var result = new MemoryStream();
                            int b      = respStream.ReadByte();
                            Assert.NotEqual(-1, b);
                            result.WriteByte((byte)b);

                            Cancel(mode, client, null); // should not cancel the operation, as using ResponseHeadersRead
                            clientReadSomeBody.SetResult(true);

                            if (copyToAsync)
                            {
                                await respStream.CopyToAsync(result, 10, new CancellationTokenSource().Token);
                            }
                            else
                            {
                                byte[] buffer = new byte[10];
                                int bytesRead;
                                while ((bytesRead = await respStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                                {
                                    result.Write(buffer, 0, bytesRead);
                                }
                            }

                            Assert.Equal(contentLength, result.Length);
                        }

                    clientFinished.SetResult(true);
                    await serverTask;
                });
            }
        }
 public bool runTest()
 {
     Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
     int iCountErrors = 0;
     int iCountTestcases = 0;
     String strLoc = "Loc_000oo";
     String strValue = String.Empty;
     try
     {
         MemoryStream ms2;
         Int32 ii = 0;
         Byte[] bytArr;
         Int32 i32;
         bytArr = new Byte[] {
                                 Byte.MinValue
                                 ,Byte.MaxValue
                                 ,100
                                 ,Byte.MaxValue-100
                             };
         strLoc = "Loc_398yc";
         ms2 = new MemoryStream();
         for(ii = 0 ; ii < bytArr.Length ; ii++)
             ms2.WriteByte(bytArr[ii]);
         ms2.Flush();
         ms2.Position = 0;
         ms2.Flush();
         for(ii = 0 ; ii < bytArr.Length ; ii++) 
         {
             iCountTestcases++;
             if((i32 = ms2.ReadByte()) != bytArr[ii]) 
             {
                 iCountErrors++;
                 printerr( "Error_38yv8_"+ii+"! Expected=="+bytArr[ii]+", got=="+i32);
             }
         }
         i32 = ms2.ReadByte();
         if(i32 != -1) 
         {
             iCountErrors++;
             printerr( "Error_238v8! -1 return expected, i32=="+i32);
         }
         ms2.Position = 0;
         for(ii = 0 ; ii < bytArr.Length; ii++)
             ms2.WriteByte(bytArr[ii]);
     } 
     catch (Exception exc_general ) 
     {
         ++iCountErrors;
         Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general=="+exc_general.ToString());
     }
     if ( iCountErrors == 0 )
     {
         Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
         return true;
     }
     else
     {
         Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
         return false;
     }
 }
Example #36
0
 protected void WriteByte(byte value)
 {
     _stream.WriteByte(value);
 }
Example #37
0
        /// <summary>
        /// 将RSA中的密钥对转换成PEM格式,usePKCS8=false时返回PKCS#1格式,否则返回PKCS#8格式,如果convertToPublic含私钥的RSA将只返回公钥,仅含公钥的RSA不受影响
        /// </summary>
        public string ToPEM(bool convertToPublic, bool usePKCS8)
        {
            var ms = new MemoryStream();
            //写入一个长度字节码
            Action <int> writeLenByte = len =>
            {
                if (len < 0x80)
                {
                    ms.WriteByte((byte)len);
                }
                else if (len <= 0xff)
                {
                    ms.WriteByte(0x81);
                    ms.WriteByte((byte)len);
                }
                else
                {
                    ms.WriteByte(0x82);
                    ms.WriteByte((byte)(len >> 8 & 0xff));
                    ms.WriteByte((byte)(len & 0xff));
                }
            };
            //写入一块数据
            Action <byte[]> writeBlock = byts =>
            {
                var addZero = (byts[0] >> 4) >= 0x8;
                ms.WriteByte(0x02);
                var len = byts.Length + (addZero ? 1 : 0);
                writeLenByte(len);

                if (addZero)
                {
                    ms.WriteByte(0x00);
                }

                ms.Write(byts, 0, byts.Length);
            };
            //根据后续内容长度写入长度数据
            Func <int, byte[], byte[]> writeLen = (index, byts) =>
            {
                var len = byts.Length - index;

                ms.SetLength(0);
                ms.Write(byts, 0, index);
                writeLenByte(len);
                ms.Write(byts, index, len);

                return(ms.ToArray());
            };
            Action <MemoryStream, byte[]> writeAll = (stream, byts) =>
            {
                stream.Write(byts, 0, byts.Length);
            };
            Func <string, int, string> TextBreak = (text, line) =>
            {
                var idx = 0;
                var len = text.Length;
                var str = new StringBuilder();
                while (idx < len)
                {
                    if (idx > 0)
                    {
                        str.Append('\n');
                    }

                    str.Append(idx + line >= len ? text.Substring(idx) : text.Substring(idx, line));
                    idx += line;
                }

                return(str.ToString());
            };


            if (KeyD == null || convertToPublic)
            {
                //生成公钥
                //写入总字节数,不含本段长度,额外需要24字节的头,后续计算好填入
                ms.WriteByte(0x30);
                var index1 = (int)ms.Length;

                //固定内容
                writeAll(ms, SeqOid);

                //从0x00开始的后续长度
                ms.WriteByte(0x03);
                var index2 = (int)ms.Length;
                ms.WriteByte(0x00);

                //后续内容长度
                ms.WriteByte(0x30);
                var index3 = (int)ms.Length;

                //写入Modulus
                writeBlock(KeyModulus);

                //写入Exponent
                writeBlock(KeyExponent);

                //计算空缺的长度
                var bytes = ms.ToArray();
                bytes = writeLen(index3, bytes);
                bytes = writeLen(index2, bytes);
                bytes = writeLen(index1, bytes);
                return("-----BEGIN PUBLIC KEY-----\n" + TextBreak(Convert.ToBase64String(bytes), 64) + "\n-----END PUBLIC KEY-----");
            }
            else
            {
                /****生成私钥****/

                //写入总字节数,后续写入
                ms.WriteByte(0x30);
                int index1 = (int)ms.Length;

                //写入版本号
                writeAll(ms, Ver);

                //PKCS8 多一段数据
                int index2 = -1, index3 = -1;
                if (usePKCS8)
                {
                    //固定内容
                    writeAll(ms, SeqOid);

                    //后续内容长度
                    ms.WriteByte(0x04);
                    index2 = (int)ms.Length;

                    //后续内容长度
                    ms.WriteByte(0x30);
                    index3 = (int)ms.Length;

                    //写入版本号
                    writeAll(ms, Ver);
                }

                //写入数据
                writeBlock(KeyModulus);
                writeBlock(KeyExponent);
                writeBlock(KeyD);
                writeBlock(ValP);
                writeBlock(ValQ);
                writeBlock(ValDp);
                writeBlock(ValDq);
                writeBlock(ValInverseQ);


                //计算空缺的长度
                var byts = ms.ToArray();

                if (index2 != -1)
                {
                    byts = writeLen(index3, byts);
                    byts = writeLen(index2, byts);
                }

                byts = writeLen(index1, byts);


                var flag = " PRIVATE KEY";
                if (!usePKCS8)
                {
                    flag = " RSA" + flag;
                }

                return("-----BEGIN" + flag + "-----\n" + TextBreak(Convert.ToBase64String(byts), 64) + "\n-----END" + flag + "-----");
            }
        }
Example #38
0
        private static int readJPGData(Stream stream, MemoryStream ms)
        {
            var bytesread = 0;

            // start header
            byte ch3 = (byte)stream.ReadByte();

            bytesread++;
            if (ch3 == 0xff)
            {
                byte ch4 = (byte)stream.ReadByte();
                bytesread++;
                if (ch4 == 0xd8)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.WriteByte(ch3);
                    ms.WriteByte(ch4);
                    int last = 0;
                    do
                    {
                        int datach = stream.ReadByte();
                        bytesread++;
                        if (datach < 0)
                        {
                            break;
                        }

                        ms.WriteByte((byte)datach);

                        if (last == 0xff)
                        {
                            if (datach == 0xd9)
                            {
                                break;
                            }
                        }

                        last = datach;
                    } while (true);

                    ms.Seek(0, SeekOrigin.Begin);
                    try
                    {
                        var temp = Image.FromStream(ms);

                        //File.WriteAllBytes(tempno + ".bmp", ms.ToArray());

                        _onNewImage?.Invoke(null, temp);

                        tempno++;
                        persecond++;

                        if (lastsecond.Second != DateTime.Now.Second)
                        {
                            Console.WriteLine("image {0}x{1} size {2} miss {3} ps {4}",
                                              temp.Width,
                                              temp.Height, 0, miss, persecond);
                            persecond  = 0;
                            lastsecond = DateTime.Now;
                            miss       = 0;
                        }
                    }
                    catch
                    {
                    }
                }
                else
                {
                    miss++;
                }
            }
            else
            {
                miss++;
            }

            return(bytesread);
        }
Example #39
0
    public static string UrlDecode(byte [] bytes, int offset, int count, Encoding e)
    {
        if (bytes == null)
                return null;
            if (count == 0)
                return string.Empty;
            StringBuilder output = new StringBuilder ();
            MemoryStream acc = new MemoryStream ();

            int end = count + offset;
            int xchar;
            for (int i = offset; i < end; i++) {
                if (bytes [i] == '%' && i + 2 < count && bytes [i + 1] != '%') {
                    if (bytes [i + 1] == (byte) 'u' && i + 5 < end) {
                        if (acc.Length > 0) {
                            output.Append (GetChars (acc, e));
                            acc.SetLength (0);
                        }
                        xchar = GetChar (bytes, i + 2, 4);
                        if (xchar != -1) {
                            output.Append ((char) xchar);
                            i += 5;
                            continue;
                        }
                    } else if ((xchar = GetChar (bytes, i + 1, 2)) != -1) {
                        acc.WriteByte ((byte) xchar);
                        i += 2;
                        continue;
                    }
                }

                if (acc.Length > 0) {
                    output.Append (GetChars (acc, e));
                    acc.SetLength (0);
                }

                if (bytes [i] == '+') {
                    output.Append (' ');
                } else {
                    output.Append ((char) bytes [i]);
                }
            }

            if (acc.Length > 0) {
                output.Append (GetChars (acc, e));
            }

            acc = null;
            return output.ToString ();
    }
Example #40
0
 public override void WriteByte(byte value)
 {
     cache.WriteByte(value);
 }
Example #41
0
    public override void serialize(MemoryStream stream)
    {
        base.serialize(stream);

        stream.WriteByte(sex);
    }
Example #42
0
 private static void _WriteCRLFToStream(MemoryStream oMS)
 {
     oMS.WriteByte(13);
     oMS.WriteByte(10);
 }
Example #43
0
        public void CheckInvalidFileEntry()
        {
            // Incorrect entry length
            {
                var stream = new MemoryStream();
                stream.Write(ArArchiveFile.Magic);
                stream.Write(new byte[] { (byte)'a', (byte)'b' });
                stream.Position = 0;

                Assert.False(ArArchiveFile.TryRead(stream, ArArchiveKind.GNU, out _, out var diagnostics));
                ExpectDiagnostics(diagnostics, DiagnosticId.AR_ERR_InvalidFileEntryLength);
            }

            // Input invalid non-numeric characters into decimal/octal fields in file entry
            {
                var offsets = new int[]
                {
                    ArFile.FieldTimestampOffset,
                    ArFile.FieldOwnerIdOffset,
                    ArFile.FieldGroupIdOffset,
                    ArFile.FieldFileModeOffset,
                    ArFile.FieldFileSizeOffset,
                    ArFile.FieldEndCharactersOffset
                };
                foreach (var offset in offsets)
                {
                    var stream = new MemoryStream();
                    stream.Write(ArArchiveFile.Magic);

                    var entry = new Span <byte>(new byte[ArFile.FileEntrySizeInBytes]);
                    entry.Fill((byte)' ');
                    entry[offset] = (byte)'a';
                    stream.Write(entry);

                    stream.Position = 0;

                    Assert.False(ArArchiveFile.TryRead(stream, ArArchiveKind.GNU, out _, out var diagnostics));
                    ExpectDiagnostics(diagnostics, DiagnosticId.AR_ERR_InvalidCharacterFoundInFileEntry);
                }
            }

            // Input name with `/`
            {
                var stream = new MemoryStream();
                stream.Write(ArArchiveFile.Magic);
                var entry = new Span <byte>(new byte[ArFile.FileEntrySizeInBytes]);
                entry.Fill((byte)' ');
                entry[0] = (byte)'a';
                entry[1] = (byte)'b';
                entry[2] = (byte)'/';
                entry[3] = (byte)'c';

                entry[ArFile.FieldEndCharactersOffset]     = (byte)'`';
                entry[ArFile.FieldEndCharactersOffset + 1] = (byte)'\n';

                stream.Write(entry);

                stream.Position = 0;

                Assert.False(ArArchiveFile.TryRead(stream, ArArchiveKind.GNU, out _, out var diagnostics));
                ExpectDiagnostics(diagnostics, DiagnosticId.AR_ERR_InvalidCharacterInFileEntryName);
            }

            // Input length of content
            {
                var stream = new MemoryStream();
                stream.Write(ArArchiveFile.Magic);
                var entry = new Span <byte>(new byte[ArFile.FileEntrySizeInBytes]);
                entry.Fill((byte)' ');
                entry[0] = (byte)'a';
                entry[ArFile.FieldFileSizeOffset]          = (byte)'2';
                entry[ArFile.FieldEndCharactersOffset]     = (byte)'`';
                entry[ArFile.FieldEndCharactersOffset + 1] = (byte)'\n';

                stream.Write(entry);

                var continuePosition = stream.Position;

                stream.Position = 0;

                Assert.False(ArArchiveFile.TryRead(stream, ArArchiveKind.GNU, out _, out var diagnostics));
                ExpectDiagnostics(diagnostics, DiagnosticId.AR_ERR_UnexpectedEndOfFile);

                stream.Position = continuePosition;

                stream.WriteByte(0);
                stream.WriteByte(1);

                stream.Position = 0;

                // Check that we can actually read the content

                var result = ArArchiveFile.TryRead(stream, ArArchiveKind.GNU, out var arFile, out diagnostics);
                ExpectNoDiagnostics(diagnostics);
                Assert.True(result, $"Error while reading file: {diagnostics}");
                Assert.AreEqual(1, arFile.Files.Count, "Invalid number of file entries found");
                Assert.AreEqual("a", arFile.Files[0].Name, "Invalid name of file entry[0] found");
                Assert.AreEqual(2, arFile.Files[0].Size, "Invalid size of file entry[0] found");
                Assert.IsInstanceOf <ArBinaryFile>(arFile.Files[0], "Invalid instance of of file entry[0] ");

                var fileStream = ((ArBinaryFile)arFile.Files[0]).Stream;
                var read       = new byte[]
                {
                    (byte)fileStream.ReadByte(),
                    (byte)fileStream.ReadByte()
                };
                Assert.AreEqual(new byte[] { 0, 1 }, read, "Invalid content of of file entry[0] ");

                Assert.Null(arFile.SymbolTable, "Invalid non-null symbol table found");
            }

            // Input length of content
            {
                var stream = new MemoryStream();
                stream.Write(ArArchiveFile.Magic);
                var entry = new Span <byte>(new byte[ArFile.FileEntrySizeInBytes]);
                entry.Fill((byte)' ');
                entry[0] = (byte)'a';
                entry[ArFile.FieldFileSizeOffset]          = (byte)'1';
                entry[ArFile.FieldEndCharactersOffset]     = (byte)'`';
                entry[ArFile.FieldEndCharactersOffset + 1] = (byte)'\n';

                stream.Write(entry);
                stream.WriteByte(0);

                var continuePosition = stream.Position;
                stream.Position = 0;

                Assert.False(ArArchiveFile.TryRead(stream, ArArchiveKind.GNU, out _, out var diagnostics));
                ExpectDiagnostics(diagnostics, DiagnosticId.AR_ERR_UnexpectedEndOfFile);

                stream.Position = continuePosition;
                stream.WriteByte(0);
                stream.Position = 0;

                Assert.False(ArArchiveFile.TryRead(stream, ArArchiveKind.GNU, out _, out diagnostics));
                ExpectDiagnostics(diagnostics, DiagnosticId.AR_ERR_ExpectingNewLineCharacter);

                stream.Position = continuePosition;
                stream.WriteByte((byte)'\n');
                stream.Position = 0;

                Assert.True(ArArchiveFile.TryRead(stream, ArArchiveKind.GNU, out _, out diagnostics));
                ExpectNoDiagnostics(diagnostics);
            }
        }
Example #44
0
        private bool DecodeWindow()
        {
            int num = delta.ReadByte();

            if (num == -1)
            {
                return(false);
            }
            int  num2 = -1;
            bool flag = (num & 4) == 4;

            num &= 0xFB;
            Stream stream;

            switch (num & 3)
            {
            case 0:
                stream = null;
                break;

            case 1:
                if (original == null)
                {
                    throw new VcdiffFormatException("Source stream requested by delta but not provided by caller.");
                }
                stream = original;
                break;

            case 2:
                stream = output;
                num2   = (int)output.Position;
                break;

            case 3:
                throw new VcdiffFormatException("Invalid window indicator - bits 0 and 1 both set.");

            default:
                throw new VcdiffFormatException("Invalid window indicator - bits 3-7 not all zero.");
            }
            byte[] array = null;
            int    num3  = 0;

            if (stream != null)
            {
                num3 = IOHelper.ReadBigEndian7BitEncodedInt(delta);
                int num4 = IOHelper.ReadBigEndian7BitEncodedInt(delta);
                stream.Position = num4;
                array           = IOHelper.CheckedReadBytes(stream, num3);
                if (num2 != -1)
                {
                    stream.Position = num2;
                }
            }
            IOHelper.ReadBigEndian7BitEncodedInt(delta);
            int num5 = IOHelper.ReadBigEndian7BitEncodedInt(delta);

            byte[]       array2       = new byte[num5];
            MemoryStream memoryStream = new MemoryStream(array2, writable: true);

            if (IOHelper.CheckedReadByte(delta) != 0)
            {
                throw new VcdiffFormatException("VcdiffDecoder is unable to handle compressed delta sections.");
            }
            int size  = IOHelper.ReadBigEndian7BitEncodedInt(delta);
            int size2 = IOHelper.ReadBigEndian7BitEncodedInt(delta);
            int size3 = IOHelper.ReadBigEndian7BitEncodedInt(delta);

            if (flag)
            {
                IOHelper.CheckedReadBytes(delta, 4);
            }
            byte[]       array3        = IOHelper.CheckedReadBytes(delta, size);
            byte[]       buffer        = IOHelper.CheckedReadBytes(delta, size2);
            byte[]       addresses     = IOHelper.CheckedReadBytes(delta, size3);
            int          num6          = 0;
            MemoryStream memoryStream2 = new MemoryStream(buffer, writable: false);

            cache.Reset(addresses);
            while (true)
            {
                int num7 = memoryStream2.ReadByte();
                if (num7 == -1)
                {
                    break;
                }
                for (int i = 0; i < 2; i++)
                {
                    Instruction instruction = codeTable[num7, i];
                    int         num8        = instruction.Size;
                    if (num8 == 0 && instruction.Type != 0)
                    {
                        num8 = IOHelper.ReadBigEndian7BitEncodedInt(memoryStream2);
                    }
                    switch (instruction.Type)
                    {
                    case InstructionType.Add:
                        memoryStream.Write(array3, num6, num8);
                        num6 += num8;
                        break;

                    case InstructionType.Copy:
                    {
                        int num9 = cache.DecodeAddress((int)memoryStream.Position + num3, instruction.Mode);
                        if (array != null && num9 < array.Length)
                        {
                            memoryStream.Write(array, num9, num8);
                            break;
                        }
                        num9 -= num3;
                        if (num9 + num8 < memoryStream.Position)
                        {
                            memoryStream.Write(array2, num9, num8);
                            break;
                        }
                        for (int k = 0; k < num8; k++)
                        {
                            memoryStream.WriteByte(array2[num9++]);
                        }
                        break;
                    }

                    case InstructionType.Run:
                    {
                        byte value = array3[num6++];
                        for (int j = 0; j < num8; j++)
                        {
                            memoryStream.WriteByte(value);
                        }
                        break;
                    }

                    default:
                        throw new VcdiffFormatException("Invalid instruction type found.");

                    case InstructionType.NoOp:
                        break;
                    }
                }
            }
            output.Write(array2, 0, num5);
            adler.Update(array2, 0, num5);
            return(true);
        }
Example #45
0
 private static void WritePointRef(MemoryStream stream, byte[] p)
 {
     stream.WriteByte(__R);
     stream.WriteByte(__Colon);
     stream.Write(p, 0, p.Length);
     stream.WriteByte(__Semicolon);
 }
Example #46
0
 public void Serialize(MemoryStream ms)
 {
     ms.WriteByte((byte)ClientMessageTypes.BombSet);
     Serializer.SerializeWithLengthPrefix(ms, this, PrefixStyle.Base128);
 }
Example #47
0
 private static void WriteString(MemoryStream stream, byte[] s)
 {
     byte[] slen = Encoding.ASCII.GetBytes(s.Length.ToString());
     stream.WriteByte(__s);
     stream.WriteByte(__Colon);
     stream.Write(slen, 0, slen.Length);
     stream.WriteByte(__Colon);
     stream.WriteByte(__Quote);
     stream.Write(s, 0, s.Length);
     stream.WriteByte(__Quote);
     stream.WriteByte(__Semicolon);
 }
Example #48
0
        private bool WriteArrayText(NpgsqlNativeTypeInfo TypeInfo, Array ar, MemoryStream array, Boolean forExtendedQuery, NativeToBackendTypeConverterOptions options)
        {
            bool writtenSomething = false;
            //we need to know the size of each dimension.
            int        c         = ar.Rank;
            List <int> lengths   = new List <int>(c);
            bool       firstItem = true;

            do
            {
                lengths.Add(ar.GetLength(--c));
            }while (c != 0);

            //c is now zero. Might as well reuse it!

            foreach (object item in ar)
            {
                if (firstItem)
                {
                    firstItem = false;
                }
                else
                {
                    array.WriteByte((byte)ASCIIBytes.Comma);
                }

                //to work out how many [ characters we need we need to work where we are compared to the dimensions.
                //Say we are at position 24 in a 3 * 4 * 5 array.
                //We're at the end of a row as 24 % 3 == 0 so write one [ for that.
                //We're at the end of a square as 24 % (3 * 4) == 24 % (12) == 0 so write one [ for that.
                //We're not at the end of a cube as 24 % (3 * 4 * 5) == 24 % (30) != 0, so we're finished for that pass.
                int curlength = 1;
                foreach (int lengthTest in lengths)
                {
                    if (c % (curlength *= lengthTest) == 0)
                    {
                        array.WriteByte((byte)ASCIIBytes.BraceCurlyLeft);
                    }
                    else
                    {
                        break;
                    }
                }

                //Write whatever the element is.
                writtenSomething |= WriteItemText(TypeInfo, item, array, forExtendedQuery, options);
                ++c; //up our counter for knowing when to write [ and ]

                //same logic as above for writing [ this time writing ]
                curlength = 1;
                foreach (int lengthTest in lengths)
                {
                    if (c % (curlength *= lengthTest) == 0)
                    {
                        array.WriteByte((byte)ASCIIBytes.BraceCurlyRight);
                    }
                    else
                    {
                        break;
                    }
                }
            }

            return(writtenSomething);
        }
Example #49
0
 private static void WriteArray(MemoryStream stream, Array a, int[] indices, Hashtable ht, ref int hv, Encoding encoding)
 {
     int n = indices.Length;
     int dimension = n - 1;
     int[] temp = new int[n + 1];
     indices.CopyTo(temp, 0);
     int len = a.GetLength(dimension);
     byte[] alen = Encoding.ASCII.GetBytes(len.ToString());
     int lb = a.GetLowerBound(dimension);
     int ub = a.GetUpperBound(dimension);
     stream.WriteByte(__a);
     stream.WriteByte(__Colon);
     stream.Write(alen, 0, alen.Length);
     stream.WriteByte(__Colon);
     stream.WriteByte(__LeftB);
     for (int i = lb; i <= ub; i++)
     {
         WriteInteger(stream, Encoding.ASCII.GetBytes(i.ToString()));
         if (a.Rank == n)
         {
             indices[n - 1] = i;
             Serialize(stream, a.GetValue(indices), ht, ref hv, encoding);
         }
         else
         {
             temp[n - 1] = i;
             WriteArray(stream, a, temp, ht, ref hv, encoding);
         }
     }
     stream.WriteByte(__RightB);
 }
        /// <summary>
        /// 将数据进行 XX 编码。
        /// </summary>
        /// <param name="bytes">待编码数据的字节数组。</param>
        /// <returns></returns>
        public static byte[] Encode(byte[] bytes)
        {
            Guard.CheckArgumentNotNull(bytes, nameof(bytes));

            int sidx    = 0;
            int lineLen = 45;

            byte[] nl = Encoding.ASCII.GetBytes(Environment.NewLine);

            byte A, B, C;

            using (MemoryStream input = new MemoryStream(bytes))
                using (MemoryStream output = new MemoryStream())
                {
                    long len = input.Length;
                    if (len == 0)
                    {
                        return(new byte[0]);
                    }

                    while (sidx + lineLen < len)
                    {
                        output.WriteByte(XXEncMap[lineLen]);

                        for (int end = sidx + lineLen; sidx < end; sidx += 3)
                        {
                            A = (byte)input.ReadByte();
                            B = (byte)input.ReadByte();
                            C = (byte)input.ReadByte();

                            output.WriteByte(XXEncMap[(A >> 2) & 63]);
                            output.WriteByte(XXEncMap[(B >> 4) & 15 | (A << 4) & 63]);
                            output.WriteByte(XXEncMap[(C >> 6) & 3 | (B << 2) & 63]);
                            output.WriteByte(XXEncMap[C & 63]);
                        }

                        output.WriteBytes(nl);
                    }

                    output.WriteByte(XXEncMap[len - sidx]);

                    while (sidx + 2 < len)
                    {
                        A = (byte)input.ReadByte();
                        B = (byte)input.ReadByte();
                        C = (byte)input.ReadByte();

                        output.WriteByte(XXEncMap[(A >> 2) & 63]);
                        output.WriteByte(XXEncMap[(B >> 4) & 15 | (A << 4) & 63]);
                        output.WriteByte(XXEncMap[(C >> 6) & 3 | (B << 2) & 63]);
                        output.WriteByte(XXEncMap[C & 63]);
                        sidx += 3;
                    }

                    if (sidx < len - 1)
                    {
                        A = (byte)input.ReadByte();
                        B = (byte)input.ReadByte();

                        output.WriteByte(XXEncMap[(A >> 2) & 63]);
                        output.WriteByte(XXEncMap[(B >> 4) & 15 | (A << 4) & 63]);
                        output.WriteByte(XXEncMap[(B << 2) & 63]);
                        output.WriteByte(XXEncMap[0]);
                    }
                    else if (sidx < len)
                    {
                        A = (byte)input.ReadByte();

                        output.WriteByte(XXEncMap[(A >> 2) & 63]);
                        output.WriteByte(XXEncMap[(A << 4) & 63]);
                        output.WriteByte(XXEncMap[0]);
                        output.WriteByte(XXEncMap[0]);
                    }

                    return(output.ToArray());
                }
        }
Example #51
0
 private static void WriteBoolean(MemoryStream stream, byte b)
 {
     stream.WriteByte(__b);
     stream.WriteByte(__Colon);
     stream.WriteByte(b);
     stream.WriteByte(__Semicolon);
 }
        /// <summary>
        /// 将数据进行 XX 解码。
        /// </summary>
        /// <param name="encodedBytes">待解码数据的字节数组。</param>
        /// <returns></returns>
        public static byte[] Decode(byte[] encodedBytes)
        {
            Guard.CheckArgumentNotNull(encodedBytes, nameof(encodedBytes));

            using (MemoryStream input = new MemoryStream(encodedBytes))
                using (MemoryStream output = new MemoryStream())
                {
                    long len = input.Length;
                    if (len == 0)
                    {
                        return(new byte[0]);
                    }

                    long didx     = 0;
                    int  nextByte = input.ReadByte();
                    while (nextByte >= 0)
                    {
                        int lineLen = XXDecMap[nextByte];

                        long end = didx + lineLen;
                        byte A, B, C, D;
                        if (end > 2)
                        {
                            while (didx < end - 2)
                            {
                                A = XXDecMap[input.ReadByte()];
                                B = XXDecMap[input.ReadByte()];
                                C = XXDecMap[input.ReadByte()];
                                D = XXDecMap[input.ReadByte()];

                                output.WriteByte((byte)(((A << 2) & 255) | ((B >> 4) & 3)));
                                output.WriteByte((byte)(((B << 4) & 255) | ((C >> 2) & 15)));
                                output.WriteByte((byte)(((C << 6) & 255) | (D & 63)));
                                didx += 3;
                            }
                        }

                        if (didx < end)
                        {
                            A = XXDecMap[input.ReadByte()];
                            B = XXDecMap[input.ReadByte()];
                            output.WriteByte((byte)(((A << 2) & 255) | ((B >> 4) & 3)));
                            didx++;

                            if (didx < end)
                            {
                                C = XXDecMap[input.ReadByte()];
                                output.WriteByte((byte)(((B << 4) & 255) | ((C >> 2) & 15)));
                                didx++;
                            }
                        }

                        do
                        {
                            nextByte = input.ReadByte();
                        }while (nextByte >= 0 && nextByte != '\n' && nextByte != '\r');

                        do
                        {
                            nextByte = input.ReadByte();
                        }while (nextByte >= 0 && (nextByte == '\n' || nextByte == '\r'));
                    }

                    return(output.ToArray());
                }
        }
Example #53
0
 private static void WriteHashtable(MemoryStream stream, Hashtable h, Hashtable ht, ref int hv, Encoding encoding)
 {
     int len = h.Count;
     byte[] hlen = Encoding.ASCII.GetBytes(len.ToString());
     stream.WriteByte(__a);
     stream.WriteByte(__Colon);
     stream.Write(hlen, 0, hlen.Length);
     stream.WriteByte(__Colon);
     stream.WriteByte(__LeftB);
     foreach (DictionaryEntry entry in h)
     {
         if ((entry.Key is Byte) || (entry.Key is SByte) || (entry.Key is Int16) || (entry.Key is UInt16) || (entry.Key is Int32))
         {
             WriteInteger(stream, Encoding.ASCII.GetBytes(entry.Key.ToString()));
         }
         else if (entry.Key is Boolean)
         {
             WriteInteger(stream, new byte[] { ((Boolean)entry.Key) ? __1 : __0 });
         }
         else
         {
             WriteString(stream, encoding.GetBytes(entry.Key.ToString()));
         }
         Serialize(stream, entry.Value, ht, ref hv, encoding);
     }
     stream.WriteByte(__RightB);
 }
    /// <summary>
    /// compresses uncompressed data to compressed data in byte array
    /// </summary>
    /// <returns></returns>
    public byte[] RLECompress()
    {
        // stores non repeatable data
        MemoryStream NoRepeat = new MemoryStream();

        // repeat counter
        int _RL = 1;

        // 2 consecutive bytes to compare
        byte preByte = 0, postByte = 0;

        // iterate through the uncompressed bytes
        for (int i = 0; i < _UnCompressed.Length - 1; i++)
        {
            // get 2 consecutive bytes
            preByte = _UnCompressed[i];
            postByte = _UnCompressed[i + 1];

            // if both are same there is scope for repitition
            if (preByte == postByte)
            {
                // but flush the non repeatable data (if present) to compressed stream 
                if (NoRepeat.Length > 0) WriteNoRepeater(NoRepeat); 

                // increase repeat count
                _RL++;
                
                // if repeat count reaches limit of repeat i.e. 128 
                // write the repeat data and reset the repeat counter
                if (_RL > 128) _RL = WriteRunLength(_RL-1,preByte); 

            }
            else
            {
                // when consecutive bytes do not match

                // store non-repeatable data
                if (_RL == 1) NoRepeat.WriteByte(preByte);

                // write repeated length and byte (if present ) to output stream
                if (_RL > 1)  _RL = WriteRunLength(_RL, preByte);
                
                // write non repeatable data to out put stream if the length reaches limit
                if (NoRepeat.Length == 128) WriteNoRepeater(NoRepeat); 
            }
        }
  
        // at the end of iteration 
        // take care of the last byte

        // if repeated 
        if (_RL > 1) 
        {
            // write run length and byte (if present ) to output stream
            _RL = WriteRunLength(_RL, preByte); 
        }
        else
        {
            // if non repeated byte is left behind
            // write non repeatable data to output stream 
            NoRepeat.WriteByte(postByte);
            WriteNoRepeater(NoRepeat);
        }

        
        // wrote EOD
        _Compressed.WriteByte((byte)128);

        //close streams
        NoRepeat.Close();
        _Compressed.Close();

        // return compressed data in byte array
        return _Compressed.ToArray();
    }
Example #55
0
 private static void WriteNull(MemoryStream stream)
 {
     stream.WriteByte(__N);
     stream.WriteByte(__Semicolon);
 }
Example #56
0
 public void Write(TelnetCode code, TelnetOption opt)
 {
     _strm.WriteByte((byte)TelnetCode.IAC);
     _strm.WriteByte((byte)code);
     _strm.WriteByte((byte)opt);
 }
        public async Task GetAsync_CancelPendingRequests_DoesntCancelReadAsyncOnResponseStream(CancellationMode mode, bool copyToAsync)
        {
            if (IsNetfxHandler)
            {
                // throws ObjectDisposedException as part of Stream.CopyToAsync/ReadAsync
                return;
            }
            if (IsCurlHandler)
            {
                // Issue #27065
                // throws OperationCanceledException from Stream.CopyToAsync/ReadAsync
                return;
            }

            using (HttpClient client = CreateHttpClient())
            {
                client.Timeout = Timeout.InfiniteTimeSpan;

                await LoopbackServer.CreateServerAsync(async (server, url) =>
                {
                    var clientReadSomeBody = new TaskCompletionSource <bool>();
                    var clientFinished     = new TaskCompletionSource <bool>();

                    var responseContentSegment = new string('s', 3000);
                    int responseSegments       = 4;
                    int contentLength          = responseContentSegment.Length * responseSegments;

                    Task serverTask = server.AcceptConnectionAsync(async connection =>
                    {
                        await connection.ReadRequestHeaderAndSendCustomResponseAsync(
                            $"HTTP/1.1 200 OK\r\n" +
                            $"Date: {DateTimeOffset.UtcNow:R}\r\n" +
                            $"Content-Length: {contentLength}\r\n" +
                            $"\r\n");

                        for (int i = 0; i < responseSegments; i++)
                        {
                            await connection.Writer.WriteAsync(responseContentSegment);
                            if (i == 0)
                            {
                                await clientReadSomeBody.Task;
                            }
                        }

                        await clientFinished.Task;
                    });


                    using (HttpResponseMessage resp = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
                        using (Stream respStream = await resp.Content.ReadAsStreamAsync())
                        {
                            var result = new MemoryStream();
                            int b      = respStream.ReadByte();
                            Assert.NotEqual(-1, b);
                            result.WriteByte((byte)b);

                            Cancel(mode, client, null); // should not cancel the operation, as using ResponseHeadersRead
                            clientReadSomeBody.SetResult(true);

                            if (copyToAsync)
                            {
                                await respStream.CopyToAsync(result, 10, new CancellationTokenSource().Token);
                            }
                            else
                            {
                                byte[] buffer = new byte[10];
                                int bytesRead;
                                while ((bytesRead = await respStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                                {
                                    result.Write(buffer, 0, bytesRead);
                                }
                            }

                            Assert.Equal(contentLength, result.Length);
                        }

                    clientFinished.SetResult(true);
                    await serverTask;
                });
            }
        }
Example #58
0
        static void Main(string[] args)
        {
            //var directory = new DirectoryInfo(@"D:\directoryInfo");

            //if (directory.Exists)
            //{
            //    Console.WriteLine("Fullname: {0}", directory.FullName);
            //    Console.WriteLine("Name: {0}", directory.Name);
            //    Console.WriteLine("Parent: {0}", directory.Parent);
            //    Console.WriteLine("CreationTime: {0}", directory.CreationTime);
            //    Console.WriteLine("Attributes: {0}", directory.Attributes.ToString());
            //    Console.WriteLine("Root: {0}", directory.Root);
            //    Console.WriteLine("LastAccessTime: {0}", directory.LastAccessTime);
            //    Console.WriteLine("LastWriteTime: {0}", directory.LastWriteTime);

            //    FileInfo[] files = directory.GetFiles("*.txt");
            //    Console.WriteLine("Найдено {0} *.txt файлов", files.Length);

            //    directory.CreateSubdirectory("SUBDIR");
            //    directory.CreateSubdirectory(@"MyDir/SubMyDir");

            //    Directory.Delete(@"D:\TESTDIR\MyDir", true);


            //string[] drives = Directory.GetLogicalDrives();
            //Console.WriteLine("Имеющиеся диски:");

            //foreach (string drive in drives)
            //    Console.WriteLine("- {0}", drive);
            //}
            //else
            //    Console.WriteLine("Директория с именем: {0} не существует.", directory.FullName);


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

            //var file = new FileInfo(@"D:\Test.txt");

            ////FileStream stream = file.Create();
            //FileStream stream = file.Open(FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
            //Console.WriteLine("FullName {0}", file.FullName);

            //stream.Close();

            //file.Delete();

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

            //using (FileStream s = file.Create())
            //{
            //    ;///
            //}

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

            //var stream = new FileStream("Test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite);


            //for(int i=0; i < 256; i++)
            //{
            //    stream.WriteByte((byte)i);
            //}

            //Console.WriteLine(stream.Position);

            //stream.Position = 0;

            //for (int i = 0; i < 256; i++)
            //{
            //    stream.WriteByte((byte)i);
            //}

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

            var memory = new MemoryStream();

            memory.Capacity = 256;

            for (int i = 0; i < 256; i++)
            {
                memory.WriteByte((byte)i);
            }

            memory.Position = 0;

            for (int i = 0; i < 256; i++)
            {
                Console.Write(" " + memory.ReadByte());
            }

            var f1 = new FileStream("Dump.dat", FileMode.Create, FileAccess.ReadWrite);

            memory.WriteTo(f1);

            f1.Position = 0;

            for (int i = 0; i < 256; i++)
            {
                Console.Write(" " + f1.ReadByte());
            }

            memory.Close();
            f1.Close();
        }
Example #59
0
        /// <summary>
        /// Builds a PDF document from the current content of this builder and its pages.
        /// </summary>
        /// <returns>The bytes of the resulting PDF document.</returns>
        public byte[] Build()
        {
            var fontsWritten = new Dictionary <Guid, ObjectToken>();

            using (var memory = new MemoryStream())
            {
                // Header
                WriteString("%PDF-1.7", memory);

                // Files with binary data should contain a 2nd comment line followed by 4 bytes with values > 127
                memory.WriteText("%");
                memory.WriteByte(169);
                memory.WriteByte(205);
                memory.WriteByte(196);
                memory.WriteByte(210);
                memory.WriteNewLine();

                // Body
                foreach (var font in fonts)
                {
                    var fontObj = font.Value.FontProgram.WriteFont(font.Value.FontKey.Name, memory, context);
                    fontsWritten.Add(font.Key, fontObj);
                }

                foreach (var image in images)
                {
                    var streamToken = new StreamToken(image.Value.StreamDictionary, image.Value.StreamData);

                    context.WriteObject(memory, streamToken, image.Value.ObjectNumber);
                }

                var procSet = new List <NameToken>
                {
                    NameToken.Create("PDF"),
                    NameToken.Text,
                    NameToken.ImageB,
                    NameToken.ImageC,
                    NameToken.ImageI
                };

                var resources = new Dictionary <NameToken, IToken>
                {
                    { NameToken.ProcSet, new ArrayToken(procSet) }
                };

                if (fontsWritten.Count > 0)
                {
                    var fontsDictionary = new DictionaryToken(fontsWritten.Select(x => (fonts[x.Key].FontKey.Name, (IToken) new IndirectReferenceToken(x.Value.Number)))
                                                              .ToDictionary(x => x.Item1, x => x.Item2));

                    var fontsDictionaryRef = context.WriteObject(memory, fontsDictionary);

                    resources.Add(NameToken.Font, new IndirectReferenceToken(fontsDictionaryRef.Number));
                }

                var reserved       = context.ReserveNumber();
                var parentIndirect = new IndirectReferenceToken(new IndirectReference(reserved, 0));

                var pageReferences = new List <IndirectReferenceToken>();
                foreach (var page in pages)
                {
                    var individualResources = new Dictionary <NameToken, IToken>(resources);
                    var pageDictionary      = new Dictionary <NameToken, IToken>
                    {
                        { NameToken.Type, NameToken.Page },
                        { NameToken.MediaBox, RectangleToArray(page.Value.PageSize) },
                        { NameToken.Parent, parentIndirect }
                    };

                    if (page.Value.Resources.Count > 0)
                    {
                        foreach (var kvp in page.Value.Resources)
                        {
                            // TODO: combine resources if value is dictionary or array, otherwise overwrite.
                            individualResources[kvp.Key] = kvp.Value;
                        }
                    }

                    pageDictionary[NameToken.Resources] = new DictionaryToken(individualResources);

                    if (page.Value.Operations.Count > 0)
                    {
                        var contentStream = WriteContentStream(page.Value.Operations);

                        var contentStreamObj = context.WriteObject(memory, contentStream);

                        pageDictionary[NameToken.Contents] = new IndirectReferenceToken(contentStreamObj.Number);
                    }

                    var pageRef = context.WriteObject(memory, new DictionaryToken(pageDictionary));

                    pageReferences.Add(new IndirectReferenceToken(pageRef.Number));
                }

                var pagesDictionaryData = new Dictionary <NameToken, IToken>
                {
                    { NameToken.Type, NameToken.Pages },
                    { NameToken.Kids, new ArrayToken(pageReferences) },
                    { NameToken.Count, new NumericToken(pageReferences.Count) }
                };

                var pagesDictionary = new DictionaryToken(pagesDictionaryData);

                var pagesRef = context.WriteObject(memory, pagesDictionary, reserved);

                var catalogDictionary = new Dictionary <NameToken, IToken>
                {
                    { NameToken.Type, NameToken.Catalog },
                    { NameToken.Pages, new IndirectReferenceToken(pagesRef.Number) }
                };

                if (ArchiveStandard != PdfAStandard.None)
                {
                    Func <IToken, ObjectToken> writerFunc = x => context.WriteObject(memory, x);

                    PdfABaselineRuleBuilder.Obey(catalogDictionary, writerFunc, DocumentInformation, ArchiveStandard);

                    switch (ArchiveStandard)
                    {
                    case PdfAStandard.A1A:
                        PdfA1ARuleBuilder.Obey(catalogDictionary);
                        break;

                    case PdfAStandard.A2B:
                        break;
                    }
                }

                var catalog = new DictionaryToken(catalogDictionary);

                var catalogRef = context.WriteObject(memory, catalog);

                var informationReference = default(IndirectReference?);
                if (IncludeDocumentInformation)
                {
                    var informationDictionary = DocumentInformation.ToDictionary();
                    if (informationDictionary.Count > 0)
                    {
                        var dictionary = new DictionaryToken(informationDictionary);
                        informationReference = context.WriteObject(memory, dictionary).Number;
                    }
                }

                TokenWriter.WriteCrossReferenceTable(context.ObjectOffsets, catalogRef, memory, informationReference);

                return(memory.ToArray());
            }
        }
Example #60
0
 public void WriteByte(byte value)
 {
     _stream.WriteByte(value);
 }