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;
        }
Esempio n. 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);
        }
Esempio n. 3
1
        public string ComputeHash(string data)
        {
            var bytes = new UTF8Encoding().GetBytes(data);
            var hash = _hashAlgorithm.ComputeHash(bytes);

            return Convert.ToBase64String(hash);
        }
Esempio n. 4
1
        public String LogUser( LogInfo info )
        {
            HttpWebRequest request = bnRequest(@"https://www.battlenet.com.cn/login/zh/");
            request.CookieContainer = cc;

            request.Method = WebRequestMethods.Http.Post;
            request.ContentType = "application/x-www-form-urlencoded";

            String postString = "";
            postString += "accountName=" + Uri.EscapeUriString(info.UserMail);
            postString += "&password="******"verify");
            }

            byte[] postData = new UTF8Encoding().GetBytes(postString);
            request.ContentLength = postData.Length;
            Stream postStream = request.GetRequestStream();
            postStream.Write(postData, 0, postData.Length);
            postStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            return  reader.ReadToEnd();
        }
Esempio n. 5
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);
 }
Esempio n. 6
1
        /// <summary>
        /// Sends some data to a URL using an HTTP POST.
        /// </summary>
        /// <param name="url">Url to send to</param>
        /// <param name="postData">The data to send</param>
        public string SendRequest(string url, string postData)
        {
            var uri = new Uri(url);
            var request = WebRequest.Create(uri);
            var encoding = new UTF8Encoding();
            var requestData = encoding.GetBytes(postData);

            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.Timeout = (300 * 1000); //TODO: Move timeout to config
            request.ContentLength = requestData.Length;

            using (var stream = request.GetRequestStream())
            {
                stream.Write(requestData, 0, requestData.Length);
            }

            var response = request.GetResponse();

            string result;

            using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
            {
                result = reader.ReadToEnd();
            }

            return result;
        }
Esempio n. 7
1
        private static void Process(Object param)
        {
            HttpListenerContext context = (HttpListenerContext)param;
            Encoding encoder = new UTF8Encoding();

            string url = context.Request.Url.AbsolutePath;

            Match url_match = Regex.Match(url, SearchUrlMatcher);
            if (!url_match.Success)
            {
                Form1.LogInfo("Unknown URL: " + url);
                return;
            }
            String AlbumName = HttpUtility.UrlDecode(url_match.Groups["Album"].ToString());
            String ArtistName = HttpUtility.UrlDecode(url_match.Groups["Artist"].ToString());

            AlbumArtRetriever retriever = AlbumArtRetrieverManager.getSelectedRetriever();

            int album_count = 0;
            String result_line = "";
            foreach (AlbumInfo album in retriever.retrieve(ArtistName, AlbumName))
            {
                album_count++;
                result_line += String.Format(PicRegexGenerator, album.AlbumArtURL, album.AlbumName, album.Artist);
            }
            Match m = Regex.Match(result_line, PicRegex);
            String s = m.Groups["Artist"].Value;
            byte[] result_bytes = encoder.GetBytes(result_line);
            context.Response.OutputStream.Write(result_bytes, 0, result_bytes.Length);
            Form1.LogInfo(String.Format("Search of {0} {1} via {2} returned {3} albums.",
                new object[] {ArtistName, AlbumName, retriever.getName(), album_count}));

            context.Response.OutputStream.Close();
        }
 public RijndaelHelper(byte[] key, byte[] vector)
 {
     encoding = new UTF8Encoding();
     rijndael = Rijndael.Create();
     rijndael.Key = key;
     rijndael.IV = vector;
 }
 public AesEncryption(byte[] Key, byte[] Vector)
 {
     RijndaelManaged rijndaelManaged = new RijndaelManaged();
     this.EncryptorTransform = rijndaelManaged.CreateEncryptor(Key, Vector);
     this.DecryptorTransform = rijndaelManaged.CreateDecryptor(Key, Vector);
     this.UTFEncoder = new UTF8Encoding();
 }
Esempio n. 10
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;
        }
Esempio n. 11
1
 public static String MD5(String text)
 {
     UTF8Encoding encoder = new UTF8Encoding();
     var md5 = new MD5CryptoServiceProvider();
     byte[] hashedDataBytes = md5.ComputeHash(encoder.GetBytes(text));
     return System.Convert.ToBase64String(hashedDataBytes);
 }
        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;
            }
        }
Esempio n. 13
1
 // Methods
 public EncryptionHelper()
 {
     RijndaelManaged managed = new RijndaelManaged();
     this.EncryptorTransform = managed.CreateEncryptor(this.Key, this.Vector);
     this.DecryptorTransform = managed.CreateDecryptor(this.Key, this.Vector);
     this.UTFEncoder = new UTF8Encoding();
 }
Esempio n. 14
1
 public AuthenticationHelper()
 {
     var rm = new RijndaelManaged();
     encryptor = rm.CreateEncryptor(key, vector);
     decryptor = rm.CreateDecryptor(key, vector);
     encoder = new UTF8Encoding();
 }
Esempio n. 15
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);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// A chave deve possuir 16 com caracteres "1234567890123456"
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetCriptografiaSimetrica(this string str, string key)
        {
            using (TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider())
            {

                provider.Mode = CipherMode.CFB;
                provider.Padding = PaddingMode.PKCS7;

                MemoryStream mStream = new MemoryStream();

                CryptoStream cs = new CryptoStream(mStream, provider.CreateEncryptor(Encoding.UTF8.GetBytes(key), new byte[] { 138, 154, 251, 188, 64, 108, 167, 121 }), CryptoStreamMode.Write);

                byte[] toEncrypt = new UTF8Encoding().GetBytes(str);

                cs.Write(toEncrypt, 0, toEncrypt.Length);
                cs.FlushFinalBlock();
                byte[] ret = mStream.ToArray();

                mStream.Close();
                cs.Close();

                str = Convert.ToBase64String(ret);

            }


            return str;
        }
Esempio n. 17
0
		/// <summary>
		/// Sends the file.
		/// </summary>
		/// <param name='fileName'>
		/// File name.
		/// </param>
		/// <param name='fileSize'>
		/// File size.
		/// </param>
		/// <param name='tl'>
		/// Tl.
		/// </param>
		private void sendFile(String fileName, Transport transport)
		{
			long fileLength = LIB.check_File_Exists(fileName);
			
			System.Text.UTF8Encoding  encoding=new System.Text.UTF8Encoding();
			var stringToSend = fileLength.ToString ();
			_transport.send(encoding.GetBytes(stringToSend), stringToSend.Length);	

			if (fileLength == 0) 
			{
				Console.WriteLine ("Filelength was 0, does not excist");
				return;
			}

			FileStream file = File.Open (fileName, FileMode.Open);

			byte[] data = new byte[BUFSIZE];
			for (int i = 0; i < fileLength; i += BUFSIZE) 
			{
				int size = file.Read (data, 0, BUFSIZE);
				Console.WriteLine (size);
				transport.send (data, size);
			}
			file.Close ();
		}
Esempio n. 18
0
 public static String SHA256(String text)
 {
     UTF8Encoding encoder = new UTF8Encoding();
     SHA256Managed sha256hasher = new SHA256Managed();
     byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(text));
     return System.Convert.ToBase64String(hashedDataBytes);
 }
		static void Main (string[] args)
		{
			if (args.Length != 1) {
				Console.WriteLine ("Usage: TestSyncWrite <uri>");
				return;
			}
		
			Gnome.Vfs.Vfs.Initialize ();

			Gnome.Vfs.Uri uri = new Gnome.Vfs.Uri (args[0]);
			
			Handle handle = Sync.Open (uri, OpenMode.Write);

			UTF8Encoding utf8 = new UTF8Encoding ();
			Result result = Result.Ok;
			Console.WriteLine ("Enter text and end with Ctrl-D");
			while (result == Result.Ok) {
				string line = Console.ReadLine ();
				if (line == null)
					break;
				byte[] buffer = utf8.GetBytes (line);

				ulong bytesWritten;
				result = Sync.Write (handle, out buffer[0],
						     (ulong)buffer.Length, out bytesWritten);
				Console.WriteLine ("result write '{0}' = {1}", uri, result);
				Console.WriteLine ("{0} bytes written", bytesWritten);
			}
			
			result = Sync.Close (handle);
			Console.WriteLine ("result close '{0}' = {1}", uri, result);
			
			Gnome.Vfs.Vfs.Shutdown ();
		}
 public static string sha256encrypt(string phrase)
 {
     UTF8Encoding encoder = new UTF8Encoding();
     SHA256Managed sha256hasher = new SHA256Managed();
     byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(phrase));
     return byteArrayToString(hashedDataBytes);
 }
Esempio n. 21
0
        public void SendSMSAsync(Action<bool> callback = null)
        {
            if (EN_SMS_NT)
            {
                new Thread(new ThreadStart(() =>
                {
                    try
                    {
                        HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(SMS_URI);
                        UTF8Encoding encoding = new UTF8Encoding();
                        byte[] data = encoding.GetBytes(_postData.ToString());
                        httpWReq.Method = "POST";
                        httpWReq.ContentType = "application/x-www-form-urlencoded";
                        httpWReq.ContentLength = data.Length;
                        using (Stream stream = httpWReq.GetRequestStream())
                        {
                            stream.Write(data, 0, data.Length);
                        }

                        HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
                        StreamReader reader = new StreamReader(response.GetResponseStream());
                        string responseString = reader.ReadToEnd();
                        reader.Close();
                        response.Close();
                        if (callback != null) callback(true);
                    }
                    catch (SystemException)
                    {
                        if (callback != null) callback(false);
                    }
                }))
                .Start();
            }
        }
        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;
        }
Esempio n. 23
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;
        }
Esempio n. 24
0
 /// <summary>
 /// 用MD5算法对字符串加密
 /// </summary>
 /// <param name="strOriginal"></param>
 /// <returns></returns>
 public static byte[] Md5Encrypt(string strOriginal)
 {
     var encoder = new UTF8Encoding();
     var md5Hasher = new MD5CryptoServiceProvider();
     byte[] bytePassword = md5Hasher.ComputeHash(encoder.GetBytes(strOriginal));
     return bytePassword;
 }
Esempio n. 25
0
 public int copy_int(int state, int size, string name)
 {
     byte[] s;
     if (size < 2)
     {
         s = new byte[1];
         s[0] = (byte)state;
     }
     else
     {
         s = BitConverter.GetBytes(size == 1 ? (byte)state : (ushort)state);
     }
     name += ": ";
     var nameBytes = new UTF8Encoding().GetBytes(name);
     var list = new List<byte>();
     list.AddRange(nameBytes);
     list.AddRange(s);
     list.AddRange(new byte[] { (byte)'\n' });
     func(buf, list.ToArray(), (uint)list.ToArray().Length);
     if (size < 2)
     {
         return s[0];
     }
     else
     {
         return BitConverter.ToUInt16(s, 0);
     }
 }
Esempio n. 26
0
        public override string Encrypt(string data)
        {
            SHA256Managed sha256hasher = new SHA256Managed();

            try
            {
                UTF8Encoding encoder = new UTF8Encoding();

                byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(string.Format(base.hashFormat, data)));

                return Convert.ToBase64String(hashedDataBytes);
            }
            catch (Exception e)
            {
                var exception = new CryptologyException("SHA256Encryptor.Encrypt()", "An error occurred while encrypting.", e);
                exception.Data.Add("hashFormat", hashFormat);
                exception.Data.Add("data", data);

                throw exception;
            }
            finally
            {
                sha256hasher.Dispose();
            }
        }
Esempio n. 27
0
        /// <summary>
        /// based on http://weblogs.asp.net/abdullaabdelhaq/archive/2009/06/27/displaying-arabic-number.aspx
        /// seems like a fairly expensive method to call so not sure if its suitable to use this everywhere
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string SubstituteArabicDigits(string input)
        {
            if (string.IsNullOrEmpty(input)) { return input; }

            Encoding utf8 = new UTF8Encoding();
            Decoder utf8Decoder = utf8.GetDecoder();
            StringBuilder result = new StringBuilder();

            Char[] translatedChars = new Char[1];
            Char[] inputChars = input.ToCharArray();
            Byte[] bytes = { 217, 160 };

            foreach (Char c in inputChars)
            {
                if (Char.IsDigit(c))
                {
                    // is this the key to it all? does adding 160 change to the unicode char for Arabic?
                    //So we can do the same with other languages using a different offset?
                    bytes[1] = Convert.ToByte(160 + Convert.ToInt32(char.GetNumericValue(c)));
                    utf8Decoder.GetChars(bytes, 0, 2, translatedChars, 0);
                    result.Append(translatedChars[0]);
                }
                else
                {
                    result.Append(c);
                }
            }

            return result.ToString();
        }
    //--------------------------------------
    //  PUBLIC METHODS
    //--------------------------------------
    void OnGUI()
    {
        #if (UNITY_IPHONE && !UNITY_EDITOR) || SA_DEBUG_MODE
        if(GUI.Button(new Rect(170, 70, 150, 50), "Find Match")) {
            GameCenterMultiplayer.instance.FindMatch (2, 2);
        }

        if(GUI.Button(new Rect(170, 130, 150, 50), "Send Data to All")) {
            string msg = "hello world";
            System.Text.UTF8Encoding  encoding = new System.Text.UTF8Encoding();
            byte[] data = encoding.GetBytes(msg);
            GameCenterMultiplayer.instance.SendDataToAll (data, GameCenterDataSendType.RELIABLE);
        }

        if(GUI.Button(new Rect(170, 190, 150, 50), "Send to Player")) {
            string msg = "hello world";
            System.Text.UTF8Encoding  encoding = new System.Text.UTF8Encoding();
            byte[] data = encoding.GetBytes(msg);

            GameCenterMultiplayer.instance.sendDataToPlayers (data, GameCenterDataSendType.RELIABLE, GameCenterMultiplayer.instance.match.playerIDs[0]);
        }

        if(GUI.Button(new Rect(170, 250, 150, 50), "Disconnect")) {
            GameCenterMultiplayer.instance.disconnect ();
        }

        #endif

        //turn based
        /*	if(GUI.Button(new Rect(330, 70, 150, 50), "Trun Based Match")) {
            GameCenterMultiplayer.instance.FindTurnBasedMatch (2, 2);
        } */
    }
Esempio n. 29
0
 public static string EncodeMD5(string password)
 {
     byte[] encodedPassword = new UTF8Encoding().GetBytes(password);
     byte[] hash = ((HashAlgorithm)CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);
     string encoded = BitConverter.ToString(hash).Replace("-", string.Empty).ToLower();
     return encoded;
 }
        /// <summary>
        /// Recibe un texto plano  y lo devuelve cifrado
        /// Cifrado Simetrico
        /// </summary>
        /// <param name="contenido"></param>
        /// <param name="clave"></param>
        /// <returns></returns>
        public static String Cifrar(String contenido, String clave)
        {
            var encoding = new UTF8Encoding();
            var cripto = new RijndaelManaged(); // es un algotimo de cifrado, para cifrar
            //var iv = cripto.GenerateIV(); // Vector de inicialización: es un vector que tiene la semilla de inicialización
            // Este IV

            byte[] cifrado;
            byte[] retorno;
            byte[] key = GetKey(clave); // recibo una clave alfanumerica y devuelvo los bytes desde una cadena UTF8

            cripto.Key = key;
            cripto.GenerateIV(); // genera numeros aleatorios (semillas)
            // voy a crear el encriptador
            byte[] aEncriptar = encoding.GetBytes(contenido); // recibo contenido y lo convierto a array de bites

            // ya lo tengo cifrado
            cifrado = cripto.CreateEncryptor().TransformFinalBlock(aEncriptar, 0, aEncriptar.Length); // transforma el contenido desde 0 hasta que termine

            // creo mi retorno
            retorno = new byte[cripto.IV.Length + cifrado.Length]; // longitud del IV + el tamaño del cifrado

            cripto.IV.CopyTo(retorno, 0); // donde quiero copiar, en que posición quiero copiar
            cifrado.CopyTo(retorno, cripto.IV.Length);
            // la mejor forma es convertirlo a base 64, datos binarios, para almacenar array de bytes
            return Convert.ToBase64String(retorno); //  conjunto de bytes transformados en string
            // muy util para guardar imagenes
        }
Esempio n. 31
0
    IEnumerator SavePlayerData()
    {
        //Send data and convert to json
        var url = new UnityWebRequest(m_Link, "POST");

        byte[] SendjSon = new System.Text.UTF8Encoding().GetBytes(m_Json);
        url.uploadHandler   = (UploadHandler) new UploadHandlerRaw(SendjSon);
        url.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        url.SetRequestHeader("Content-Type", "application/json");
        yield return(url.SendWebRequest());//Do other stuff while sending results


        if (url.isNetworkError)
        {
            Debug.Log("Failed to get highscore table");
        }
        else
        {
            Debug.Log("Sent to database:" + url.downloadHandler.text);
        }
    }
Esempio n. 32
0
    public void HelloWorld()
    {
        if (HttpContext.Current.Request.Params["mode"] != null)
        {
            string mode = Convert.ToString(HttpContext.Current.Request.Params["mode"]);
        }
        string response = "Testing Web service response without tags ";



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



        HttpContext.Current.Response.Clear();



        HttpContext.Current.Response.BinaryWrite(encoding.GetBytes(response));
        //return "~1~Hello World~";
    }
Esempio n. 33
0
    IEnumerator WaitForUnityWebRequestSetGameLevel(UnityWebRequest request, string json)
    {
        byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(json);
        request.uploadHandler   = new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        //Debug.Log("SET LEVEL REQUEST");
        yield return(request.SendWebRequest());

        while (!request.isDone)
        {
            yield return(null);
        }
        //Debug.Log("Response SET LEVEL: " + request.downloadHandler.text);
        SetGameLevelJSONResponse setGameLevelJSONResponse = JsonUtility.FromJson <SetGameLevelJSONResponse>(request.downloadHandler.text);

        if (request.downloadHandler.text == "" || request.downloadHandler.text == null)
        {
            Debug.Log("Connection Error");
        }
    }
    //json request used to handle the save data
    IEnumerator PostRequestJSON(string url, string json)
    {
        //create web request
        var uwr = new UnityWebRequest(url, "POST");

        byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
        uwr.uploadHandler   = (UploadHandler) new UploadHandlerRaw(jsonToSend);
        uwr.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        uwr.SetRequestHeader("Content-Type", "application/json");

        yield return(uwr.SendWebRequest());

        if (uwr.isNetworkError)
        {
            Debug.Log("error sending request");
        }
        else
        {
            Debug.Log("Received: " + uwr.downloadHandler.text);
        }
    }
Esempio n. 35
0
    private static Object CreateAssetFormTemplate(string pathName, string resourceFile)
    {
        if (!pathName.Contains("UI"))
        {
            Debug.Log("没有在UI文件里");
            return(null);
        }
        if (File.Exists(pathName))
        {
            Debug.Log("已经存在了" + Path.GetFileNameWithoutExtension(pathName));
            return(null);
        }
        //获取要创建资源的绝对路径
        string fullName = Path.GetFullPath(pathName);

        //读取本地模版文件
        System.Text.UTF8Encoding utf8withoutBom = new System.Text.UTF8Encoding(false);
        StreamReader             reader         = new StreamReader(resourceFile);
        string content = reader.ReadToEnd();

        reader.Close();

        //获取资源的文件名
        string fileName = Path.GetFileNameWithoutExtension(pathName).Replace("Skin", "");

        //替换默认的文件名
        content = content.Replace("#NAME", fileName);

        //写入新文件
        StreamWriter writer = new StreamWriter(fullName, false, utf8withoutBom);

        writer.Write(content);
        writer.Close();

        //刷新本地资源
        AssetDatabase.ImportAsset(pathName);
        AssetDatabase.Refresh();

        return(AssetDatabase.LoadAssetAtPath(pathName, typeof(Object)));
    }
Esempio n. 36
0
    /// <summary>
    /// This method is responsible for sending data to the server
    /// </summary>
    /// <param name="json">The content of the JSON about the robot trajectory</param>
    /// <returns></returns>
    private IEnumerator Upload(string json)
    {
        var uwr = new UnityWebRequest(url, "POST");

        Debug.Log(json);
        byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
        uwr.uploadHandler   = (UploadHandler) new UploadHandlerRaw(jsonToSend);
        uwr.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        //uwr.SetRequestHeader("Content-Type", "application/json");

        //Send the request then wait here until it returns
        if (loadingBar)
        {
            AsyncOperation operation = uwr.SendWebRequest();
            while (!operation.isDone)
            {
                float progress = Mathf.Clamp01(operation.progress / .9f);

                loadingBar.value = progress;

                yield return(null);
            }
            loadingBar.value = 0;
        }
        else
        {
            yield return(uwr.SendWebRequest());
        }

        if (uwr.isNetworkError)
        {
            Debug.Log("Error While Sending: " + uwr.error);
        }
        else
        {
            Debug.Log("Received: " + uwr.downloadHandler.text);
        }

        uploadComplete = true;
    }
Esempio n. 37
0
    IEnumerator PostRequest(string url, string json)
    {
        var uwr = new UnityWebRequest(url, "POST");

        byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
        uwr.uploadHandler      = (UploadHandler) new UploadHandlerRaw(jsonToSend);
        uwr.downloadHandler    = (DownloadHandler) new DownloadHandlerBuffer();
        uwr.certificateHandler = new AcceptAllCertificatesSignedWithASpecificKeyPublicKey();
        uwr.SetRequestHeader("Content-Type", "application/json");
        {
            //Send the request then wait here until it returns
            uwr.timeout = 5;
            yield return(uwr.SendWebRequest());

            if (uwr.isNetworkError || uwr.isHttpError)
            {
                GameSettings.MyDebug("Error While Sending: " + uwr.error);
                objProgressCircle.SetActive(false);
                btnSendObj.SetActive(true);
            }
            else
            {
                GameSettings.MyDebug("Received: " + uwr.downloadHandler.text);

                EmailStatusRes emailStatusRes = new EmailStatusRes();
                emailStatusRes = JsonUtility.FromJson <EmailStatusRes>(uwr.downloadHandler.text);

                if (emailStatusRes.success)
                {
                    GameSettings.email = email;
                    SceneSwitcher.LoadScene2(GameSettings.THEMATIC_LEADERBOARDS);
                }
                else
                {
                    objProgressCircle.SetActive(false);
                    btnSendObj.SetActive(true);
                }
            }
        }
    }
Esempio n. 38
0
    //--------------------------------------
    //  PUBLIC METHODS
    //--------------------------------------

    void OnGUI()
    {
#if (UNITY_IPHONE && !UNITY_EDITOR) || SA_DEBUG_MODE
        if (GUI.Button(new Rect(170, 70, 150, 50), "Find Match"))
        {
            GameCenterMultiplayer.instance.FindMatch(2, 2);
        }

        if (GUI.Button(new Rect(170, 130, 150, 50), "Send Data to All"))
        {
            string msg = "hello world";
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] data = encoding.GetBytes(msg);
            GameCenterMultiplayer.instance.SendDataToAll(data, GameCenterDataSendType.RELIABLE);
        }


        if (GUI.Button(new Rect(170, 190, 150, 50), "Send to Player"))
        {
            string msg = "hello world";
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] data = encoding.GetBytes(msg);

            GameCenterMultiplayer.instance.sendDataToPlayers(data, GameCenterDataSendType.RELIABLE, GameCenterMultiplayer.instance.match.playerIDs[0]);
        }

        if (GUI.Button(new Rect(170, 250, 150, 50), "Disconnect"))
        {
            GameCenterMultiplayer.instance.disconnect();
        }
#endif


        //turn based

        /*	if(GUI.Button(new Rect(330, 70, 150, 50), "Trun Based Match")) {
         *              GameCenterMultiplayer.instance.FindTurnBasedMatch (2, 2);
         *      } */
    }
Esempio n. 39
0
    public void Start()
    {
        _target = new IPEndPoint(IPAddress.Parse(_destinationIP), 6454);

        _socket = new UdpClient();
        _socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        _socket.Connect(_target);

        string str = "Art-Net";

        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        encoding.GetBytes(str, 0, str.Length, _artNetPacket, 0);

        _artNetPacket[7] = 0x0;

        //opcode low byte first
        _artNetPacket[8] = 0x00;
        _artNetPacket[9] = 0x50;

        //proto ver high byte first
        _artNetPacket[10] = 0x0;
        _artNetPacket[11] = 0x14;

        //TODO: Full Addressing

        //sequence
        _artNetPacket[12] = 0x0;

        //physical port
        _artNetPacket[13] = 0x0;

        //universe low byte first
        _artNetPacket[14] = _universe;
        _artNetPacket[15] = 0x0;

        //length high byte first
        _artNetPacket[16] = ((512 >> 8) & 0xFF);
        _artNetPacket[17] = (512 & 0xFF);
    }
Esempio n. 40
0
    public static IEnumerator PostMessage(Message msg, System.Action <bool> callback = null)
    {
        bool requestErrorOccurred = false;

        // convert message into json body
        string bodyJsonString = JsonUtility.ToJson(msg);
        var    request        = new UnityWebRequest(url_root + "/messages/", "POST");

        byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(bodyJsonString);
        request.uploadHandler   = (UploadHandler) new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");

        yield return(request.SendWebRequest());

        if (request.isNetworkError || request.isHttpError)
        {
            Debug.Log("Something went wrong, and returned error: " + request.error);
            requestErrorOccurred = true;
        }
        else
        {
            Debug.Log("Response: " + request.downloadHandler.text);

            if (request.responseCode == 201)
            {
                Debug.Log("Request finished successfully! New Message created successfully.");
            }
            else
            {
                Debug.Log("Request failed (status:" + request.responseCode + ").");
                requestErrorOccurred = true;
            }
        }
        if (callback != null)
        {
            callback(requestErrorOccurred);
        }
    }