Пример #1
0
        public PythonEncoding(Encoding encoding, PythonEncoderFallback encoderFallback, PythonDecoderFallback decoderFallback)
        //: base(0, encoderFallback, decoderFallback)  // unfortunately, this constructor is internal until .NET Framework 4.6
        {
            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }
            if (encoderFallback == null)
            {
                throw new ArgumentNullException(nameof(encoderFallback));
            }
            if (decoderFallback == null)
            {
                throw new ArgumentNullException(nameof(decoderFallback));
            }

            byte[] markerBytes = encoding.GetBytes(new[] { Pass1Marker });
            CharacterWidth = markerBytes.Length;
            IsBigEndian    = markerBytes[0] == 0;

            // set up pass 1 Encoding, using provided fallback instances
            encoderFallback.Encoding      = decoderFallback.Encoding = this;
            encoderFallback.IsPass1       = decoderFallback.IsPass1 = true;
            Pass1Encoding                 = (Encoding)encoding.Clone();
            Pass1Encoding.EncoderFallback = encoderFallback;
            Pass1Encoding.DecoderFallback = decoderFallback;

            // set up pass 2 Encoding, using clones of provided fallback instances
            encoderFallback               = (PythonEncoderFallback)encoderFallback.Clone();
            decoderFallback               = (PythonDecoderFallback)decoderFallback.Clone();
            encoderFallback.IsPass1       = decoderFallback.IsPass1 = false;
            Pass2Encoding                 = (Encoding)encoding.Clone();
            Pass2Encoding.EncoderFallback = encoderFallback;
            Pass2Encoding.DecoderFallback = decoderFallback;
        }
Пример #2
0
        private string GetTokenFromBase64String(string base54string)
        {
            byte[] credentialBytes;
            try
            {
                credentialBytes = Convert.FromBase64String(base54string);
                Encoding encoding = Encoding.ASCII;
                // Make a writable copy of the encoding to enable setting a decoder fallback.
                encoding = (Encoding)encoding.Clone();
                // Fail on invalid bytes rather than silently replacing and continuing.
                encoding.DecoderFallback = DecoderFallback.ExceptionFallback;
                string token = encoding.GetString(credentialBytes);

                if (String.IsNullOrEmpty(token))
                {
                    return(string.Empty);
                }
                else
                {
                    return(token);
                }
            }
            catch {
                return(string.Empty);
            }
        }
Пример #3
0
        private static PythonTuple DoEncode(Encoding encoding, object input, string errors, bool includePreamble)
        {
            // input should be some Unicode object
            string res;

            if (Converter.TryConvertToString(input, out res))
            {
                StringBuilder sb = new StringBuilder();

                encoding = (Encoding)encoding.Clone();

#if FEATURE_ENCODING // EncoderFallback
                encoding.EncoderFallback = EncoderFallback.ExceptionFallback;
#endif

                if (includePreamble)
                {
                    byte[] preamble = encoding.GetPreamble();
                    for (int i = 0; i < preamble.Length; i++)
                    {
                        sb.Append((char)preamble[i]);
                    }
                }

                byte[] bytes = encoding.GetBytes(res);
                for (int i = 0; i < bytes.Length; i++)
                {
                    sb.Append((char)bytes[i]);
                }
                return(PythonTuple.MakeTuple(sb.ToString(), res.Length));
            }
            throw PythonOps.TypeErrorForBadInstance("cannot decode {0}", input);
        }
Пример #4
0
        public string UncodePassword(byte[] cryptedPassword)
        {
            Encoding encoding = Encoding.ASCII;

            encoding = (Encoding)encoding.Clone();

            encoding.DecoderFallback = DecoderFallback.ExceptionFallback;
            string decodedCredentials;

            try
            {
                decodedCredentials = encoding.GetString(cryptedPassword);
            }
            catch (DecoderFallbackException)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(decodedCredentials))
            {
                return(null);
            }


            return(decodedCredentials);
        }
Пример #5
0
    public void GetLastAccount(string deviceId, int devicePlatform, int deviceType, int deviceUserId, string gamecenterId, int gameId, int socailType, int socialPlatform, int socialUserId)
    {
        Encoding e = Encoding.GetEncoding("UTF-8");

        e.Clone();
        byte[] pGCId     = e.GetBytes(gamecenterId);
        byte[] pTempGCId = new byte[pGCId.Length + 10];
        int    jj        = 0;

        for (jj = 0; jj < pGCId.Length; jj++)
        {
            pTempGCId[jj] = pGCId[jj];
        }
        pTempGCId[jj] = 0;

        Encoding ee = Encoding.GetEncoding("UTF-8");

        ee.Clone();
        byte[] pDeviceId     = ee.GetBytes(deviceId);
        byte[] pTempDeviceId = new byte[pDeviceId.Length + 10];
        int    ii            = 0;

        for (ii = 0; ii < pDeviceId.Length; ii++)
        {
            pTempDeviceId[ii] = pDeviceId[ii];
        }
        pTempDeviceId[ii] = 0;

        getLastAccount(pTempDeviceId, devicePlatform, getLastType(deviceType), deviceUserId, pTempGCId, gameId, getLastType(socailType), socialPlatform, socialUserId);
    }
        private static void TextEncodingRoundrip(Encoding encoding)
        {
            using var stream = new MemoryStream();

            using (var writer = new ObjectWriter(stream, leaveOpen: true))
            {
                SerializerService.WriteTo(encoding, writer, CancellationToken.None);
            }

            stream.Position = 0;

            using var reader = ObjectReader.TryGetReader(stream);
            Assert.NotNull(reader);
            var actualEncoding   = (Encoding)SerializerService.ReadEncodingFrom(reader, CancellationToken.None).Clone();
            var expectedEncoding = (Encoding)encoding.Clone();

            // set the fallbacks to the same instance so that equality comparison does not take them into account:
            actualEncoding.EncoderFallback   = EncoderFallback.ExceptionFallback;
            actualEncoding.DecoderFallback   = DecoderFallback.ExceptionFallback;
            expectedEncoding.EncoderFallback = EncoderFallback.ExceptionFallback;
            expectedEncoding.DecoderFallback = DecoderFallback.ExceptionFallback;

            Assert.Equal(expectedEncoding.GetPreamble(), actualEncoding.GetPreamble());
            Assert.Equal(expectedEncoding.CodePage, actualEncoding.CodePage);
            Assert.Equal(expectedEncoding.WebName, actualEncoding.WebName);
            Assert.Equal(expectedEncoding, actualEncoding);
        }
Пример #7
0
        private static Tuple <Bytes, int> DoEncode(Encoding encoding, object input, string errors = "strict", bool includePreamble = false)
        {
            // input should be some Unicode object
            if (Converter.TryConvertToString(input, out string str))
            {
                encoding = (Encoding)encoding.Clone();

#if FEATURE_ENCODING // EncoderFallback
                encoding.EncoderFallback = EncoderFallback.ExceptionFallback;
#endif

                byte[] bytes = encoding.GetBytes(str);

                if (!includePreamble)
                {
                    return(Tuple.Create(Bytes.Make(bytes), str.Length));
                }

                MemoryStream sb       = new MemoryStream();
                byte[]       preamble = encoding.GetPreamble();
                sb.Write(preamble, 0, preamble.Length);
                sb.Write(bytes, 0, bytes.Length);

                return(Tuple.Create(Bytes.Make(sb.ToArray()), str.Length));
            }
            throw PythonOps.TypeErrorForBadInstance("cannot decode {0}", input);
        }
 internal CsvReaderSettings Clone()
 {
     var clone = MemberwiseClone() as CsvReaderSettings;
     clone.Readonly = false;
     clone.Encoding = Encoding == null ? null : Encoding.Clone() as Encoding;
     return clone;
 }
Пример #9
0
        public static Encoding WithFatalFallback(this Encoding enc)
        {
            var encoding = enc.Clone() as Encoding;

            encoding.EncoderFallback = EncoderFallback.ExceptionFallback;
            return(encoding);
        }
Пример #10
0
    public bool PosTest1()
    {
        bool retVal = true;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Verify method Clone .");

        try
        {
            Encoding encoding      = Encoding.UTF8;
            Encoding encodingClone = (Encoding)encoding.Clone();

            if (Encoding.ReferenceEquals(encoding, encodingClone) || !Encoding.Equals(encoding, encodingClone))
            {
                TestLibrary.TestFramework.LogError("001.1", "Method Clone Err.");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return(retVal);
    }
Пример #11
0
        public void Clone(Encoding encoding)
        {
            Encoding clone = (Encoding)encoding.Clone();

            Assert.NotSame(encoding, clone);
            Assert.Equal(encoding, clone);
        }
Пример #12
0
    //数据上报函数
    public int StoreUserDefineData(string pData, string pDefaultDataDetail)
    {
        Encoding e = Encoding.GetEncoding("UTF-8");

        e.Clone();
        byte[] pDataName     = e.GetBytes(pData);
        byte[] pTempDataName = new byte[pDataName.Length + 10];
        int    jj            = 0;

        for (jj = 0; jj < pDataName.Length; jj++)
        {
            pTempDataName[jj] = pDataName[jj];
        }
        pTempDataName[jj] = 0;
        Encoding ee = Encoding.GetEncoding("UTF-8");

        ee.Clone();
        byte[] pDefaultDataDetailName     = ee.GetBytes(pDefaultDataDetail);
        byte[] pTempDefaultDataDetailName = new byte[pDefaultDataDetailName.Length + 10];
        int    ii = 0;

        for (ii = 0; ii < pDefaultDataDetailName.Length; ii++)
        {
            pTempDefaultDataDetailName[ii] = pDefaultDataDetailName[ii];
        }
        pTempDefaultDataDetailName[ii] = 0;

        int state = storeUserDefineData(pTempDataName, pTempDefaultDataDetailName);

        return(state);
    }
Пример #13
0
    //支付操作
    public void DoOfflineOperationByPurchase(string id, string transactionId, int parameter)
    {
        Encoding e = Encoding.GetEncoding("UTF-8");

        e.Clone();
        byte[] pId     = e.GetBytes(id);
        byte[] pTempId = new byte[pId.Length + 10];
        int    jj      = 0;

        for (jj = 0; jj < pId.Length; jj++)
        {
            pTempId[jj] = pId[jj];
        }
        pTempId[jj] = 0;

        Encoding ee = Encoding.GetEncoding("UTF-8");

        ee.Clone();
        byte[] pTransactionId     = ee.GetBytes(transactionId);
        byte[] pTempTransactionId = new byte[pTransactionId.Length + 10];
        int    ii = 0;

        for (ii = 0; ii < pTransactionId.Length; ii++)
        {
            pTempTransactionId[ii] = pTransactionId[ii];
        }
        pTempTransactionId[ii] = 0;

        doOfflineOperationByPurchase(pTempId, pTempTransactionId, parameter);
    }
Пример #14
0
        private static Tuple DoEncode(Encoding encoding, object input, string errors, bool includePreamble)
        {
            // input should be some Unicode object
            Conversion conv;
            string     res = Converter.TryConvertToString(input, out conv);

            if (conv != Conversion.None)
            {
                StringBuilder sb = new StringBuilder();

                encoding = (Encoding)encoding.Clone();
                encoding.EncoderFallback = EncoderFallback.ExceptionFallback;

                if (includePreamble)
                {
                    byte[] preamble = encoding.GetPreamble();
                    for (int i = 0; i < preamble.Length; i++)
                    {
                        sb.Append((char)preamble[i]);
                    }
                }

                byte[] bytes = encoding.GetBytes(res);
                for (int i = 0; i < bytes.Length; i++)
                {
                    sb.Append((char)bytes[i]);
                }
                return(Tuple.MakeTuple(sb.ToString(), res.Length));
            }
            throw Ops.TypeError("cannot decode {0}", Ops.GetDynamicType(input).__name__);
        }
Пример #15
0
        private static Encoding GetEncodingWithFallback(Encoding encoding)
        {
            Encoding replacementFallback = (Encoding)encoding.Clone();

            replacementFallback.EncoderFallback = EncoderFallback.ReplacementFallback;
            replacementFallback.DecoderFallback = DecoderFallback.ReplacementFallback;
            return(replacementFallback);
        }
Пример #16
0
        private static Encoding GetEncodingWithFallback(Encoding encoding)
        {
            Encoding copy = (Encoding)encoding.Clone();

            copy.EncoderFallback = EncoderFallback.ReplacementFallback;
            copy.DecoderFallback = DecoderFallback.ReplacementFallback;
            return(copy);
        }
Пример #17
0
        private static Encoding GetEncodingWithFallback(Encoding encoding)
        {
            Encoding encoding2 = (Encoding)encoding.Clone();

            encoding2.EncoderFallback = EncoderFallback.ReplacementFallback;
            encoding2.DecoderFallback = DecoderFallback.ReplacementFallback;
            return(encoding2);
        }
Пример #18
0
		Encoding GetEncoding(Encoding encoding) {
			var clone = (Encoding)encoding.Clone();
			Debug.Assert(!clone.IsReadOnly);
			if (clone.IsReadOnly)
				return encoding;
			clone.EncoderFallback = new EncoderReplacementFallback("\uFFFD");
			clone.DecoderFallback = new DecoderReplacementFallback("\uFFFD");
			return clone;
		}
Пример #19
0
        private static PythonTuple DoDecode(Encoding encoding, object input, string errors, bool fAlwaysThrow)
        {
            // input should be character buffer of some form...
            string res;

            if (!Converter.TryConvertToString(input, out res))
            {
                Bytes tempBytes = input as Bytes;
                if (tempBytes == null)
                {
                    throw PythonOps.TypeErrorForBadInstance("argument 1 must be string, got {0}", input);
                }
                else
                {
                    res = tempBytes.ToString();
                }
            }

            int preOffset = CheckPreamble(encoding, res);

            byte[] bytes = new byte[res.Length - preOffset];
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = (byte)res[i + preOffset];
            }

#if !SILVERLIGHT    // DecoderFallback
            encoding = (Encoding)encoding.Clone();

            ExceptionFallBack fallback = null;
            if (fAlwaysThrow)
            {
                encoding.DecoderFallback = DecoderFallback.ExceptionFallback;
            }
            else
            {
                fallback = new ExceptionFallBack(bytes);
                encoding.DecoderFallback = fallback;
            }
#endif
            string decoded      = encoding.GetString(bytes, 0, bytes.Length);
            int    badByteCount = 0;

#if !SILVERLIGHT    // DecoderFallback
            if (!fAlwaysThrow)
            {
                byte[] badBytes = fallback.buffer.badBytes;
                if (badBytes != null)
                {
                    badByteCount = badBytes.Length;
                }
            }
#endif

            PythonTuple tuple = PythonTuple.MakeTuple(decoded, bytes.Length - badByteCount);
            return(tuple);
        }
Пример #20
0
            // This is defined in TWTL as well, we should look into refactoring/relayering at a later time
            private static Encoding GetEncodingWithFallback(Encoding encoding)
            {
                // Clone it and set the "?" replacement fallback
                Encoding fallbackEncoding = (Encoding)encoding.Clone();

                fallbackEncoding.EncoderFallback = EncoderFallback.ReplacementFallback;
                fallbackEncoding.DecoderFallback = DecoderFallback.ReplacementFallback;

                return(fallbackEncoding);
            }
Пример #21
0
        private static Encoding GetEncodingWithFallback(Encoding encoding)
        {
            // Clone it and set the "?" replacement fallback
            var result = (Encoding)encoding.Clone();

            result.EncoderFallback = EncoderFallback.ReplacementFallback;
            result.DecoderFallback = DecoderFallback.ReplacementFallback;

            return(result);
        }
Пример #22
0
        public PythonSurrogateEscapeEncoding(Encoding encoding)
        {
            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            byte[] markerBytes = encoding.GetBytes(new[] { Pass1SurrogateMarker });
            CharacterWidth = markerBytes.Length;
            IsBigEndian    = markerBytes[0] == 0;

            Pass1Encoding = (Encoding)encoding.Clone();
            Pass1Encoding.DecoderFallback = new SurrogateEscapeDecoderFallback(isPass1: true, CharacterWidth, IsBigEndian);
            Pass1Encoding.EncoderFallback = new SurrogateEscapeEncoderFallback(isPass1: true);

            Pass2Encoding = (Encoding)encoding.Clone();
            Pass2Encoding.DecoderFallback = new SurrogateEscapeDecoderFallback(isPass1: false, CharacterWidth, IsBigEndian);
            Pass2Encoding.EncoderFallback = new SurrogateEscapeEncoderFallback(isPass1: false);
        }
Пример #23
0
        private static Tuple <string, string> ExtractUserNameAndPassword(string authorizationParameter)
        {
            byte[] credentialBytes;

            try
            {
                credentialBytes = Convert.FromBase64String(authorizationParameter);
            }
            catch (FormatException e)
            {
                Trace.TraceWarning($"Unable to extract authentication header: {e}");
                return(null);
            }

            // The currently approved HTTP 1.1 specification says characters here are ISO-8859-1.
            // However, the current draft updated specification for HTTP 1.1 indicates this encoding is infrequently
            // used in practice and defines behavior only for ASCII.
            Encoding encoding = Encoding.ASCII;

            // Make a writable copy of the encoding to enable setting a decoder fallback.
            encoding = (Encoding)encoding.Clone();

            // Fail on invalid bytes rather than silently replacing and continuing.
            encoding.DecoderFallback = DecoderFallback.ExceptionFallback;
            string decodedCredentials;

            try
            {
                decodedCredentials = encoding.GetString(credentialBytes);
            }
            catch (DecoderFallbackException e)
            {
                Trace.TraceWarning($"Unable to decode authentication header: {e}");
                return(null);
            }

            if (string.IsNullOrEmpty(decodedCredentials))
            {
                Trace.TraceWarning($"Unable to find authentication header");
                return(null);
            }

            int colonIndex = decodedCredentials.IndexOf(':');

            if (colonIndex == -1)
            {
                Trace.TraceWarning($"Unable to find colon in authentication header");
                return(null);
            }

            string userName = decodedCredentials.Substring(0, colonIndex);
            string password = decodedCredentials.Substring(colonIndex + 1);

            return(new Tuple <string, string>(userName, password));
        }
Пример #24
0
        private static Encoding Clone(Encoding encoding)
        {
            // encodings have to be cloned to change the EncoderFallback property later

#if !NETSTANDARD1_0 && !NETSTANDARD1_1 && !PORTABLE && !NETFX_CORE
            // Clone isn't supported by .net standard 1.0, 1.1 and portable
            return((Encoding)encoding.Clone());
#else
            return(encoding);
#endif
        }
Пример #25
0
        public static Credentials ParseCredentials(string authorizationString)
        {
            byte[] credentialBytes;

            try
            {
                credentialBytes = Convert.FromBase64String(authorizationString);
            }
            catch (FormatException)
            {
                return(null);
            }

            // The currently approved HTTP 1.1 specification says characters here are ISO-8859-1.
            // However, the current draft updated specification for HTTP 1.1 indicates this encoding is infrequently
            // used in practice and defines behavior only for ASCII.
            Encoding encoding = Encoding.ASCII;

            // Make a writable copy of the encoding to enable setting a decoder fallback.
            encoding = (Encoding)encoding.Clone();
            // Fail on invalid bytes rather than silently replacing and continuing.
            encoding.DecoderFallback = DecoderFallback.ExceptionFallback;
            string decodedCredentials;

            try
            {
                decodedCredentials = encoding.GetString(credentialBytes);
            }
            catch (DecoderFallbackException)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(decodedCredentials))
            {
                return(null);
            }

            var credentials = decodedCredentials.Split(':');

            if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]))
            {
                return(null);
            }

            return(new Credentials()
            {
                Username = credentials[0], Password = credentials[1]
            });
        }
        private static Tuple <string, string> ExtractUserNameAndPassword(string authorizationParameter)
        {
            byte[] credentialBytes;

            try
            {
                // 5.1 Pela especificação desse tipo de autenticação, o usuário e senha devem vir formatados em Base64({usuario}:{senha})
                // Base64 > byte[]
                credentialBytes = Convert.FromBase64String(authorizationParameter);
            }
            catch (FormatException)
            {
                return(null);
            }

            Encoding encoding = Encoding.ASCII;

            encoding = (Encoding)encoding.Clone();
            encoding.DecoderFallback = DecoderFallback.ExceptionFallback;
            string decodedCredentials;

            try
            {
                // byte[] : string
                decodedCredentials = encoding.GetString(credentialBytes);
            }
            catch (DecoderFallbackException)
            {
                return(null);
            }

            if (String.IsNullOrEmpty(decodedCredentials))
            {
                return(null);
            }

            //Inicia o processo de separação do usuário e senha
            int colonIndex = decodedCredentials.IndexOf(':');

            if (colonIndex == -1)
            {
                return(null);
            }

            string userName = decodedCredentials.Substring(0, colonIndex);
            string password = decodedCredentials.Substring(colonIndex + 1);

            return(new Tuple <string, string>(userName, password));
        }
Пример #27
0
        /// <summary>
        /// Reads and converts text from a stream
        /// </summary>
        /// <param name="SourceContent">Text content</param>
        /// <param name="SourceEncoding">Encoding the text is in</param>
        /// <param name="ForceEncoding">Force the encoding (skips UTF-8 check if true)</param>
        /// <returns>C# usable string</returns>
        public static string GetText(Stream SourceContent, Encoding SourceEncoding, bool ForceEncoding)
        {
            Encoding E = null;

            if (!ForceEncoding && SourceEncoding.CodePage != Encoding.UTF8.CodePage && IsUtf8(SourceContent))
            {
                E = Encoding.UTF8;
            }
            else
            {
                E = (Encoding)SourceEncoding.Clone();
            }

            return(E.GetString(SourceContent.GetBytes()));
        }
Пример #28
0
        /// <summary>
        /// Creates a clone of this instance.
        /// </summary>
        /// <returns>A clone of the instance.</returns>
        protected override ConfigurationElement DoClone()
        {
            CodeConfiguration clone = new CodeConfiguration();

            clone._encoding   = Encoding.Clone() as EncodingConfiguration;
            clone._formatting = Formatting.Clone() as FormattingConfiguration;

            foreach (HandlerConfiguration handler in Handlers)
            {
                HandlerConfiguration handlerClone = handler.Clone() as HandlerConfiguration;
                clone.Handlers.Add(handlerClone);
            }

            return(clone);
        }
Пример #29
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TextFileReader"/> class.
        /// </summary>
        /// <param name="filePath">The path to text file.</param>
        /// <param name="encoding">The encoding of text file.</param>
        public TextFileLineReader(string filePath, Encoding encoding)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException("File (" + filePath + ") is not found.");
            }

            var safeEncoding = (Encoding)encoding.Clone();

            safeEncoding.DecoderFallback = new DecoderReplacementFallback("");

            _fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            _length     = _fileStream.Length;
            _binReader  = new BinaryReader(_fileStream, safeEncoding);
        }
Пример #30
0
    public void GetGamecenterData(Int32 gameId, string gamecenterId, Int32 gcPlatform, Int32 gcType)
    {
        Encoding e = Encoding.GetEncoding("UTF-8");

        e.Clone();
        byte[] pId     = e.GetBytes(gamecenterId);
        byte[] pTempId = new byte[pId.Length + 10];
        int    jj      = 0;

        for (jj = 0; jj < pId.Length; jj++)
        {
            pTempId[jj] = pId[jj];
        }
        pTempId[jj] = 0;
        getGamecenterData(gameId, pTempId, gcPlatform, getLastType(gcType));
    }
Пример #31
0
 public void Clone(Encoding encoding)
 {
     Encoding clone = (Encoding)encoding.Clone();
     Assert.NotSame(encoding, clone);
     Assert.Equal(encoding, clone);
 }