GetString() публичный Метод

public GetString ( byte bytes, int index, int count ) : string
bytes byte
index int
count int
Результат string
        public decimal GetConvertion(string from, string to)
        {
            WebClient objWebClient = null;
            UTF8Encoding objUTF8 = null;
            decimal result = 0;

            try{
                objWebClient = new WebClient();
                objUTF8 = new UTF8Encoding();

                byte[] aRequestedHTML = objWebClient.DownloadData(String.Format("http://www.xe.com/ucc/convert/?Amount=1&From={0}&To={1}", from, to));
                string strRequestedHTML = objUTF8.GetString(aRequestedHTML);

                int search1 = strRequestedHTML.LastIndexOf("&nbsp;<span class=\"uccResCde\">USD</span>");
                string search2 = strRequestedHTML.Substring(search1 - 21, 21);
                int search3 = search2.LastIndexOf(">");
                string stringRepresentingCE = search2.Substring(search3 + 1);

                result = Convert.ToDecimal(stringRepresentingCE.Trim());

            }
            catch (Exception ex){
                // Agregar codigo para manejar la excepción.
            }

            return result;
        }
Пример #2
1
        public static NameValueCollection Parse(Stream stream)
        {
            Dictionary<string, string[]> form = new Dictionary<string, string[]>();
            UTF8Encoding encoding = new UTF8Encoding(false);

            return HttpUtility.ParseQueryString(encoding.GetString(stream.ReadAllBytes()),encoding);
        }
Пример #3
1
 public static string GetSha1Hash(this string value)
 {
     var encoding = new UTF8Encoding();
     var hash = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     var hashed = hash.ComputeHash(encoding.GetBytes(value));
     return encoding.GetString(hashed);
 }
Пример #4
1
        /// <summary>
        /// Base64 Decode
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        public static string Base64Decode(string src)
        {
            string sReturn = "";

            if (src != "")
            {
                byte[] arr = null;
                UTF8Encoding uniEnc = null;

                try
                {
                    uniEnc = new UTF8Encoding();
                    arr = Convert.FromBase64String(src);
                    sReturn = uniEnc.GetString(arr);
                }
                catch
                {
                }
                finally
                {
                    uniEnc = null;
                }
            }
            return sReturn;
        }
Пример #5
1
        protected string Encode(string value)
        {
            UTF8Encoding encoding = new UTF8Encoding();

            switch (_DataType.Encoding)
            {
                case "BASE64": return Convert.ToBase64String(encoding.GetBytes(value));
                case "7BIT":
                case "8BIT":                
                    value = Regex.Replace(value, @"[^\r]\n", "\r\n");
                    value = Regex.Replace(value, @"\r[^\n]", "\r\n");

                    bool is7Bit = _DataType.Encoding.Equals("7BIT");

                    List<byte> data = new List<byte>(encoding.GetBytes(value));
                    for (int i = data.Count - 1; i >= 0; i--)
                    {
                        if (data[i] == 0)
                            data.RemoveAt(i);

                        if (is7Bit && data[i] > 127)
                            data.RemoveAt(i);
                    }

                    return encoding.GetString(data.ToArray());
                default:
                    return value;
            }
        }
Пример #6
0
        private static async Task<int> Run(int port) {
            using (var client = new TcpClient()) {
                await client.ConnectAsync(IPAddress.Loopback, port);

                var utf8 = new UTF8Encoding(false);
                using (var reader = new StreamReader(client.GetStream(), utf8, false, 4096, true))
                using (var writer = new StreamWriter(client.GetStream(), utf8, 4096, true)) {
                    var filename = await reader.ReadLineAsync();
                    var args = (await reader.ReadLineAsync()).Split('|')
                        .Select(s => utf8.GetString(Convert.FromBase64String(s)))
                        .ToList();
                    var workingDir = await reader.ReadLineAsync();
                    var env = (await reader.ReadLineAsync()).Split('|')
                        .Select(s => s.Split(new[] { '=' }, 2))
                        .Select(s => new KeyValuePair<string, string>(s[0], utf8.GetString(Convert.FromBase64String(s[1]))))
                        .ToList();
                    var outputEncoding = await reader.ReadLineAsync();
                    var errorEncoding = await reader.ReadLineAsync();

                    return await ProcessOutput.Run(
                        filename,
                        args,
                        workingDir,
                        env,
                        false,
                        new StreamRedirector(writer, outputPrefix: "OUT:", errorPrefix: "ERR:"),
                        quoteArgs: false,
                        elevate: false,
                        outputEncoding: string.IsNullOrEmpty(outputEncoding) ? null : Encoding.GetEncoding(outputEncoding),
                        errorEncoding: string.IsNullOrEmpty(errorEncoding) ? null : Encoding.GetEncoding(errorEncoding)
                    );
                }
            }
        }
    void DealWithMatchData(GP_TBM_Match match)
    {
        mMatch = match;
        // Common.DebugPopUp("Dealing with match nata", "Participant info " + mMatch.PendingParticipantId);
        if (mMatch.Data != null)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            string stringData = encoding.GetString(mMatch.Data, 0, mMatch.Data.Length);
            if (stringData.Length > 10)
            {
                Common.roundInformation.SetNewGameDataFromGooglePlay(mMatch.Data);
                // AndroidMessage.Create("match data not empty", "it is  " + stringData);
                StartDoingTurn(mMatch);
                CreateParticipantUI();
                return;
            }
        }

        // Otherwise, this is the first player. Initialize the game state.
        initGame(mMatch);


        // Let the player take the first turn
        StartDoingTurn(mMatch);
        CreateParticipantUI();
        //SetGameStateBased on gameState
    }
Пример #8
0
        public static string GetDecryptedText(string EncryptedString)
        {
            string sdec = "";
            try
            {
                string smsg = EncryptedString;

                DESCryptoServiceProvider des = new DESCryptoServiceProvider();

                System.Text.Encoding utf = new System.Text.UTF8Encoding();

                byte[] key = utf.GetBytes("12348765");
                byte[] iv ={ 1, 2, 3, 4, 8, 7, 6, 5 };

                ICryptoTransform decryptor = des.CreateDecryptor(key, iv);

                byte[] bmsg = utf.GetBytes(smsg);

                byte[] benc1 = System.Convert.FromBase64String(EncryptedString);
                byte[] bdec = decryptor.TransformFinalBlock(benc1, 0, benc1.Length);
                sdec = utf.GetString(bdec);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
            return sdec;
        }
Пример #9
0
        public string DecodeFromFile(string fileName)
        {
            string keyData = "";
            UTF8Encoding utf = new UTF8Encoding();
            Rijndael rjn = Rijndael.Create();
            Byte[] decIV = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255 };
            Byte[] decKey = { 0x3, 0x6, 0x9, 0x12, 0x15, 0x18, 0x21, 0x24, 0x27, 0x30, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
            rjn.IV = decIV;
            rjn.Key = decKey;
            ICryptoTransform decoder = rjn.CreateDecryptor(decIV, decKey);

            FileStream fOpen = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Read);
            Byte[] encBinData = new Byte[16];
            Byte[] decBinData;
            int i =0;
            for (i = 0; i < fOpen.Length; i += 16)
            {
                fOpen.Seek((long)i, SeekOrigin.Begin);
                fOpen.Read(encBinData, 0, 16);
                decBinData = decoder.TransformFinalBlock(encBinData, 0, encBinData.Length);
                keyData += utf.GetString(decBinData);
            }
            fOpen.Close();
            return keyData;
        }
        public static decimal[] getCoordinates(string address1, string address2,
            string city, string state, string zipcode, string appId)
        {
            string retVal;
            decimal[] coordinates = new decimal[2];

            System.Net.WebClient webClient = new System.Net.WebClient();
            string request = "http://where.yahooapis.com/geocode?location="
                + address1 + "+" + address2 + "+" + city + "+" + state + "+" + zipcode
                + "&" + appId;

            byte[] responseXML;
            try
            {
                responseXML = webClient.DownloadData(request);
                System.Text.UTF8Encoding objUTF8 = new System.Text.UTF8Encoding();
                retVal = objUTF8.GetString(responseXML) + "\n";
            }
            catch (System.Exception ex)
            {
                retVal = ex.Message;
            }

            // parse the return values
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(retVal);
            XmlNode ndLatitude = xml.SelectSingleNode("//latitude");
            XmlNode ndLongitude = xml.SelectSingleNode("//longitude");

            coordinates[0] = Convert.ToDecimal(ndLatitude.InnerText);
            coordinates[1] = Convert.ToDecimal(ndLongitude.InnerText);

            return coordinates;
        }
Пример #11
0
        static string read_text(string path)
        {
            var bytes = File.ReadAllBytes(path);
            var encoding = new UTF8Encoding();

            return encoding.GetString(bytes);
        }
Пример #12
0
        public static String GenerateNonce()
        {
            List<byte> allowedChars = new List<byte> (62);
              foreach (byte n in Enumerable.Range (48, 10)) {
            allowedChars.Add (n);
              }

              foreach (byte n in Enumerable.Range (65, 26)) {
            allowedChars.Add (n);
              }

              foreach (byte n in Enumerable.Range (97, 26)) {
            allowedChars.Add (n);
              }

              RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider ();
              List<Byte> nonceList = new List<Byte> (32);
              int i = 1;
              do {
            byte[] b = new byte[1];
            rng.GetBytes (b);
            byte bt = b[0];
            if (allowedChars.Contains (bt)) {
              nonceList.Add (bt);
              i++;
            }
              } while (i <= 32);

              UTF8Encoding encoder = new UTF8Encoding ();
              return encoder.GetString (nonceList.ToArray ());
        }
Пример #13
0
		public IEnumerable<Task> Can_put_and_get_an_attachment()
		{
			var store = new DocumentStore {Url = Url + Port};
			store.Initialize();

			var dbname = GenerateNewDatabaseName();
			yield return store.AsyncDatabaseCommands.EnsureDatabaseExistsAsync(dbname);

			const string someData = "The quick brown fox jumps over the lazy dog";
			var encoding = new UTF8Encoding();
			var bytes = encoding.GetBytes(someData);

			yield return store.AsyncDatabaseCommands
				.ForDatabase(dbname)
				.PutAttachmentAsync("123", Guid.Empty, bytes, null);

			var get = store.AsyncDatabaseCommands
				.ForDatabase(dbname)
				.GetAttachmentAsync("123");
			yield return get;
			
			var returnedBytes = get.Result.Data().ReadData(); 
			var returned = encoding.GetString(returnedBytes,0,returnedBytes.Length);

			Assert.AreEqual(someData, returned);
		}
        private static string RequestGetToUrl(string url)
        {
            WebProxy proxy = WebProxy.GetDefaultProxy();
            if (string.IsNullOrEmpty(url))
                return null;

            if (url.IndexOf("://") <= 0)
                url = "http://" + url.Replace(",", ".");

            try
            {
                using (var client = new WebClient())
                {
                    //proxy
                    if (proxy != null)
                        client.Proxy = proxy;

                    //response
                    byte[] response = client.DownloadData(url);
                    //out
                    var enc = new UTF8Encoding();
                    string outp = enc.GetString(response);
                    return outp;
                }
            }
            catch (WebException ex)
            {
                string err = ex.Message;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
            }
            return null;
        }
Пример #15
0
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "MP3 File (*.mp3)|*.mp3;";
            if (open.ShowDialog() != DialogResult.OK) return;

            TrimMp3(open.FileName, "temp.mp3", TimeSpan.FromSeconds(Int32.Parse(textBox1.Text)), TimeSpan.FromSeconds(Int32.Parse(textBox1.Text)+15));

            string path = "chgk.mp3";
            using (FileStream fs = File.Open(path, FileMode.Open))
            {
                byte[] b = new byte[1024];
                UTF8Encoding temp = new UTF8Encoding(true);

                while (fs.Read(b, 0, b.Length) > 0)
                {
                    textBox1.Text += (temp.GetString(b));
                }
            }

            string[] toMerge = { path, "temp.mp3" };
            FileStream t = File.Create("chgk_"+textBox2.Text+".mp3");
            Combine(toMerge, t);
            for (int i = 0; i < 100; i++)
            {
                progressBar1.Value++;
                System.Threading.Thread.Sleep(30);
            }
            t.Close();
        }
    public static string DecryptData(string Message)
    {
        byte[] Results;
        System.Text.UTF8Encoding UTF8         = new System.Text.UTF8Encoding();
        MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

        byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
        TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

        TDESAlgorithm.Key     = TDESKey;
        TDESAlgorithm.Mode    = CipherMode.ECB;
        TDESAlgorithm.Padding = PaddingMode.PKCS7;
        byte[] DataToDecrypt = Convert.FromBase64String(Message);
        try
        {
            ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
            Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
        }
        finally
        {
            TDESAlgorithm.Clear();
            HashProvider.Clear();
        }
        return(UTF8.GetString(Results));
    }
Пример #17
0
    /*
     * public void read_csv(string path) {
     *  var starlist = new System.Collections.Generic.List<star>();
     *  path = Path.Combine(path, "star\\star.csv");
     *  using(var sr = new StreamReader(new FileStream(path, System.IO.FileMode.Open))) {
     *      string line;
     *      line = sr.ReadLine();
     *      if(line != EXPECTED_LINE)
     *          throw new Exception("wrong first line");
     *      while((line = sr.ReadLine()) != null) {
     *          star s = new star(line);
     *          starlist.Add(s);
     *      }
     *  }
     *  stars = starlist.ToArray();
     *  Debug.Log(String.Format("{0} stars", starlist.Count));
     * }
     */

    public void read_dat(string path)
    {
        var        starlist      = new System.Collections.Generic.List <star>();
        string     path1         = Path.Combine(path, "star\\star.dat");
        string     path2         = Path.Combine(path, "star\\star.string");
        FileStream fs            = File.OpenRead(path2);
        var        unicodeencode = new System.Text.UTF8Encoding();
        Func <UInt32, UInt32, string> getstring = delegate(UInt32 offset, UInt32 length) {
            fs.Seek(offset, SeekOrigin.Begin);
            byte[] str = new byte[length];
            fs.Read(str, 0, checked ((int)length));
            return(unicodeencode.GetString(str));
        };

        using (var br = new BinaryReader(new FileStream(path1, System.IO.FileMode.Open))) {
            try {
                while (true)
                {
                    star s = star.makestar(br, getstring);
                    starlist.Add(s);
                    GameDad.starprogress++;
                }
            }
            catch (EndOfStreamException) {}
        }
        stars = starlist.ToArray();
        Debug.Log(String.Format("{0} stars", starlist.Count));
    }
Пример #18
0
        static void getApiKey()
        {
            string path = ".apikey";

            if (!File.Exists(path))
            {
                using (FileStream fs = File.Create(path))
                {

                    var NewApiKey = "";
                    Console.WriteLine(@"There is no steam API key set. To get an api key, vist https://steamcommunity.com/dev/apikey.");

                    while (NewApiKey.Length != 32)
                    {
                        Console.WriteLine("Please enter your API key : ");
                        NewApiKey = Console.ReadLine();
                        if (NewApiKey.Length != 32)
                            Console.WriteLine("Your API key is invalid, please enter a valid 32 character API key.");
                    }

                    AddText(fs, NewApiKey);
                }
            }

            var apikey = "";
            using (var fs = File.Open(".apikey", FileMode.Open, FileAccess.Read))
            {
                byte[] b = new byte[1024];
                UTF8Encoding temp = new UTF8Encoding(true);
                fs.Read(b, 0, b.Length);
                apikey = temp.GetString(b);
            }
            steamApiKey = apikey;
        }
Пример #19
0
        /// <summary>
        /// This returns your IP address by navigating to an online IP reporter website; downloading the string it reports. 
        /// Btw, you can get at the string by GetExternalIp().ToString()
        /// Relys on http://www.whatismyip.com/automation/n09230945.asp working right
        /// </summary>
        /// <returns>returns null if something goes wrong</returns>
        public static IPAddress GetExternalIp()
        {
            string whatIsMyIp = "http://www.whatismyip.com/automation/n09230945.asp";      // this is their special page that simply returns the string consisting of your IP address
            WebClient wc = new WebClient();
            UTF8Encoding utf8 = new UTF8Encoding();
            string requestHtml = "";

            try
            {
                requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
            }
            catch (WebException we)
            {
                // do something with exception
                Console.Write(we.ToString());
            }

            int L1 = requestHtml.Length;    // Get length of IP address
            int L2 = requestHtml.Replace(".", "").Length;  // remove decimal points and get new length

            bool didFindValidIP;
            if (L1 - L2 == 3)       // were there 3 decimal points?  That means it worked!
                didFindValidIP = true;
            else
                didFindValidIP = false;

            IPAddress externalIp = null;
            if (didFindValidIP)
            {
                externalIp = IPAddress.Parse(requestHtml.ToString());
            }
            return externalIp;
        }
Пример #20
0
        /// <summary>
        /// Metho to decrypt a string
        /// </summary>
        /// <param name="cipherText"></param>
        /// <param name="passPhrase"></param>
        /// <returns></returns>
        public static string Decrypt(string cipherText)
        {
            byte[] results;
            System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
            System.Security.Cryptography.MD5CryptoServiceProvider hashProvider = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] TDESKey = hashProvider.ComputeHash(utf8.GetBytes(passCrypto));
            System.Security.Cryptography.TripleDESCryptoServiceProvider TDESAlgorithm = new System.Security.Cryptography.TripleDESCryptoServiceProvider();
            cipherText = cipherText.Replace(" ", "+");
            if (cipherText.Length % 4 > 0)
                cipherText = cipherText.PadRight(cipherText.Length + 4 - cipherText.Length % 4, '=');
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = System.Security.Cryptography.CipherMode.ECB;
            TDESAlgorithm.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
            byte[] dataToDecrypt = Convert.FromBase64String(cipherText);

            try
            {
                System.Security.Cryptography.ICryptoTransform decryptor = TDESAlgorithm.CreateDecryptor();
                results = decryptor.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
            }
            finally
            {
                TDESAlgorithm.Clear();
                hashProvider.Clear();
            }
            return utf8.GetString(results);
        }
		static void Main (string[] args)
		{
			if (args.Length != 1) {
				Console.WriteLine ("Usage: TestAsyncStream <uri>");
				return;
			}
		
			Gnome.Vfs.Vfs.Initialize ();

			VfsStream stream = new VfsStream (args[0], FileMode.Open, true);
			
			UTF8Encoding utf8 = new UTF8Encoding ();
			buffer = new byte[1024];
			int read;
			while ((read = stream.Read (buffer, 0, buffer.Length)) != 0) {
				Console.WriteLine ("read ({0} bytes) : '{1}'",
						   read, utf8.GetString (buffer, 0, read));
			}

			long offset = stream.Seek (0, SeekOrigin.Begin);
			Console.WriteLine ("Offset after seek is {0}", offset);
			
			buffer = new byte[1024];
			IAsyncResult result = stream.BeginRead (buffer, 0, buffer.Length,
								new System.AsyncCallback (OnReadComplete),
								stream);

			loop = new MainLoop ();
			loop.Run ();

			Gnome.Vfs.Vfs.Shutdown ();
		}
Пример #22
0
        public override string ReadLine()
        {
            // max line length in byte 1024

            var enc = new UTF8Encoding();
            int i = 0;
            bool end = false;
            while (!end)
            {
                long cur = _stream.ReadByte();
                switch (cur)
                {
                    case -1:
                        //throw new EndOfStreamException();
                        break;
                    case 10:
                        end = true;
                        break;
                    default:
                        _buffer[i] = (byte)cur;
                        break;
                }
                ++i;
            }
            return enc.GetString(_buffer, 0, i - 1);
        }
Пример #23
0
        /// <summary>
        /// Converts the object to xml string.
        /// </summary>
        /// <param name="obj">The object to be serialized</param>
        /// <param name="toBeIndented"><c>true</c> if wants the xml string was indented, otherwise <c>false</c>.</param>
        /// <returns>The xml string.</returns>
        public static string ObjectToXml(object obj, bool toBeIndented)
        {
            if (null == obj)
            {
                throw new ArgumentNullException("obj");
            }
            UTF8Encoding encoding = new UTF8Encoding(false);
            XmlSerializer serializer = new XmlSerializer(obj.GetType());
            MemoryStream stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, encoding);
            writer.Formatting = (toBeIndented ? Formatting.Indented : Formatting.None);

            try
            {
                serializer.Serialize(writer, obj);
            }
            catch (InvalidOperationException)
            {
                throw new InvalidOperationException("Can not convert object to xml.");
            }
            finally
            {
                writer.Close();
            }
            string xml = encoding.GetString(stream.ToArray());
            return xml;
        }
        public unsafe static string Hex2CharFileName(string hex)
        {
            string ret = hex;

            byte[] char2hex = { 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66 };
            Dictionary<byte, byte> hex2char = new Dictionary<byte, byte>();
            for (byte i = 0; i < 16; ++i)
                hex2char[char2hex[i]] = i;

            string fileExt = Path.GetExtension(hex);
            string fileNameWithoutExt = Path.GetFileNameWithoutExtension(hex);

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] tmp = encoding.GetBytes(fileNameWithoutExt);
            fixed (byte* p_src = &tmp[0])
            {
                byte[] des = new byte[tmp.Length / 2];
                // hex2char
                for (int i = 0; i < des.Length; ++i)
                {
                    byte up = (byte)(hex2char[p_src[2 * i]] << 4);
                    byte low = (hex2char[p_src[2 * i + 1]]);
                    des[i] = (byte)(up | low);
                }
                ret = encoding.GetString(des);
                ret += fileExt;
            }
            return ret;
        }
Пример #25
0
 /// <summary>
 /// Check if a port is open to the world using a port checker
 /// </summary>
 /// <param name="externalIP">IP addrress to probe</param>
 /// <param name="intPortNumber">Port number to check</param>
 /// <returns>boolean indicating if the port is accesible from the outside world</returns>
 public static bool CheckExternalPort(IPAddress externalIP, int intPortNumber)
 {
     string strUrl = "http://yams.in/check-port.php?s=" + externalIP.ToString() + "&p=" + intPortNumber.ToString();
     WebClient wcCheckPort = new WebClient();
     UTF8Encoding utf8 = new UTF8Encoding();
     string strResponse = "";
     try
     {
         strResponse = utf8.GetString(wcCheckPort.DownloadData(strUrl));
         switch (strResponse)
         {
             case "open":
                 return true;
             case "closed":
                 return false;
             default:
                 return false;
         }
     }
     catch (WebException e)
     {
         YAMS.Database.AddLog("Unable to check open port: " + e.Data, "utils", "warn");
         return false;
     }
 }
Пример #26
0
        private static string Decrypt(byte[] inputInBytes)
        {
            // UTFEncoding is used to transform the decrypted Byte Array
            // information back into a string.
            UTF8Encoding utf8encoder = new UTF8Encoding();
            TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider();

            // As before we must provide the encryption/decryption key along with
            // the init vector.

            //ICryptoTransform cryptoTransform = tdesProvider.CreateDecryptor(EncriptKey, EncriptIv);
            ICryptoTransform cryptoTransform = tdesProvider.CreateDecryptor();

            // Provide a memory stream to decrypt information into
            MemoryStream decryptedStream = new MemoryStream();
            CryptoStream cryptStream = new CryptoStream(decryptedStream, cryptoTransform, CryptoStreamMode.Write);
            cryptStream.Write(inputInBytes, 0, inputInBytes.Length);
            cryptStream.FlushFinalBlock();
            decryptedStream.Position = 0;

            // Read the memory stream and convert it back into a string
            byte[] result = new byte[decryptedStream.Length];
            decryptedStream.Read(result, 0, System.Convert.ToInt32(decryptedStream.Length));
            cryptStream.Close();
            UTF8Encoding myutf = new UTF8Encoding();
            return myutf.GetString(result);
        }
Пример #27
0
        public string Decrypt(string message)
        {
            byte[] results;
            UTF8Encoding utf8 = new UTF8Encoding();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] deskey = md5.ComputeHash(utf8.GetBytes(Passphrase));
            TripleDESCryptoServiceProvider desalg = new TripleDESCryptoServiceProvider();
            desalg.Key = deskey;
            desalg.Mode = CipherMode.ECB;
            desalg.Padding = PaddingMode.PKCS7;
            byte[] decryptData = Convert.FromBase64String(message);
            try
            {
                //To transform the utf binary code to md5 decrypt
                ICryptoTransform decryptor = desalg.CreateDecryptor();
                results = decryptor.TransformFinalBlock(decryptData, 0, decryptData.Length);
            }
            finally
            {
                desalg.Clear();
                md5.Clear();

            }
            //TO convert decrypted binery code to string
            return utf8.GetString(results);
        }
Пример #28
0
        private string SendSms(string smsUrl, string postData)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] data = encoding.GetBytes(postData);

            WebRequest smsRequest = WebRequest.Create(smsUrl);
            smsRequest.Method = "POST";
            smsRequest.ContentType = "application/x-www-form-urlencoded";
            smsRequest.ContentLength = data.Length;

            Stream smsDataStream = null;
            smsDataStream = smsRequest.GetRequestStream();
            smsDataStream.Write(data, 0, data.Length);
            smsDataStream.Close();

            WebResponse smsResponse = smsRequest.GetResponse();

            byte[] responseBuffer = new byte[smsResponse.ContentLength];
            int count = int.MaxValue;
            try
            {
                count = (int)smsResponse.ContentLength - 1;
            }
            catch { }
            smsResponse.GetResponseStream().Read(responseBuffer, 0, count);
            smsResponse.Close();

            return encoding.GetString(responseBuffer);
        }
Пример #29
0
        static void Main(string[] args)
        {
            //Console.WriteLine("Test");
            //Console.ReadLine();
            WebClient wc = new WebClient();

            string WebURL = @"http://*****:*****@"http://www.google.co.th";
            UTF8Encoding encUTF8 = new UTF8Encoding();
            string returnedData = "";

            try
            {
                Console.WriteLine(WebURL);
                Console.WriteLine("Connecting...");

                returnedData = encUTF8.GetString(wc.DownloadData(WebURL));

                Console.WriteLine(returnedData);
                Console.WriteLine("Download data complete ");

            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR :: " + ex.Message);
            }
            Console.ReadLine();
        }
Пример #30
0
        private void MessageCallBack(IAsyncResult aResult)
        {
            try
            {
                int size = sck.EndReceiveFrom(aResult, ref epRemote);
                if (size > 0)
                {
                    byte[] receivedData = new byte[1464];
                    receivedData = (byte[])aResult.AsyncState;
                    UTF8Encoding eEncoding = new UTF8Encoding();
                    string receivedMessage = eEncoding.GetString(receivedData); //декодирование байтов в строку

                    tbMessage.Text += NameClient_2.Text + ": " + receivedMessage;
                    tbMessage.Text += "\r\n";
                }

                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
                MessageBox.Show("Проверте: \r\n - верно ли внесены сетевые настройки игры;\r\n - отсутствует сетевое подключение;\r\n - Ваш противник покинул игру или неуспел подключится.", "Oшибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
            }
        }
Пример #31
0
 public string Encrypt(string password)
 {
     var md5 = new MD5CryptoServiceProvider();
     var encoding = new UTF8Encoding();
     var bytes = encoding.GetBytes(password);
     return encoding.GetString(md5.ComputeHash(bytes));
 }
        public static string DecryptString(string Message)
        {
            byte[] Results;
            string passphrase = ReadCert();

            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;
            byte[] DataToDecrypt = Convert.FromBase64String(Message);
            try
            {
                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally
            {
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }
            return UTF8.GetString(Results);
        }
Пример #33
0
        public string Cancelar()
        {
            try
            {
                XmlSerializerNamespaces nameSpaces = new XmlSerializerNamespaces();
                nameSpaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
                nameSpaces.Add("tipos", "http://*****:*****@"D:\Ret_CANC_LOTE_2805131157.xml";

                RetornoCancelamentoNFSe objretorno = SerializeClassToXml.DeserializeClasse<RetornoCancelamentoNFSe>(sPathRetConsultaCanc);

                string sMessageRetorno = TrataRetornoCancelamento(objretorno);
                return sMessageRetorno;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #34
0
    public string String()
    {
        int    len   = Int();
        string value = encoding.GetString(data, i, len);

        i += len;
        return(value);
    }
Пример #35
0
                /// <summary>
                /// Get_String
                /// </summary>
                public string Get_String()
                {
                    //New UTF8 Object
                    System.Text.UTF8Encoding EUTF8 = new System.Text.UTF8Encoding();

                    //Return
                    return(EUTF8.GetString(Get_Bytes()));
                }
Пример #36
0
    public static string get_uft8(string unicodeString)
    {
        System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
        Byte[] encodedBytes           = utf8.GetBytes(unicodeString);
        String decodedString          = utf8.GetString(encodedBytes);

        return(decodedString);
    }
Пример #37
0
    public static string Get_UFT8(string unicodeString)
    {
        System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();
        var    encodedBytes           = utf8.GetBytes(unicodeString);
        string decodedString          = utf8.GetString(encodedBytes);

        return(decodedString);
    }
Пример #38
0
    public string ReadString16()
    {
        ushort len = ReadInt16();

        byte[] bytes = mBinReader.ReadBytes(len);
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        return(encoding.GetString(bytes));
    }
Пример #39
0
    public static string ReadString(BinaryReader _Reader)
    {
        ushort len = _Reader.ReadUInt16();

        byte [] data = _Reader.ReadBytes(len);

        System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
        return(enc.GetString(data));
    }
Пример #40
0
 public static string BytesToString(byte[] buf)
 {
     if (buf == null)
     {
         return("");
     }
     System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
     return(enc.GetString(buf));
 }
            /// <summary>
            /// decrypt value
            /// </summary>
            /// <param name="Passphrase"></param>
            /// <param name="Message"></param>
            /// <returns></returns>
            /// <remarks></remarks>
            private static string Decrypt(string Passphrase, string Message)
            {
                //try
                //{
                if (IsNullOrEmpty(Message))
                {
                    return(string.Empty);
                }
                byte[] Results;
                System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

                // Step 1. We hash the passphrase using MD5
                // We use the MD5 hash generator as the result is a 128 bit byte array
                // which is a valid length for the TripleDES encoder we use below

                MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();

                byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));

                // Step 2. Create a new TripleDESCryptoServiceProvider object
                TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();

                // Step 3. Setup the decoder
                TDESAlgorithm.Key     = TDESKey;
                TDESAlgorithm.Mode    = CipherMode.ECB;
                TDESAlgorithm.Padding = PaddingMode.PKCS7;

                Message = Message.Replace(" ", "+"); // Replace space with plus sign in encrypted value if any.- kalpesh joshi [09/05/2013]

                // Step 4. Convert the input string to a byte[]
                byte[] DataToDecrypt = Convert.FromBase64String(Message);

                // Step 5. Attempt to decrypt the string
                try
                {
                    ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                    Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
                }
                catch
                {
                    return("");
                }
                finally
                {
                    // Clear the TripleDes and Hashprovider services of any sensitive information
                    TDESAlgorithm.Clear();
                    HashProvider.Clear();
                }

                // Step 6. Return the decrypted string in UTF8 format
                return(UTF8.GetString(Results));
                //}
                //catch (Exception)
                //{
                //    throw;
                //}
            }
Пример #42
0
 public void LoadXmlFromBase64(string response)
 {
     //System.Diagnostics.Debug.WriteLine("response=" + response);
     System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
     if (response != null)
     {
         LoadXml(enc.GetString(Convert.FromBase64String(response)));
     }
 }
Пример #43
0
        /// <summary>
        /// Deserialize an object
        /// </summary>
        /// <param name="bytes">The results of a previous call to <see cref="ToByteArray"/></param>
        /// <param name="type">Type type of the object, in C# use typeof(), VB use GetType()</param>
        /// <returns>The deserialized object</returns>
        static public object FromByteArray(byte[] bytes, Type type)
        {
            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            string xml = enc.GetString(bytes);

            DataContractSerializer serializer = new DataContractSerializer(type);

            return(_FromXml(xml, serializer));
        }
Пример #44
0
        /// <summary>
        /// Deserialize an object
        /// </summary>
        /// <typeparam name="T">The Type of object being deserialized</typeparam>
        /// <param name="bytes">The results of a previous call to <see cref="ToByteArray"/></param>
        /// <param name="type">Type type of the object, in C# use typeof(), VB use GetType()</param>
        /// <param name="rootName">Typically the object name, 'Employees', for instance</param>
        /// <param name="rootNamespace">An xml namespaces, example, 'http://www.entityspaces.net'</param>
        /// <returns>The deserialized object</returns>
        static public T FromByteArray <T>(byte[] bytes, string rootName, string rootNamespace)
        {
            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            string xml = enc.GetString(bytes);

            DataContractSerializer serializer = new DataContractSerializer(typeof(T), rootName, rootNamespace);

            return((T)_FromXml(xml, serializer));
        }
Пример #45
0
        public string readString(BinaryReader reader)
        {
            ushort len = reader.ReadUInt16();

            System.Text.UTF8Encoding converter = new System.Text.UTF8Encoding();
            string str = converter.GetString(reader.ReadBytes(len), 0, len);

            return(str);
        }
Пример #46
0
        // Compliments of Richard W.
        public static string StoreEncrypt(string Plain_Text, byte[] Key, byte[] IV)
        {
            RijndaelManaged Crypto    = null;
            MemoryStream    MemStream = null;
            //I crypto transform is used to perform the actual decryption vs encryption, hash function are a version of crypto transforms.
            ICryptoTransform Encryptor = null;
            //Crypto streams allow for encryption in memory.
            CryptoStream Crypto_Stream = null;

            System.Text.UTF8Encoding Byte_Transform = new System.Text.UTF8Encoding();

            //Just grabbing the bytes since most crypto functions need bytes.
            byte[] PlainBytes = Byte_Transform.GetBytes(Plain_Text);

            try
            {
                Crypto      = new RijndaelManaged();
                Crypto.Key  = Key;
                Crypto.IV   = IV;
                Crypto.Mode = CipherMode.CBC;
                //Crypto.KeySize = 256;
                //Crypto.BlockSize = 256;
                //Crypto.FeedbackSize = 256;
                //Crypto.Padding = PaddingMode.None;

                MemStream = new MemoryStream();

                //Calling the method create encryptor method Needs both the Key and IV these have to be from the original Rijndael call
                //If these are changed nothing will work right.
                Encryptor = Crypto.CreateEncryptor(Crypto.Key, Crypto.IV);

                //The big parameter here is the cryptomode.write, you are writing the data to memory to perform the transformation
                Crypto_Stream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write);

                //The method write takes three params the data to be written (in bytes) the offset value (int) and the length of the stream (int)
                Crypto_Stream.Write(PlainBytes, 0, PlainBytes.Length);
            }
            finally
            {
                //if the crypto blocks are not clear lets make sure the data is gone
                if (Crypto != null)
                {
                    Crypto.Clear();
                }
                //Close because of my need to close things then done.
                Crypto_Stream.Close();
            }
            //This is just here to convert the Encrypted byte array to a string for viewing purposes.
            System.Text.UTF8Encoding UTF = new System.Text.UTF8Encoding();

            //Return the memory byte array
            var Encrypted_Bytes = MemStream.ToArray();

            var Encrypted_Text = UTF.GetString(Encrypted_Bytes);

            return(Convert.ToBase64String(Encrypted_Bytes));
        }
Пример #47
0
        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="result"></param>
        private void Read(IAsyncResult result)
        {
            if (!ClientSocket.Connected)
            {
                return;
            }
            try
            {
                // Web Socket protocol: 0x00开头,0xFF结尾
                System.Text.UTF8Encoding decoder = new System.Text.UTF8Encoding();
                int startIndex = 0;
                int endIndex   = 0;

                //查找起启位置
                while (receivedDataBuffer[startIndex] == 0x00)
                {
                    startIndex++;
                }
                // 查找结束位置
                endIndex = startIndex + 1;
                while (receivedDataBuffer[endIndex] != 0xff && endIndex != WebSocketProtocol.GetInstance.MaxBufferSize - 1)
                {
                    endIndex++;
                }
                if (endIndex == WebSocketProtocol.GetInstance.MaxBufferSize - 1)
                {
                    endIndex = WebSocketProtocol.GetInstance.MaxBufferSize;
                }


                string messageReceived = decoder.GetString(receivedDataBuffer, startIndex, endIndex - startIndex);

                MessageEntity me = JsonConvert.DeserializeObject(messageReceived, typeof(MessageEntity)) as MessageEntity;
                if (!string.IsNullOrEmpty(this.Name))
                {
                    ReceiveData(this, me);
                }
                else if (me.MessageId.ToLower() == "login")
                {
                    if (NewUserConnection != null)
                    {
                        this.Name = (Newtonsoft.Json.JsonConvert.DeserializeObject(me.MessageContent, typeof(ChartMessage)) as ChartMessage).Message;
                        NewUserConnection(this, me);
                    }
                }

                /* MessageEntity me=new MessageEntity();
                 * me.MessageContent = messageReceived;
                 * ReceiveData(this, me);*/
                Array.Clear(receivedDataBuffer, 0, receivedDataBuffer.Length);
                ClientSocket.BeginReceive(receivedDataBuffer, 0, receivedDataBuffer.Length, 0, new AsyncCallback(Read), null);
            }
            catch (Exception ex)
            {
                DisConnection(this, null);
            }
        }
Пример #48
0
        void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            RequestState state = (RequestState)e.UserState;

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            String str = encoding.GetString(e.Result);

            this.SpiderView.Scripting.InvokeFunction(state.Callback, str);
        }
Пример #49
0
    public string ReadString8()
    {
        int len = ReadByte();

        byte[] bytes = mBinReader.ReadBytes(len);
        // System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        return(encoding.GetString(bytes));
    }
Пример #50
0
 public static string DecryptString(string strToEncrypt, int id)
 {
             #if UNITY_WINRT
     int toInt    = 0;
     int intStr   = 0;
     int toIntStr = 0;
     System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
     byte[] secureKeyBytes             = encoding.GetBytes(PlayerPrefsElite.key[id]);
     string secureKeyEncoded           = System.Convert.ToBase64String(secureKeyBytes);
     int[]  secureKey = new int[secureKeyEncoded.Length];
     for (int x = 0; x < secureKeyEncoded.Length; x++)
     {
         secureKey[x] = System.Convert.ToInt32(secureKeyEncoded[x]);
     }
     string toDc       = "";
     string strEncrypt = "";
     for (int y = 0; y <= strToEncrypt.Length - 1; y += 2)
     {
         intStr     = int.Parse(strToEncrypt.Substring(y, 1), System.Globalization.NumberStyles.HexNumber) * 16 + int.Parse(strToEncrypt.Substring((y + 1), 1), System.Globalization.NumberStyles.HexNumber);
         toInt      = (y / 2) % secureKey.Length;
         toIntStr   = intStr - System.Convert.ToInt32(secureKey[toInt]) + 256;
         toIntStr   = toIntStr % 256;
         toDc       = ((char)toIntStr).ToString();
         strEncrypt = strEncrypt + toDc;
     }
     byte[] decodedBytes = System.Convert.FromBase64String(strEncrypt);
     System.Text.UTF8Encoding decodedText = new System.Text.UTF8Encoding();
     string decodedTexta = decodedText.GetString(decodedBytes, 0, decodedBytes.Length);
     return(decodedTexta);
             #else
     int    toInt            = 0;
     int    intStr           = 0;
     int    toIntStr         = 0;
     byte[] secureKeyBytes   = System.Text.Encoding.UTF8.GetBytes(PlayerPrefsElite.key[id]);
     string secureKeyEncoded = System.Convert.ToBase64String(secureKeyBytes);
     int[]  secureKey        = new int[secureKeyEncoded.Length];
     for (int x = 0; x < secureKeyEncoded.Length; x++)
     {
         secureKey[x] = System.Convert.ToInt32(secureKeyEncoded[x]);
     }
     string toDc       = "";
     string strEncrypt = "";
     for (int y = 0; y <= strToEncrypt.Length - 1; y += 2)
     {
         intStr     = int.Parse(strToEncrypt.Substring(y, 1), System.Globalization.NumberStyles.HexNumber) * 16 + int.Parse(strToEncrypt.Substring((y + 1), 1), System.Globalization.NumberStyles.HexNumber);
         toInt      = (y / 2) % secureKey.Length;
         toIntStr   = intStr - System.Convert.ToInt32(secureKey[toInt]) + 256;
         toIntStr   = toIntStr % 256;
         toDc       = ((char)toIntStr).ToString();
         strEncrypt = strEncrypt + toDc;
     }
     byte[] decodedBytes = System.Convert.FromBase64String(strEncrypt);
     string decodedText  = System.Text.Encoding.UTF8.GetString(decodedBytes);
     return(decodedText);
             #endif
 }
Пример #51
0
        /// <summary>
        /// This method is a callback function to the Send method. It ensures all the data that needs to be sent is sent in the correct order. And it ends when there is no more data
        /// to me sent to the server.
        /// </summary>
        /// <param name="result"></param>
        public static void SendCallBack(IAsyncResult result)
        {
            // The number of bytes that were sent.
            int bytes;

            // Pull the Preserved state obj out of the arObject.
            PreservedState state = (PreservedState)result.AsyncState;

            // Store the socket
            Socket socket = state.socket;

            if (socket.Connected)
            {
                // Retrieve the number of bytes sent
                try
                {
                    bytes = socket.EndSend(result);
                }
                catch (Exception e)
                {
                    socket.Close();
                    return;
                }
            }
            else
            {
                return;
            }

            // Lock this method so multiple threads can be sending data at the same time.
            lock (locker)
            {
                // store the PreservedState buffer into a outgoing buffer.
                byte[] outgoingBuffer = state.buffer;

                // Convert all the buffer data into a string.
                String data = encoding.GetString(outgoingBuffer, bytes, outgoingBuffer.Length - bytes);

                // Iif the string is empty end this send callback
                if (data == "")
                {
                    // If the optional callback was provided in Send(), run it. Else, just return
                    if (state.callBack != null)
                    {
                        state.callBack(null);
                    }
                    else
                    {
                        return;
                    }
                }

                // If there is more data to send call Send again.
                Send(socket, data);
            }
        }
Пример #52
0
        static async void startWSHandler(object context_raw)
        {
            // create a Cancellation Token
            var TokenSource = new CancellationTokenSource();
            var Token       = TokenSource.Token;

            // create the websocket
            HttpListenerContext context = context_raw as HttpListenerContext;
            var ws = await context.AcceptWebSocketAsync(null);

            // some content converter
            byte[] buffy        = new byte[4096];
            var    text_decoder = new System.Text.UTF8Encoding();


            List <Player> player        = new List <Player>();
            StringBuilder stringBuilder = new StringBuilder();
            Session       session       = null;
            CommandParser parser        = createParser(session, player, stringBuilder);

            parser.Builder = stringBuilder;
            // actual processing
            while (true)
            {
                try
                {
                    var wsresult = await ws.WebSocket.ReceiveAsync(new ArraySegment <byte>(buffy), Token);

                    if (wsresult.MessageType != WebSocketMessageType.Close)
                    {
                        string cmd = text_decoder.GetString(buffy, 0, wsresult.Count);
                        System.Console.Write("> ");
                        System.Console.WriteLine(cmd);

                        stringBuilder.Clear();
                        parser.Parse(cmd);

                        if (stringBuilder.Length != 0)
                        {
                            System.Console.WriteLine(stringBuilder.ToString());
                            await ws.WebSocket.SendAsync(text_decoder.GetBytes(stringBuilder.ToString()), WebSocketMessageType.Text, true, Token);
                        }
                    }
                    else //else close
                    {
                        ws.WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Bye", Token).Wait();
                        Console.WriteLine("Closed WebSocket");
                        return;
                    }
                } catch
                {
                    Console.WriteLine("Unhandled Exception with WebSocket");
                    break;
                }
            }
        }
Пример #53
0
        public void run()
        {
            //Console.WriteLine("NEW CONNECTION!");

            byte[] buffer = new byte[32768];

            var stream = tcpClient.GetStream();

            int timeout = 5000;

            this.tcpClient.ReceiveTimeout = timeout;
            stream.ReadTimeout            = timeout;

            try
            {
                for (;;)
                {
                    int count = stream.Read(buffer, 0, buffer.Length);
                    if (count < 1)
                    {
                        break;
                    }

                    System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
                    string request = enc.GetString(buffer, 0, count);

                    //Console.Out.WriteLine("---- REQUEST START");

                    stopWatch.Restart();

                    bool keepAlive = handleRequest(request);

                    stopWatch.Stop();

                    //Console.Out.WriteLine("---- REQUEST END (" + stopWatch.ElapsedMilliseconds + "ms)");

                    if (false == keepAlive)
                    {
                        break;
                    }
                }
            }
            catch (IOException)
            {
                //Console.Out.WriteLine("IOException " + e);
            }

            stream.Close();
            stream = null;

            tcpClient.Close();
            tcpClient = null;

            handlerUsage--;
            //Console.WriteLine("Finished Handler: " + handlerId + " (usage: " + handlerUsage + ")");
        }
Пример #54
0
        public static string ByteArrayToString(byte[] bytes)
        {
            System.Text.Encoding encoding = null;

            //encoding = new System.Text.ASCIIEncoding();
            //encoding = new System.Text.UnicodeEncoding();
            //encoding = new System.Text.UTF7Encoding();
            encoding = new System.Text.UTF8Encoding();
            return(encoding.GetString(bytes, 0, bytes.Length));
        }
        /// <summary>
        /// Deserialize an object
        /// </summary>
        /// <typeparam name="T">The Type of object being deserialized</typeparam>
        /// <param name="bytes">The results of a previous call to <see cref="ToByteArray"/></param>
        /// <returns>The deserialized object</returns>
        static public T FromByteArray <T>(byte[] bytes)
        {
            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            string xml = enc.GetString(bytes);
            //string xml = enc.GetString(bytes, 0, bytes.Length);

            DataContractSerializer serializer = new DataContractSerializer(typeof(T));

            return((T)_FromXml(xml, serializer));
        }
Пример #56
0
        static void PrintBitString(BitArray _in)
        {
            byte[] arr = new byte[_in.Length / 8];
            _in.CopyTo(arr, 0);

            System.Text.UTF8Encoding asciiEncoding = new System.Text.UTF8Encoding();
            string strCharacter = asciiEncoding.GetString(arr);

            Console.WriteLine(strCharacter);
        }
Пример #57
0
        public String GetBodyRaw()
        {
            // discover the body as a raw string
            byte[] b = new byte[this.Request.Body.Length];
            this.Request.Body.Read(b, 0, Convert.ToInt32(this.Request.Body.Length));
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            String bodyData = encoding.GetString(b);

            return(bodyData);
        }
        private string DecryptValue(string base64string)
        {
            string returnVal = null;

            byte[] encrytpedBytes             = Convert.FromBase64String(base64string);
            byte[] unencrytpedBytes           = System.Security.Cryptography.ProtectedData.Unprotect(encrytpedBytes, null, System.Security.Cryptography.DataProtectionScope.LocalMachine);
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            returnVal = encoding.GetString(unencrytpedBytes);
            return(returnVal);
        }
Пример #59
0
    private bool IsDone  = false; //更新完毕
    protected override void OnEnter(ProcedureOwner procedureOwner)
    {
        base.OnInit(procedureOwner);

        ClientApp.Event.Subscribe(ResourceCheckCompleteEventArgs.EventId, OnCheckComplete);         //检查资源列表完成
        ClientApp.Event.Subscribe(VersionListUpdateSuccessEventArgs.EventId, OnListUpdateSuccess);  //更新list成功
        ClientApp.Event.Subscribe(ResourceUpdateChangedEventArgs.EventId, OnResourceUpdateChanged); //更新单个资源进度
        ClientApp.Event.Subscribe(ResourceUpdateSuccessEventArgs.EventId, OnResourceUpdateSuccess); //更新单个资源成功
        ClientApp.Event.Subscribe(ResourceUpdateFailureEventArgs.EventId, OnResourceUpdateFailure); //更新单个资源失败
        ClientApp.Event.Subscribe(ResourceUpdateAllCompleteEventArgs.EventId, OnAllComplete);       //全部更新完成

        string ver = Application.version.Replace('.', '_');
        string url = "http://eltsres.gulugames.cn/test/" + "GameResourceVersion_" + ver + ".xml";

        WebRequestEvent _event = new WebRequestEvent
        {
            OnSuccess = delegate(int SerialId, byte[] bytes)
            {
                System.Text.UTF8Encoding code = new System.Text.UTF8Encoding(false);
                bytes = CleanUTF8Bom(bytes);
                string str = code.GetString(bytes);
                Debug.Log(str);
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(str);
                XmlNode      node = xml.SelectSingleNode("ResourceVersionInfo");
                XmlAttribute LatestInternalResourceVersionNode = node.Attributes["LatestInternalResourceVersion"];
                int          LatestInternalResourceVersion     = int.Parse(LatestInternalResourceVersionNode.Value); //内部版本号

                node = node.SelectSingleNode("StandaloneWindows");
                XmlAttribute ZipHashCodeNode = node.Attributes["ZipHashCode"];
                int          ZipHashCode     = int.Parse(ZipHashCodeNode.Value);

                XmlAttribute ZipLengthNode = node.Attributes["ZipLength"];
                int          ZipLength     = int.Parse(ZipLengthNode.Value);

                XmlAttribute HashCodeNode = node.Attributes["HashCode"];
                int          HashCode     = int.Parse(HashCodeNode.Value);

                XmlAttribute LengthNode = node.Attributes["Length"];
                int          Length     = int.Parse(LengthNode.Value);

                if (ClientApp.Resource.CheckVersionList(LatestInternalResourceVersion) == GameFramework.Resource.CheckVersionListResult.NeedUpdate)
                {
                    ClientApp.Resource.UpdateVersionList(Length, HashCode, ZipLength, ZipHashCode);
                }
                else
                {
                    ClientApp.Resource.CheckResources();
                }
            }
        };

        ClientApp.Resource.UpdatePrefixUri = "http://eltsres.gulugames.cn/test/windows/";
        ClientApp.WebRequest.AddWebRequest(url, _event);
    }
Пример #60
0
        /**
         * base-64 encode a byte array
         * @param src The byte array to encode
         * @param start The starting index
         * @param length The number of bytes
         * @returns The base64 encoded result
         */

        public static String encode(byte[] src, int start, int length)
        {
            byte[] dst      = new byte[(length + 2) / 3 * 4 + length / 72];
            int    x        = 0;
            int    dstIndex = 0;
            int    state    = 0;
            int    old      = 0;
            int    len      = 0;
            int    max      = length + start;

            for (int srcIndex = start; srcIndex < max; srcIndex++)
            {
                x = src[srcIndex];
                switch (++state)
                {
                case 1:
                    dst[dstIndex++] = encodeData[(x >> 2) & 0x3f];
                    break;

                case 2:
                    dst[dstIndex++] = encodeData[((old << 4) & 0x30)
                                                 | ((x >> 4) & 0xf)];
                    break;

                case 3:
                    dst[dstIndex++] = encodeData[((old << 2) & 0x3C)
                                                 | ((x >> 6) & 0x3)];
                    dst[dstIndex++] = encodeData[x & 0x3F];
                    state           = 0;
                    break;
                }
                old = x;
                if (++len >= 72)
                {
                    dst[dstIndex++] = (byte)'\n';
                    len             = 0;
                }
            }

            switch (state)
            {
            case 1:
                dst[dstIndex++] = encodeData[(old << 4) & 0x30];
                dst[dstIndex++] = (byte)'=';
                dst[dstIndex++] = (byte)'=';
                break;

            case 2:
                dst[dstIndex++] = encodeData[(old << 2) & 0x3c];
                dst[dstIndex++] = (byte)'=';
                break;
            }
            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            return(enc.GetString(dst, 0, dstIndex));
        }