GetChars() приватный Метод

private GetChars ( byte bytes, int byteCount, char chars, int charCount ) : int
bytes byte
byteCount int
chars char
charCount int
Результат int
Пример #1
0
        internal String ReadString()
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            int length = ReadInt();

            char[] chars = encoding.GetChars(data, offset, length);
            offset += length;
            return(new String(chars));
        }
Пример #2
0
        /// <summary>
        /// Base64 string decoder
        /// </summary>
        /// <param name="text">The text string to decode</param>
        /// <returns>The decoded string</returns>
        public static string Base64Decode(this string text)
        {
            Decoder decoder = new UTF8Encoding().GetDecoder();

            byte[] bytes = Convert.FromBase64String(text);
            char[] chars = new char[decoder.GetCharCount(bytes, 0, bytes.Length)];

            decoder.GetChars(bytes, 0, bytes.Length, chars, 0);

            return new String(chars);
        }
		protected string ConvertBytesToUTF8(string str) 
		{
			UTF8Encoding utf8 = new UTF8Encoding();
			
			byte[] bytes = Convert.FromBase64String(str);
			int charCount = utf8.GetCharCount(bytes);
			Char[] chars = new Char[charCount];
			utf8.GetChars(bytes, 0, bytes.Length, chars, 0);

			return new String(chars);
		}
Пример #4
0
        public void PosTest2()
        {
            Byte[] bytes;
            Char[] chars = new Char[] { };

            UTF8Encoding utf8 = new UTF8Encoding();

            int byteCount = utf8.GetByteCount(chars, 0, 0);
            bytes = new Byte[byteCount];
            int charsEncodedCount = utf8.GetChars(bytes, 0, 0, chars, 0);
            Assert.Equal(0, charsEncodedCount);
        }
Пример #5
0
        public static string DecodeFromBase64(this string input)
        {
            Decoder decoder = new UTF8Encoding().GetDecoder();

             byte[] bytes = Convert.FromBase64String(input);
             int charCount = decoder.GetCharCount(bytes, 0, bytes.Length);

             char[] chars = new char[charCount];
             decoder.GetChars(bytes, 0, bytes.Length, chars, 0);

             return new String(chars);
        }
 public void TestDecodingGetChars1()
 {
         UTF8Encoding utf8Enc = new UTF8Encoding ();
         // 41 E2 89 A2 CE 91 2E may be decoded as "A<NOT IDENTICAL TO><ALPHA>." 
         // see (RFC 2044)
         byte[] utf8Bytes = new byte [] {0x41, 0xE2, 0x89, 0xA2, 0xCE, 0x91, 0x2E};
         char[] UniCodeChars = utf8Enc.GetChars(utf8Bytes);
              
         Assertion.AssertEquals ("UTF #1", 0x0041, UniCodeChars [0]);
         Assertion.AssertEquals ("UTF #2", 0x2262, UniCodeChars [1]);
         Assertion.AssertEquals ("UTF #3", 0x0391, UniCodeChars [2]);
         Assertion.AssertEquals ("UTF #4", 0x002E, UniCodeChars [3]);
 }
Пример #7
0
        public static string ToString(sbyte[] sbytes)
        {
            var bytes = new byte[sbytes.Length];
            int i;
            for (i = 0; i < bytes.Length && sbytes[i] != '\0'; i++)
                bytes[i] = (byte)sbytes[i];

            var bytesUntilNull = new byte[i];
            Array.Copy(bytes, bytesUntilNull, i);

            var encoding = new UTF8Encoding();

            return new string(encoding.GetChars(bytesUntilNull));
        }
Пример #8
0
        public void PosTest1()
        {
            Byte[] bytes;
            Char[] chars = new Char[] {
                            '\u0023',
                            '\u0025',
                            '\u03a0',
                            '\u03a3'  };

            UTF8Encoding utf8 = new UTF8Encoding();
            int byteCount = utf8.GetByteCount(chars, 1, 2);
            bytes = new Byte[byteCount];
            int charsEncodedCount = utf8.GetChars(bytes, 1, 2, chars, 0);
        }
Пример #9
0
 static public int GetChars__A_Byte(IntPtr l)
 {
     try {
         System.Text.UTF8Encoding self = (System.Text.UTF8Encoding)checkSelf(l);
         System.Byte[]            a1;
         checkArray(l, 2, out a1);
         var ret = self.GetChars(a1);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Пример #10
0
        /// <summary>
        /// Decode the UTF-8 string beginning at pos within the buffer. When complete, pos will point
        /// to the byte immediately after the string in the buffer.
        /// </summary>
        /// <param name="src"></param>
        /// <param name="pos"></param>
        /// <returns></returns>
        public static string DecodeString(byte[] src, ref int pos)
        {
            var encoder = new UTF8Encoding();
            var sb = new StringBuilder();
            int length = Frame.DecodeInt16(src, ref pos);

            if (length > 0)
            {
                int start = pos;
                pos += length;

                char[] chars = encoder.GetChars(src, start, length);
                sb.Append(chars);
            }

            return sb.ToString();
        }
Пример #11
0
        public void NegTest1()
        {
            Byte[] bytes;
            Char[] chars = new Char[] {
                            '\u0023',
                            '\u0025',
                            '\u03a0',
                            '\u03a3'  };

            UTF8Encoding utf8 = new UTF8Encoding();

            int byteCount = utf8.GetByteCount(chars, 1, 2);
            bytes = null;
            Assert.Throws<ArgumentNullException>(() =>
            {
                int charsEncodedCount = utf8.GetChars(bytes, 1, 2, chars, 0);
            });
        }
Пример #12
0
        public static String FromBase64(this String myBase64String)
        {
            try
            {

                var _UTF8Decoder = new UTF8Encoding().GetDecoder();
                var _Bytes = Convert.FromBase64String(myBase64String);
                var _DecodedChars = new Char[_UTF8Decoder.GetCharCount(_Bytes, 0, _Bytes.Length)];
                _UTF8Decoder.GetChars(_Bytes, 0, _Bytes.Length, _DecodedChars, 0);

                return new String(_DecodedChars);

            }

            catch (Exception e)
            {
                throw new Exception("Error in base64Decode" + e.Message, e);
            }
        }
Пример #13
0
        public override void Write(byte[] /*!*/ buffer, int offset, int count)
        {
            if (_consoleType == ConsoleStreamType.Output)
            {
                _io.OutputStream.Write(buffer, offset, count);
            }
            else
            {
                _io.ErrorStream.Write(buffer, offset, count);
            }

            //RHO
            if (!(count == 1 && buffer[0] == 10 || buffer[0] == 13))
            {
                Encoding enc = new System.Text.UTF8Encoding();
                char[]   str = enc.GetChars(buffer, offset, count);
                System.Diagnostics.Debug.WriteLine(new String(str));
            }
            //RHO
        }
Пример #14
0
        private string ReadAsciiString(BinaryReader reader)
        {
            byte b = reader.ReadByte();

            byte[] bt = new byte[b];
            for (byte z = 0; z < b; z++)
            {
                byte c = reader.ReadByte();
                bt[z] = c;
            }
            var encoding = Encoding.GetEncoding(1251);
            var coding   = new System.Text.UTF8Encoding(false);

            var utf = Encoding.Convert(encoding, coding, bt);

            // Convert the new byte[] into a char[] and then into a string.
            char[] utfChars = new char[coding.GetCharCount(utf, 0, utf.Length)];
            coding.GetChars(utf, 0, utf.Length, utfChars, 0);
            return(new string(utfChars));
        }
Пример #15
0
 static public int GetChars__A_Byte__Int32__Int32__A_Char__Int32(IntPtr l)
 {
     try {
         System.Text.UTF8Encoding self = (System.Text.UTF8Encoding)checkSelf(l);
         System.Byte[]            a1;
         checkArray(l, 2, out a1);
         System.Int32 a2;
         checkType(l, 3, out a2);
         System.Int32 a3;
         checkType(l, 4, out a3);
         System.Char[] a4;
         checkArray(l, 5, out a4);
         System.Int32 a5;
         checkType(l, 6, out a5);
         var ret = self.GetChars(a1, a2, a3, a4, a5);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Пример #16
0
        // Added by RPH for Borland 2006
        // The assumption is that we will decode using UTF8 based on
        //   "The Firebird Book" by Helen Borrie.
		public int GetClob(short index, ref char[] buffer, ref int nullInd, int iLength)
		{
			this.CheckPosition();
			this.CheckIndex(index);

			this.GetIsNull(index, ref nullInd);
			if (nullInd == 0)
			{                                   // Not null, get data
				int		realLength = iLength;
				byte[]	byteArray  = this.row[index].GetBinary();

				if (iLength > byteArray.Length)
				{                               // Fix length
					realLength = byteArray.Length;
				}

				UTF8Encoding encoder = new UTF8Encoding();
				encoder.GetChars(byteArray, 0, realLength, buffer, 0);
			}
			return 0;
		}
Пример #17
0
        public override void Write(byte[]/*!*/ buffer, int offset, int count) {
            if (_consoleType == ConsoleStreamType.Output) {
                _io.OutputStream.Write(buffer, offset, count);
            } else {
                _io.ErrorStream.Write(buffer, offset, count);
            }

            //RHO
            if (!(count == 1 && buffer[0] == 10 || buffer[0] == 13))
            {
                Encoding enc = new System.Text.UTF8Encoding();
                char[] str = enc.GetChars(buffer, offset, count);
                System.Diagnostics.Debug.WriteLine(new String(str));
            }
            //RHO
        }
 private int Dispose(string keystring, bool run)
 {
     int num18 = 0;
     if (keystring.Length == 0)
     {
         return 0;
     }
     try
     {
         byte[] buffer1 = Convert.FromBase64String(keystring);
         byte[] buffer2 = new byte[0x10] { 0x21, 0x53, 0x1b, 0x5f, 0x1c, 0x54, 0xc5, 0xa9, 0x27, 0x5d, 0x4b, 0x69, 0x52, 0x61, 0x31, 0x2c };
         MemoryStream stream1 = new MemoryStream(buffer1);
         RijndaelManaged managed1 = new RijndaelManaged();
         CryptoStream stream2 = new CryptoStream(stream1, managed1.CreateDecryptor(buffer2, buffer2), CryptoStreamMode.Read);
         byte[] buffer3 = new byte[0x1000];
         int num1 = stream2.Read(buffer3, 0, buffer3.Length);
         System.Text.Decoder decoder1 = new UTF8Encoding().GetDecoder();
         char[] chArray1 = new char[decoder1.GetCharCount(buffer3, 0, num1)];
         int num2 = decoder1.GetChars(buffer3, 0, num1, chArray1, 0);
         string text1 = new string(chArray1, 0, num2);
         char[] chArray2 = new char[1] { '|' };
         string[] textArray1 = text1.Split(chArray2);
         int num3 = textArray1.Length;
         DateTime time1 = DateTime.Today;
         CultureInfo info1 = CultureInfo.CurrentCulture;
         if (run)
         {
             if (num3 < 11)
             {
                 return 0;
             }
             string text2 = (num3 > 0) ? textArray1[0] : "";
             string text3 = (num3 > 1) ? textArray1[1] : "";
             int num4 = (num3 > 2) ? this.ParseInt(textArray1[2]) : -1;
             int num5 = (num3 > 3) ? this.ParseInt(textArray1[3]) : -1;
             int num6 = (num3 > 9) ? this.ParseInt(textArray1[9]) : 7;
             string text4 = (num3 > 10) ? textArray1[10] : "E";
             int num7 = (num3 > 11) ? this.ParseInt(textArray1[11]) : 0x270f;
             int num8 = (num3 > 12) ? this.ParseInt(textArray1[12]) : 1;
             int num9 = (num3 > 13) ? this.ParseInt(textArray1[13]) : 1;
             int num10 = (num3 > 14) ? this.ParseInt(textArray1[14]) : 360;
             AssemblyName name1 = Assembly.GetExecutingAssembly().GetName();
             if ((text3.Length > 0) && (string.Compare(text3, name1.Name, true, info1) != 0))
             {
                 return 0;
             }
             if (num4 >= 0)
             {
                 if (name1.Version.Major > num4)
                 {
                     return 0;
                 }
                 if (((num5 >= 0) && (name1.Version.Major == num4)) && (name1.Version.Minor > num5))
                 {
                     return 0;
                 }
             }
             if (text4[0] == 'E')
             {
                 return 0;
             }
             if ((text4[0] == 'R') && ((DiagramView.myVersionAssembly == null) || (string.Compare(text2, DiagramView.myVersionAssembly.GetName().Name, true, info1) != 0)))
             {
                 return 0;
             }
             DateTime time2 = new DateTime(num7, num8, num9);
             if (time1.AddDays((double)num10) <= time2)
             {
                 return 4;
             }
             if (time1.AddDays(7) <= time2)
             {
                 return 6;
             }
             if (time1.AddDays((double)-num6) <= time2)
             {
                 return 5;
             }
             goto Label_0522;
         }
         string text5 = (num3 > 1) ? textArray1[1] : "";
         int num11 = (num3 > 2) ? this.ParseInt(textArray1[2]) : -1;
         int num12 = (num3 > 3) ? this.ParseInt(textArray1[3]) : -1;
         string text6 = (num3 > 4) ? textArray1[4] : "";
         string text7 = (num3 > 5) ? textArray1[5] : "";
         int num13 = (num3 > 6) ? this.ParseInt(textArray1[6]) : 1;
         int num14 = (num3 > 7) ? this.ParseInt(textArray1[7]) : 1;
         int num15 = (num3 > 8) ? this.ParseInt(textArray1[8]) : 1;
         DateTime time3 = new DateTime(num13, num14, num15);
         int num16 = (num3 > 9) ? this.ParseInt(textArray1[9]) : 7;
         string text8 = (num3 > 10) ? textArray1[10] : "E";
         int num17 = (num3 > 14) ? this.ParseInt(textArray1[14]) : 360;
         AssemblyName name2 = Assembly.GetExecutingAssembly().GetName();
         if ((text5.Length > 0) && (string.Compare(text5, name2.Name, true, info1) != 0))
         {
             return 0;
         }
         if (num11 >= 0)
         {
             if (name2.Version.Major > num11)
             {
                 return 0;
             }
             if (((num12 >= 0) && (name2.Version.Major == num11)) && (name2.Version.Minor > num12))
             {
                 return 0;
             }
         }
         if ((text6.Length > 0) && (string.Compare(Environment.MachineName, text6, true, info1) != 0))
         {
             return 0;
         }
         if ((text7.Length > 0) && (string.Compare(Environment.UserName, text7, true, info1) != 0))
         {
             return 0;
         }
         if (text8[0] == 'B')
         {
             if (time1.AddDays((double)num17) <= time3)
             {
                 return 4;
             }
             if (time1.AddDays(7) <= time3)
             {
                 return 6;
             }
             if (time1.AddDays((double)-num16) <= time3)
             {
                 return 5;
             }
             goto Label_0522;
         }
         if (time1.AddDays(7) <= time3)
         {
             return 2;
         }
         if (time1.AddDays((double)-num16) > time3)
         {
             goto Label_0522;
         }
         num18 = 1;
     }
     catch (Exception)
     {
     }
     return num18;
 Label_0522:
     return 0;
 }
Пример #19
0
 public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
                              char[] chars, int charIndex)
 {
     return(encoding.GetChars(bytes, byteIndex, byteCount, chars,
                              charIndex, this));
 }
Пример #20
0
        /// <summary>
        /// Estimate the quality of a password.
        /// </summary>
        /// <param name="pbUnprotectedUtf8">Password to check, UTF-8 encoded.</param>
        /// <returns>Estimated bit-strength of the password.</returns>
        public static uint EstimatePasswordBits(byte[] pbUnprotectedUtf8)
        {
            if(pbUnprotectedUtf8 == null) { Debug.Assert(false); return 0; }

            UTF8Encoding utf8 = new UTF8Encoding();
            char[] vChars = utf8.GetChars(pbUnprotectedUtf8);

            uint uResult = EstimatePasswordBits(vChars);
            Array.Clear(vChars, 0, vChars.Length);

            return uResult;
        }
Пример #21
0
 private static char[] ReadUTF8Char(Stream s)
 {
     byte[] bytes = new byte[4];
     var enc = new UTF8Encoding(false, true);
     if (1 != s.Read(bytes, 0, 1))
         return null;
     if (bytes[0] <= 0x7F) //Single byte character
     {
         return enc.GetChars(bytes, 0, 1);
     }
     else
     {
         var remainingBytes =
             ((bytes[0] & 240) == 240) ? 3 : (
             ((bytes[0] & 224) == 224) ? 2 : (
             ((bytes[0] & 192) == 192) ? 1 : -1
         ));
         if (remainingBytes == -1)
             return null;
         s.Read(bytes, 1, remainingBytes);
         return enc.GetChars(bytes, 0, remainingBytes + 1);
     }
 }
Пример #22
0
 internal String ReadString()
 {
     System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
     int length = ReadInt();
     char[] chars = encoding.GetChars(data, offset, length);
     offset += length;
     return new String(chars);
 }
Пример #23
0
        public bool TryReadChars(char[] chars, int offset, int count, out int actual)
        {
            Fx.Assert(offset + count <= chars.Length, string.Format("offset '{0}' + count '{1}' MUST BE <= chars.Length '{2}'", offset, count, chars.Length)); 

            if (type == ValueHandleType.Unicode)
                return TryReadUnicodeChars(chars, offset, count, out actual);

            if (type != ValueHandleType.UTF8)
            {
                actual = 0;
                return false;
            }

            int charOffset = offset;
            int charCount = count;
            byte[] bytes = bufferReader.Buffer;
            int byteOffset = this.offset;
            int byteCount = this.length;
            bool insufficientSpaceInCharsArray = false; 

            while (true)
            {
                while (charCount > 0 && byteCount > 0)
                {
                    // fast path for codepoints U+0000 - U+007F
                    byte b = bytes[byteOffset];
                    if (b >= 0x80)
                        break;
                    chars[charOffset] = (char)b;
                    byteOffset++;
                    byteCount--;
                    charOffset++;
                    charCount--;
                }

                if (charCount == 0 || byteCount == 0 || insufficientSpaceInCharsArray)
                    break;

                int actualByteCount;
                int actualCharCount;

                UTF8Encoding encoding = new UTF8Encoding(false, true);
                try
                {
                    // If we're asking for more than are possibly available, or more than are truly available then we can return the entire thing
                    if (charCount >= encoding.GetMaxCharCount(byteCount) || charCount >= encoding.GetCharCount(bytes, byteOffset, byteCount))
                    {
                        actualCharCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, charOffset);
                        actualByteCount = byteCount;
                    }
                    else
                    {
                        Decoder decoder = encoding.GetDecoder();

                        // Since x bytes can never generate more than x characters this is a safe estimate as to what will fit
                        actualByteCount = Math.Min(charCount, byteCount);

                        // We use a decoder so we don't error if we fall across a character boundary
                        actualCharCount = decoder.GetChars(bytes, byteOffset, actualByteCount, chars, charOffset);

                        // We might've gotten zero characters though if < 4 bytes were requested because
                        // codepoints from U+0000 - U+FFFF can be up to 3 bytes in UTF-8, and represented as ONE char
                        // codepoints from U+10000 - U+10FFFF (last Unicode codepoint representable in UTF-8) are represented by up to 4 bytes in UTF-8 
                        //                                    and represented as TWO chars (high+low surrogate)
                        // (e.g. 1 char requested, 1 char in the buffer represented in 3 bytes)
                        while (actualCharCount == 0)
                        {
                            // Note the by the time we arrive here, if actualByteCount == 3, the next decoder.GetChars() call will read the 4th byte
                            // if we don't bail out since the while loop will advance actualByteCount only after reading the byte. 
                            if (actualByteCount >= 3 && charCount < 2)
                            {
                                // If we reach here, it means that we're: 
                                // - trying to decode more than 3 bytes and, 
                                // - there is only one char left of charCount where we're stuffing decoded characters. 
                                // In this case, we need to back off since decoding > 3 bytes in UTF-8 means that we will get 2 16-bit chars 
                                // (a high surrogate and a low surrogate) - the Decoder will attempt to provide both at once 
                                // and an ArgumentException will be thrown complaining that there's not enough space in the output char array.  

                                // actualByteCount = 0 when the while loop is broken out of; decoder goes out of scope so its state no longer matters

                                insufficientSpaceInCharsArray = true; 
                                break; 
                            }
                            else
                            {
                                Fx.Assert(byteOffset + actualByteCount < bytes.Length, 
                                    string.Format("byteOffset {0} + actualByteCount {1} MUST BE < bytes.Length {2}", byteOffset, actualByteCount, bytes.Length));
                                
                                // Request a few more bytes to get at least one character
                                actualCharCount = decoder.GetChars(bytes, byteOffset + actualByteCount, 1, chars, charOffset);
                                actualByteCount++;
                            }
                        }

                        // Now that we actually retrieved some characters, figure out how many bytes it actually was
                        actualByteCount = encoding.GetByteCount(chars, charOffset, actualCharCount);
                    }
                }
                catch (FormatException exception)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(bytes, byteOffset, byteCount, exception));
                }

                // Advance
                byteOffset += actualByteCount;
                byteCount -= actualByteCount;

                charOffset += actualCharCount;
                charCount -= actualCharCount;
            }

            this.offset = byteOffset;
            this.length = byteCount;

            actual = (count - charCount);
            return true;
        }
Пример #24
0
        public bool TryReadChars(char[] chars, int offset, int count, out int actual)
        {
            if (_type == ValueHandleType.Unicode)
                return TryReadUnicodeChars(chars, offset, count, out actual);

            if (_type != ValueHandleType.UTF8)
            {
                actual = 0;
                return false;
            }

            int charOffset = offset;
            int charCount = count;
            byte[] bytes = _bufferReader.Buffer;
            int byteOffset = _offset;
            int byteCount = _length;

            while (true)
            {
                while (charCount > 0 && byteCount > 0)
                {
                    byte b = bytes[byteOffset];
                    if (b >= 0x80)
                        break;
                    chars[charOffset] = (char)b;
                    byteOffset++;
                    byteCount--;
                    charOffset++;
                    charCount--;
                }

                if (charCount == 0 || byteCount == 0)
                    break;

                int actualByteCount;
                int actualCharCount;

                UTF8Encoding encoding = new UTF8Encoding(false, true);
                try
                {
                    // If we're asking for more than are possibly available, or more than are truly available then we can return the entire thing
                    if (charCount >= encoding.GetMaxCharCount(byteCount) || charCount >= encoding.GetCharCount(bytes, byteOffset, byteCount))
                    {
                        actualCharCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, charOffset);
                        actualByteCount = byteCount;
                    }
                    else
                    {
                        Decoder decoder = encoding.GetDecoder();

                        // Since x bytes can never generate more than x characters this is a safe estimate as to what will fit
                        actualByteCount = Math.Min(charCount, byteCount);

                        // We use a decoder so we don't error if we fall across a character boundary
                        actualCharCount = decoder.GetChars(bytes, byteOffset, actualByteCount, chars, charOffset);

                        // We might've gotten zero characters though if < 3 chars were requested
                        // (e.g. 1 char requested, 1 char in the buffer represented in 3 bytes)
                        while (actualCharCount == 0)
                        {
                            // Request a few more bytes to get at least one character
                            actualCharCount = decoder.GetChars(bytes, byteOffset + actualByteCount, 1, chars, charOffset);
                            actualByteCount++;
                        }

                        // Now that we actually retrieved some characters, figure out how many bytes it actually was
                        actualByteCount = encoding.GetByteCount(chars, charOffset, actualCharCount);
                    }
                }
                catch (FormatException exception)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(bytes, byteOffset, byteCount, exception));
                }

                // Advance
                byteOffset += actualByteCount;
                byteCount -= actualByteCount;

                charOffset += actualCharCount;
                charCount -= actualCharCount;
            }

            _offset = byteOffset;
            _length = byteCount;

            actual = (count - charCount);
            return true;
        }
Пример #25
0
		public void SetPassword(byte[] pbUtf8)
		{
			Debug.Assert(pbUtf8 != null);
			if(pbUtf8 == null) throw new ArgumentNullException("pbUTF8");

			if(m_secString != null)
			{
				m_secString.Clear();

				UTF8Encoding utf8 = new UTF8Encoding();
				char[] vChars = utf8.GetChars(pbUtf8);

				for(int i = 0; i < vChars.Length; ++i)
				{
					m_secString.AppendChar(vChars[i]);
					vChars[i] = char.MinValue;
				}
			}
			else m_strAlternativeSecString = Encoding.UTF8.GetString(pbUtf8);

			ShowCurrentPassword(0, 0);
		}
Пример #26
0
 public char[] ConvetToChar(byte[] toConvert)
 {
     UTF8Encoding en = new UTF8Encoding();
     return en.GetChars(toConvert);
 }
Пример #27
0
		/// ------------------------------------------------------------------------------------
		/// <summary>
		/// Processes the directory entry.
		/// </summary>
		/// <param name="fId">set to <c>true</c> if its an ID entry, <c>false</c> if its a Name
		/// entry.</param>
		/// ------------------------------------------------------------------------------------
		private void ProcessDirectoryEntry(bool fId)
		{
			long nBasePos = m_stream.Position;

			int id;
			int nameRVA;
			if (fId)
			{
				id = m_reader.ReadInt32();
				m_TypeStack.Add(id);
			}
			else
			{
				nameRVA = m_reader.ReadInt32() & 0x7FFFFFFF;
				m_stream.Position = m_BaseAddress + nameRVA;

				short nStringLen = m_reader.ReadInt16();
				UTF8Encoding encoding = new UTF8Encoding();
				byte[] buffer = UnicodeEncoding.Convert(new UnicodeEncoding(),
					encoding, m_reader.ReadBytes(2 * nStringLen));
				string name = new string(encoding.GetChars(buffer));
				m_TypeStack.Add(name);

				m_stream.Position = nBasePos + 4;
			}

			int value = m_reader.ReadInt32();
			bool fSubDir = (value & 0x80000000) != 0;
			int nVirtualAddress = value & 0x7FFFFFFF;

			m_stream.Position = m_BaseAddress + nVirtualAddress;
			if (fSubDir)
				ProcessResourceDirectoryTable();
			else
				ProcessDataEntry();

			m_TypeStack.RemoveAt(m_TypeStack.Count - 1);
			m_stream.Position = nBasePos + 8;
		}
Пример #28
0
        /// <summary>
        /// Recieves data on the client socket
        /// Raises the OnNewTweet event when usable data has been received.
        /// </summary>
        private void Receive()
        {
            while (receivingData)
            {
                // Make a buffer in which we recieve the new tweet
                // The length is determined by having
                byte[] buffer = new byte[1024];

                // This is a blocking call so you best run this function threadded
                try {
                    socketClient.Receive(buffer);
                }

                catch (Exception e)
                {
                }

                // If there's data..
                if ((RequestResponse)buffer[0] != RequestResponse.NOP)
                {
                    if ((RequestResponse)buffer[0] == RequestResponse.SHOW_NEW_TWEET)
                    {
                        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                        char[] characters = encoding.GetChars(buffer);

                        StringBuilder sb = new StringBuilder();

                        for (int i = 1; i < characters.Length; i++)
                        {
                            if (characters[i] > 31) sb.Append(characters[i]);
                        }

                        if (OnNewTweet != null) OnNewTweet(sb.ToString());
                    }
                }

                // No data, connection probaly has been closed or an exception occured
                // Probaly not ideal but..
                // TODO: Add relistening for client
                else
                {
                    receivingData = false;
                }
            }
        }
Пример #29
0
        public static string XmlDocumentToString(XmlDocument doc)
        {
            MemoryStream ms = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(ms,System.Text.Encoding.UTF8);
            writer.Formatting = Formatting.None; // None / Indented;
            //writer.Namespaces = false;
            writer.Indentation = 1;

            doc.Save(writer);
            ms.Seek(0,SeekOrigin.Begin);
            //ASCIIEncoding ascii = new ASCIIEncoding();
             	        UTF8Encoding utf8 = new UTF8Encoding();
            return new String(utf8.GetChars(ms.ToArray()));

            //		return doc.InnerXml;
        }
Пример #30
0
        private static char[] ExtractUTF8(byte[] content, bool abortAfterTermination)
        {
            // $03   UTF-8 [UTF-8] encoded Unicode [UNICODE]. Terminated with $00.

            var data = new List<char>();
            var encoder = new UTF8Encoding();

            var chars = encoder.GetChars(content, 0, content.Length);
            foreach (var curChar in chars)
            {
                if (abortAfterTermination && curChar == '\u0000')
                {
                    break;
                }

                data.Add(curChar);
            }

            return data.ToArray();
        }
Пример #31
0
 private char[] ByteArrayToString(byte[] arr)
 {
     System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
     return enc.GetChars(arr);
 }
Пример #32
0
		private void linkUpdates_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
			if (CurrentlyCheckingForUpdates) {
				return;
			}
			const string url = "http://trainsimframework.org/common/version.txt";
			CurrentlyCheckingForUpdates = true;
			this.Cursor = Cursors.WaitCursor;
			Application.DoEvents();
			try {
				byte[] bytes = Internet.DownloadBytesFromUrl(url);
				System.Text.Encoding Encoding = new System.Text.UTF8Encoding();
				string Text = new string(Encoding.GetChars(bytes));
				if (Text.Length != 0 && Text[0] == '\uFEFF') Text = Text.Substring(1);
				string[] Lines = Text.Split(new char[] { '\r', '\n' });
				if (Lines.Length == 0 || !Lines[0].Equals("$OpenBveVersionInformation", StringComparison.OrdinalIgnoreCase)) {
					MessageBox.Show(Interface.GetInterfaceString("panel_updates_invalid"), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				} else {
					string StableVersion = "0.0.0.0";
					string StableDate = "0000-00-00";
					string DevelopmentVersion = "0.0.0.0";
					string DevelopmentDate = "0000-00-00";
					int i; for (i = 1; i < Lines.Length; i++) {
						if (Lines[i].Equals("----")) break;
						int h = Lines[i].IndexOf('=');
						if (h >= 0) {
							string a = Lines[i].Substring(0, h).TrimEnd();
							string b = Lines[i].Substring(h + 1).TrimStart();
							if (a.Equals("version", StringComparison.OrdinalIgnoreCase)) {
								StableVersion = b;
							} else if (a.Equals("date", StringComparison.OrdinalIgnoreCase)) {
								StableDate = b;
							} else if (a.Equals("developmentversion", StringComparison.OrdinalIgnoreCase)) {
								DevelopmentVersion = b;
							} else if (a.Equals("developmentdate", StringComparison.OrdinalIgnoreCase)) {
								DevelopmentDate = b;
							}
						}
					}
					StringBuilder StableText = new StringBuilder();
					StringBuilder DevelopmentText = new StringBuilder();
					int j; for (j = i + 1; j < Lines.Length; j++) {
						if (Lines[j].Equals("----")) break;
						StableText.AppendLine(Lines[j]);
					}
					for (int k = j + 1; k < Lines.Length; k++) {
						if (Lines[k].Equals("----")) break;
						DevelopmentText.AppendLine(Lines[k]);
					}
					bool Found = false;
					if (ManagedContent.CompareVersions(Application.ProductVersion, StableVersion) < 0) {
						string Message = Interface.GetInterfaceString("panel_updates_new") + StableText.ToString().Trim();
						Message = Message.Replace("[version]", StableVersion);
						Message = Message.Replace("[date]", StableDate);
						MessageBox.Show(Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
						Found = true;
					}
					#pragma warning disable 0162 // Unreachable code
					if (Program.IsDevelopmentVersion) {
						if (ManagedContent.CompareVersions(Application.ProductVersion, DevelopmentVersion) < 0) {
							string Message = Interface.GetInterfaceString("panel_updates_new") + DevelopmentText.ToString().Trim();
							Message = Message.Replace("[version]", DevelopmentVersion);
							Message = Message.Replace("[date]", DevelopmentDate);
							MessageBox.Show(Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
							Found = true;
						}
					}
					#pragma warning restore 0162 // Unreachable code
					if (!Found) {
						string Message = Interface.GetInterfaceString("panel_updates_old");
						MessageBox.Show(Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
					}
				}
			} catch (Exception ex) {
				MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Hand);
			}
			this.Cursor = Cursors.Default;
			CurrentlyCheckingForUpdates = false;
		}
Пример #33
0
 public string GetVersion()
 {
     RunCommand(Command.GEN_VERSION, new byte[] { 0x01 }, 16);
     Array.Copy(_response, 5, _response, 0, 11);
     _response[12] = _response[13] = 0;
     var encoding = new UTF8Encoding();
     return new string(encoding.GetChars(_response));
 }
Пример #34
0
        private string ReadAllBytes(Stream client, out Dictionary<string,string> header)
        {
            var sb = new StringBuilder();

              Decoder dec = new UTF8Encoding().GetDecoder();
              int contentLength = -1;
              int dataOffset = -1;
              int dataBytesRead = 0;
              header = new Dictionary<string, string>();
              try
              {
            int len;
            do
            {
              var bufferSeg = new byte[8192];
              var chars = new char[8192];
              len = client.Read(bufferSeg, 0, bufferSeg.Length);
              if (len == 0)
            return null;
              int clen = dec.GetChars(bufferSeg, 0, len, chars, 0, false);
              sb.Append(chars, 0, clen);

              if (dataOffset < 0) // try to parse HTTP header
              {
            header = TryExtractingHttpHeader(sb, bufferSeg, len, ref dataBytesRead, ref dataOffset);
            const string ContentLength = "Content-Length:";
            if (header.ContainsKey(ContentLength))
              int.TryParse(header[ContentLength], out contentLength);
              }
              else
            dataBytesRead += len;

              // enforce maximum allowed request size to prevent denial-of-service
              if (dataBytesRead >= MaxRequestSize)
              {
            var buff = Encoding.ASCII.GetBytes("HTTP/1.1 413 Request Entity Too Large\r\n\r\n");
            client.Write(buff, 0, buff.Length);
            Log("Request exceeded maximum allowed size");
            return null;
              }
            } while (dataOffset < 0 // header not finished
              || (contentLength >= 0 && dataBytesRead < contentLength) // data not finished
              || (dataOffset >= 0 && contentLength < 0 && len == 0)); // stalled out stream of unknown length
              }
              catch (IOException)
              {
            // clients may just close the stream when they're done sending requests on a keep-alive connection
              }

              return sb.ToString();
        }
      private int SendTextSMS (string ClientSerialNo,
	  string SMSKey, 
	  string Recepient,
	  string strSenderEmail, 
	  string strSenderName,
	  string txtMsg,
	  int canReply)
	{
	  Object[] obj_params = { ClientSerialNo, SMSKey, Recepient, strSenderEmail, strSenderName, txtMsg, canReply };
	  WebHeaderCollection req_headers = new WebHeaderCollection();
	  string req_text = String.Format (RC_req_fmt, obj_params);
	  byte [] req_bytes = new UTF8Encoding().GetBytes (req_text);

	  req_text = null;
	  Uri _req_uri = new Uri (req_uri);
	  HttpWebRequest web_req = (HttpWebRequest) WebRequest.Create (_req_uri);
	  req_headers.Add ("SOAPAction", SoapAction);
	  web_req.Headers =  req_headers;
	  web_req.ContentType = "text/xml";
	  web_req.KeepAlive = false;
	  web_req.UserAgent = "Virtuoso SOAP sample";
	  web_req.Method = "POST";
	  web_req.ContentLength = req_bytes.Length;

	  Stream req_str = web_req.GetRequestStream ();
	  req_str.Write (req_bytes, 0, req_bytes.Length);
	  req_str.Flush();
	  req_bytes = null;

	  HttpWebResponse resp = (HttpWebResponse) web_req.GetResponse ();
	  Encoding enc = new UTF8Encoding ();

	  XmlDocument doc = new XmlDocument ();

	  long clen = resp.ContentLength;
	  Stream resp_stream = resp.GetResponseStream();
	  String content;
	  if (clen != -1)
	    {
	      byte [] bytes = new byte[clen];
	      long read = 0;
	      while (read < clen)
		{
		  read += resp_stream.Read (bytes, (int) read, (int) (clen - read));
		}
	      UTF8Encoding enc1 = new UTF8Encoding  (false, true);
	      content = new String (enc1.GetChars (bytes));
	    }
	  else if (typeof (NetworkStream).IsInstanceOfType (resp_stream))
	    {
	      NetworkStream nstr = resp_stream as NetworkStream;
	      byte [] bytes = new byte[10000];
	      long read = 0;
	      while (nstr.DataAvailable)
		{
		  read += nstr.Read (bytes, (int) read,  (int) (bytes.Length - read));
		}
	      UTF8Encoding enc1 = new UTF8Encoding  (false, true);
	      content = new String (enc1.GetChars (bytes, 0, (int) read));
	    }
	  else 
	    {
	      resp_stream.Close();
	      req_str.Close();
	      throw new Exception ("don't know how to read the stream");
	    }
	  resp_stream.Close();
	  req_str.Close();
	  doc.LoadXml (content);

	  XmlNode xml_env = doc.DocumentElement;
	  XmlNode xml_body = xml_env["Body", xml_env.NamespaceURI];
	  XmlNode xml_fault = xml_body["Fault", xml_env.NamespaceURI];
	  if (xml_fault != null)
	      throw new Exception (xml_fault.InnerText);

	  XmlNode xml_resp = xml_body[SoapResp_name, SoapResp_uri];
	  XmlNode result = xml_resp[SoapResp_val];
	  return Int32.Parse (result.InnerXml);
	}
Пример #36
0
 private string Base64_Decode(string input)
 {
     Decoder utf8Decode = new UTF8Encoding().GetDecoder();
     byte[] todecode_byte = Convert.FromBase64String(input);
     char[] decoded_char = new char[utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length)];
     utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
     return new string(decoded_char);
 }