public void Start() { GameObject gameControllerObject = GameObject.FindWithTag ("GameController"); if (gameControllerObject != null) { gameController = gameControllerObject.GetComponent<GameController> (); } if (gameController == null) { Debug.Log ("Cannot find 'GameController' script"); } string url = "https://api.sendgrid.com/api/mail.send.json"; string api_user = "******"; string api_key = "123456"; string to = gameController.getEmail(); string subject = "High Score for Astroid Shooter!"; string text = "Look at my score! I got " + gameController.getScore() + "Can you beat me?"; string from = "*****@*****.**"; WWWForm form = new WWWForm(); form.AddField("api_user", api_user); form.AddField("api_key", api_key); form.AddField("to", to); form.AddField("toName", ""); form.AddField("subject", subject); form.AddField("text", text); form.AddField("from", from); WWW www = new WWW(url, form); StartCoroutine(WaitForRequest(www)); }
public IEnumerator GetDiceRollResult() { string _uuid; if (PlayerPrefs.HasKey ("uuid")) { _uuid = PlayerPrefs.GetString ("uuid"); } else { yield break; } string url = ConfURL.HOST_NAME+ConfURL.PLAYER_BASE_MAKE; WWWForm form = new WWWForm (); form.AddField ("UUID", _uuid); form.AddField ("JobID", SelectJob); WWW www = new WWW(url, form); yield return www; if (www.error != null) { Debug.Log ("error"); } else { Debug.Log ("success"); Debug.Log (www.text); var charaAPI = JsonUtility.FromJson<RollResult>(www.text); baseStatus = charaAPI.BaseStatus; status = charaAPI.Status; InputBaseStatus(baseStatus); InputStatus(status); submitBtn.gameObject.SetActive (true); } }
IEnumerator Login() { WWWForm form = new WWWForm(); //here you create a new form connection form.AddField( "myform_hash", hash ); //add your hash code to the field myform_hash, check that this variable name is the same as in PHP file form.AddField( "myform_nick", formNick ); form.AddField( "myform_pass", formPassword ); WWW w = new WWW(URL, form); //here we create a var called 'w' and we sync with our URL and the form yield return w; //we wait for the form to check the PHP file, so our game dont just hang if (w.error != null) { print(w.error); //if there is an error, tell us } else { EXPBar.nick = formNick; print("Test ok"); formText = w.text; //here we return the data our PHP told us w.Dispose(); //clear our form in game } formNick = ""; //just clean our variables formPassword = ""; }
IEnumerator LoginCR() { WWWForm form = new WWWForm(); string action="login"; form.AddField("id",FB.UserId); form.AddField("hash",Util.Md5Sum(safeHash)); form.AddField("action",action); WWW hs_post = new WWW(controllerPHP,form); yield return hs_post; if (hs_post.error!=null){ Debug.Log ("ERRO |"+hs_post.error+"|"); }else{ JSONObject jObj=new JSONObject(hs_post.text); Debug.Log (Regex.Unescape(hs_post.text)+" FOI AQUI"); if (Regex.Unescape(hs_post.text)==""){ Debug.Log ("SUCESSO"); }else if (jObj["result"].str!=null){ }else{ } } }
/// <summary> /// Adds Score to database /// </summary> /// <param name="name"></param> /// <param name="id"></param> /// <param name="score"></param> /// <returns></returns> private IEnumerator AddScore(string name, string id, string score) { WWWForm f = new WWWForm(); f.AddField("ScoreID", id); f.AddField("Name", name); f.AddField("Point", score); WWW w = new WWW("demo/theappguruz/score/add", f); yield return w; if (w.error == null) { JSONObject jsonObject = new JSONObject(w.text); string data = jsonObject.GetField("Status").str; if (data != null && data.Equals("Success")) { Debug.Log("Successfull"); } else { Debug.Log("Fatel Error"); } } else { Debug.Log("No Internet Or Other Network Issue" + w.error); } }
public IEnumerator CreatePlantType() { WWWForm form = new WWWForm (); form.AddField ("common_name", commonName); form.AddField ("latin_name", latinName); //form.AddField ("plant_size", "short-leafy"); //form.AddField ("model", "http://" + DataManager.dataManager.ipAddress + "/plantModel/1/"); print (DataManager.dataManager.ipAddress); string url = DataManager.dataManager.ipAddress + ptSuffix;//plantTypeURL;//string.Concat (plantTypeURL, "/"); Debug.Log(url); object[] parms = new object[2] { url, form }; yield return DataManager.dataManager.StartCoroutine("PostRequest", parms); /* WWW www = new WWW (url, form); yield return www; if (!string.IsNullOrEmpty (www.error)) { print (www.error); print (www.text); } */ addPlantModule.gameObject.SetActive (true); addPlantModule.StartCoroutine ("GetPlantTypes"); EndModule (); yield return null; }
//POST请求(Form表单传值、效率低、安全 ,) IEnumerator POST(string url, Dictionary<string, string> post) { //表单 WWWForm form = new WWWForm(); //从集合中取出所有参数,设置表单参数(AddField()). foreach (KeyValuePair<string, string> post_arg in post) { form.AddField(post_arg.Key, post_arg.Value); } //表单传值,就是post WWW www = new WWW(url, form); yield return www; mJindu = www.progress; if (www.error != null) { //POST请求失败 mContent = "error :" + www.error; } else { //POST请求成功 mContent = www.text; } }
IEnumerator save_answer() { string urlMessage = "https://ilearn-td.herokuapp.com/api/records/save_answer"; WWWForm form = new WWWForm (); // pass the email authentication string user_email = ButtonLogin.user_email; form.AddField ("email", user_email); form.AddField ("quiz", 1); form.AddField ("question", "In what form does light travel?"); form.AddField ("answer", chosenSolution); if (rightAnswer) { form.AddField ("correct", 1); } else { form.AddField("correct", 0); } WWW w = new WWW(urlMessage, form); yield return w; if (!string.IsNullOrEmpty (w.error)) { // this is done if the authentication is rejected or the response has // value >= 400 which means error in authentication or connection or server is down Debug.Log("The record is not saved"); } else { // if the response has OK status } }
private IEnumerator doLogin() { string url = connect.getURL() + "/login/login.php"; // isSucess = false; WWWForm form = new WWWForm(); Debug.Log("initial Login:"******","+user.getPassword()); form.AddField("act", user.getAccount()); form.AddField("psd", user.getPassword()); form.AddField("hash", connect.getHash()); byte[] rawData = form.data; WWW www = new WWW(url, rawData); yield return www; // check for errors if (www.error == null) { string temp = www.text; Debug.Log("temp:" + temp + " num:" + temp.Length); Debug.Log(www.text); if (temp.Length == 5) //success login { user.loadAllfromServer(); changeScene("Main"); } else//帳密有誤 { changeScene("Login"); } } else { changeScene("Login"); Debug.Log("WWW Error: " + www.error); } }
public static WWW Prepare(string section, string action, Dictionary<string,object> postdata = null) { if(postdata == null) { postdata = new Dictionary<string,object>(); } else { postdata.Remove ("publickey"); postdata.Remove ("section"); postdata.Remove ("action"); } postdata.Add ("publickey", PUBLICKEY); postdata.Add ("section", section); postdata.Add ("action", action); var json = PJSON.JsonEncode(postdata); var post = new WWWForm(); post.AddField("data", PEncode.Base64(json)); post.AddField("hash", PEncode.MD5 (json + PRIVATEKEY)); return new WWW(APIURL, post); }
public IEnumerator WaitForRequest() { // yield return new WaitForEndOfFrame(); WWWForm form = new WWWForm(); form.AddField("username", Id.name); form.AddField("wheatbought", f.aaa); form.AddField("dogsbought", 3); form.AddField("timeplayed", 4); form.AddField("timeplayedlvl1", 5); form.AddField("timeplayedlvl2", 6); form.AddField("timeplayedlvl3", 7); form.AddField("deathsinlvl1", 8); form.AddField("deathsinlvl2", 9); form.AddField("deathsinlvl3", 10); form.AddField("sheepkilledinlvl1", 11); form.AddField("sheepkilledinlvl2", 12); form.AddField("sheepkilledinlvl3", 13); form.AddField("score", 14); www = new WWW(url, form); yield return www; if (!string.IsNullOrEmpty(www.error)) { print(www.error); } else { print("Finished Uploading scores"); } }
public void SavePosi() { { //when the button is clicked //setup url to the ASP.NET webpage that is going to be called string customUrl = url + "SameGame/Create"; //setup a form WWWForm form = new WWWForm(); //Setup the paramaters //Save the perks position string x = transform.position.x.ToString("0.00"); string y = transform.position.y.ToString("0.00"); string z = transform.position.z.ToString("0.00"); string rx = transform.rotation.x.ToString("0.00"); string ry = transform.rotation.y.ToString("0.00"); string rz = transform.rotation.z.ToString("0.00"); form.AddField("PerksName", transform.name); form.AddField("PerkPosition", x + "," + y + "," + z); form.AddField("PerkRotation", rx + "," + ry + "," + rz); form.AddField("Username", username + ""); //Call the server WWW www = new WWW(customUrl, form); StartCoroutine(WaitForRequest(www)); } }
IEnumerator SetScore(int score, string name, string url) { WWWForm form = new WWWForm(); form.AddField("Name", name); form.AddField("Record", score); WWW w = new WWW(url, form); yield return w; if (!string.IsNullOrEmpty(w.error)) { print(w.error); } else { switch (w.text) { case "1": print("Sucesso"); break; case "-1": print( "Erro ao cadastrar."); break; default: print(w.text); break; } } }
IEnumerator LoadFromPHP() { WWWForm form = new WWWForm(); form.AddField("Service", "Load"); form.AddField("User", "teste"); WWW w = new WWW(url, form); yield return w; Debug.Log(w.text); if (w.text == "error") { //USUARIO NAO EXISTE Debug.Log ("NAO ECZISTE!"); } else { string[] datas = w.text.Split(';'); foreach(string data in datas) { string[] info = data.Split('='); switch(info[0]) { case "XP": XP = int.Parse(info[1]); break; case "Nivel": Nivel = int.Parse(info[1]); break; case "Lvl_Max": Lvl_Max = int.Parse(info[1]); break; } } } }
public IEnumerator GetCountUser() { //todo offline //if (EndGetCountUserEvent != null) //{ // EndGetCountUserEvent(0); //} //yield break; WWWForm form = new WWWForm(); form.AddField(GameConst.NameHeaderParamKey, GetKeyMD5("counter", GameConst.SekretKey)); Debug.Log(string.Format("{0} {1} {2}", "GetCountUser key", "counter", GetKeyMD5("counter", GameConst.SekretKey))); form.AddField("action", "counter"); WWW www = new WWW(GameConst.URLServer, form); yield return www; if (www.error != null) { Debug.Log(www.error); yield break; } if (EndGetCountUserEvent != null) { var aaa = int.Parse(www.text) + 7500; EndGetCountUserEvent(aaa); } }
private IEnumerator LoginAccess() { WWWForm form = new WWWForm (); form.AddField ("name", loginManager.GetPlayerName()); form.AddField ("room_no", loginManager.GetRoomNo()); WWW download = new WWW ("http://" + loginManager.GetURL() + "/users/login", form); yield return download; if (download.error == null) { Debug.Log (download.text); loginManager.ShowSuccess(); loginSuccess = true; loginManager.ShowWaiting(); // cast var json = Json.Deserialize(download.text) as Dictionary<string, object>; // keep status userManager.user_id = (long)json["user_id"]; userManager.play_id = (long)json["play_id"]; userManager.state = (string)json["state"]; userManager.role = (string)json["role"]; } else { Debug.Log ("Error"); loginManager.ShowError(); } }
public void RegisterWithAccount() { string email = txtEmail.text; string password = txtPassword.text; string confirm = txtConfirm.text; if (email.Length == 0 || password.Length == 0 || confirm.Length == 0) { Debug.LogError("Khong duoc de trong!"); return; } if (!password.Equals (confirm)) { Debug.LogError("Mat khau khong trung khop!"); return; } if (!toggleAgree.isOn) { Debug.LogError ("Chua dong y dieu khoan"); return; } int iRand = Random.Range (0, 27); string avatar = @"/assets/images/avatar/" + (iRand < 10 ? "00" + iRand : "0" + iRand) + ".png"; WWWForm formReg = new WWWForm(); formReg.AddField("name", email); formReg.AddField("email", email); formReg.AddField("password", password); formReg.AddField ("avatar", avatar); WWW regHTTP = new WWW(Constants.URLREG, formReg); StartCoroutine(WaitForRegRequest(regHTTP)); }
IEnumerator LoadFromPHP() { WWWForm form = new WWWForm(); form.AddField("Service", "Load"); form.AddField ("UserID", tw.su.Nick); WWW w = new WWW(url, form); yield return w; Debug.Log(w.text); if (w.text == "error") { //USUARIO NAO EXISTE Debug.Log ("NAO ECZISTE!"); } else { string[] datas = w.text.Split(';'); foreach(string data in datas) { string[] info = data.Split('='); switch(info[0]) { case "XP": sld.value = int.Parse(info[1]); break; case "Senha": tw.tst.lvlPlayer = int.Parse(info[1]); break; } } } }
public void CreateAccount(string id, string password, CallBackPtr func = null, int score = 0, int soft_cash = 0, int hard_cash = 0, int equipment = 0, int item = 0, int buying_equipment_body = 0, int buying_equipment_eye = 0, int buying_equipment_mouth = 0, int buying_equipment_fin = 0, int hp_lv = 0, //int scale_lv = 0, int speed_lv = 0, int fever_lv = 0, string nick_name = "", int exp_lv = 0, int exp_sub = 0){ WWWForm form = new WWWForm(); form.AddField("action", "create"); form.AddField("id",id); form.AddField("password",password); form.AddField("score",score); form.AddField("soft_cash",soft_cash); form.AddField("hard_cash",hard_cash); form.AddField("equipment",equipment); form.AddField("item",item); form.AddField("buying_equipment_eye", buying_equipment_eye); form.AddField("buying_equipment_body", buying_equipment_body); form.AddField("buying_equipment_mouth", buying_equipment_mouth); form.AddField("buying_equipment_fin", buying_equipment_fin); form.AddField("hp_lv", hp_lv); //form.AddField("scale_lv", scale_lv); form.AddField("speed_lv", speed_lv); form.AddField("fever_lv", fever_lv); form.AddField("nick_name", nick_name); form.AddField("exp_lv", exp_lv); form.AddField("exp_sub", exp_sub); StartCoroutine(WaitingForResponse(new WWW(URL, form), func)); form = null; }
// Use this for initialization void Start() { WWWForm form = new WWWForm (); form.AddField("UID",1); data = new WWW ("http://128.199.83.67/APPgame/backside/php/getleveldata.php", form); StartCoroutine (get_data_from_mysql (data)); }
private IEnumerator board_info_send() { string sendu_n = u_n.ToString (); u_n = unit_movement.unit_no; x = this.transform.position.x; y = this.transform.position.y; float posx = x / (float)-0.75; float posy = (y / (float)-0.8) + (float)0.3; string strx = posx.ToString (); string stry = posy.ToString (); string url = "http://192.168.3.83:3000/plays/update.json"; WWWForm form = new WWWForm (); form.AddField ("play_id", pid); form.AddField ("user_id", uid); form.AddField ("move_id", sendu_n); form.AddField ("posx", strx); form.AddField ("posy", stry); form.AddField ("promote", "false"); form.AddField ("get_id", get_id); Debug.Log ("get_id = " + get_id); WWW www = new WWW (url, form); yield return www; if (www.error == null) { Debug.Log (www.text); } }
private static void LogCallback(string message, string trace, LogType type) { if (System.Array.IndexOf(logTypes, type) != -1) { string supportData = null; try { if (collectSupportData != null) { supportData = collectSupportData(); } } catch { } try { var form = new WWWForm(); form.AddField("application", SafeString(appName)); form.AddField("version", SafeString(version)); form.AddField("userData", SafeString(userData)); form.AddField("supportData", SafeString(supportData)); form.AddField("userId", SafeString(userId)); form.AddField("message", SafeString(message)); form.AddField("trace", SafeString(trace)); new WWW(uri, form.data); } catch { } } }
// Use this for initialization IEnumerator Start() { // Create a form object for sending high score data to the server WWWForm form = new WWWForm(); //Retrieves the Leo number from the use to submit to the url form.AddField ("ctl00$Copy$leonumber", leoDiamondNumber); // Create a download object WWW download = new WWW( traceLeo_url, form ); // Wait until the download is done yield return download; if(!string.IsNullOrEmpty(download.error)) { print( "Error downloading: " + download.error ); } else { // show the data Debug.Log(download.text); if(download.text.Contains("ctl00_Copy_rolLink")){ Debug.Log("LEO DIAMOND TRACED!!!"); }else{ Debug.Log("Nope. Sorry."); } } }
IEnumerator LoginCoroutine(string username, string password) { WWWForm loginForm = new WWWForm (); loginForm.AddField ("myform_username", username); loginForm.AddField ("myform_password", password); loginForm.AddField ("myform_hash", server.SecretKey); WWW www = new WWW (server.Url + "/php/Login.php", loginForm); yield return www; if (www.error != null) { response.text = "Error communicating with server: " + www.error; } else { string wwwOutput = www.text; if (wwwOutput == "PASSWORD CORRECT") { server.Login (username, password); response.text = wwwOutput; yield return new WaitForSeconds(0.5f); FindObjectOfType<LevelManager> ().LoadLevel ("Initialising"); } else { response.text = wwwOutput; } } }
// it looks like most of the classes using the DatabaseManager have callbacks that only use the string 'data' to process, so we could cache these strings // based on the parameter set passed in, like 'LoadCases','Owner', or 'LoadCase', 'caseName', and the string containing the data we want to use for offline session public void DBCallOffline(string URL, WWWForm form, DatabaseMgr.Callback callback){ // if we can find a match in our list of cached responses, send it back // first, find the arguments string strFormData = Encoding.UTF8.GetString(form.data, 0, form.data.Length); //"command=cmd¶m=paramvalue" string[] fields = strFormData.Split ('&'); string command = ""; string param1 = ""; string[] pair; if (fields [0].Contains ("=")) { pair = fields [0].Split ('='); command = pair [1]; if (fields.Length > 1 && fields[1].Contains("=")){ pair = fields [1].Split ('='); param1 = pair [1].Replace("+"," "); } } string data = ""; foreach (CachedDBResult result in OfflineDBResults) { if (result.command == command && result.param1 == param1){ data = result.data; break; } } // don't use coroutine here because the timescale might be 0 and // then we will never return... //StartCoroutine(CallbackAfterDelay(callback,data)); // do callback if ( callback != null ) callback(true,data,"",null); }
public IEnumerator GetCharaList() { Debug.Log ("GetCharaList"); string url = ConfURL.HOST_NAME+ConfURL.PLAYER_LIST; WWWForm form = new WWWForm (); form.AddField ("UUID", _uuid); WWW www = new WWW(url, form); yield return www; Debug.Log (www); if (www.error != null) { Debug.Log("Error"); } else { Debug.Log("Success"); var charaAPI = MiniJSON.Json.Deserialize (www.text) as Dictionary<string,object>; foreach(KeyValuePair<string, object> data in charaAPI) { Debug.Log(data.Key); Debug.Log(data.Value); } } }
public void NameCheckRequest(string playername, int checkNumber) { WWWForm nameform = new WWWForm(); nameform.AddField("name", playername); WWW www1 = new WWW(namecheckurl, nameform); StartCoroutine(WaitForNameCheck(www1,checkNumber,playername)); }
IEnumerator sendData() { Debug.Log("signUp button pressed"); WWWForm signUpForm = new WWWForm(); Debug.Log("Entered email text: " + emailField.text); signUpForm.AddField("UserEmail", emailField.text); Debug.Log("Entered password text: " + passwordField.text); signUpForm.AddField("UserPassword", passwordField.text); WWW php = new WWW(url, signUpForm); yield return php; //we wait for the form to check the PHP file, so our game dont just hang if (php.error != null) { print(php.error); //if there is an error, tell us } else { print("Test ok"); formText = php.text; //here we return the data our PHP told us php.Dispose(); //clear our form in game print(formText); } }
private IEnumerator SendScore() { if (!button.IsInteractable()) yield break; WWWForm form = new WWWForm(); System.Collections.Generic.Dictionary<string,string> headers = form.headers; Hashtable rawData = new Hashtable(); rawData ["name"] = GameObject.FindGameObjectWithTag("EmailInput").GetComponent<InputField>().text; rawData ["score"] = Player.score; rawData ["device"] = SystemInfo.deviceModel; rawData ["duration"] = Time.timeSinceLevelLoad.ToString (); string json = "{\"score\":\""+rawData["score"]+"\","+ " \"duration\":\""+rawData["duration"]+"\","+ " \"name\":\""+rawData["name"]+"\","+ " \"device\":\""+rawData["device"]+"\" }"; byte[] bytes = Encoding.UTF8.GetBytes(json); headers["Content-Type"] = "application/json"; headers["X-Parse-Application-Id"] = "AgbCv2IdOihHPcIuvH3PItFACXiwNG0pDfVuuvnD"; headers["X-Parse-REST-API-Key"] = "9YPTNj3LuPArgOUImPhUQKi5jqkhSfLKb3IvMnfd"; headers["X-Parse-Master-Key"] = "ycsMy49UqD1T5IbmhffM1uuNuKXBcfIL2g314I0q"; WWW postRequest = new WWW( scorePostUrl, bytes, headers ); yield return postRequest; if (!string.IsNullOrEmpty(postRequest.error)) { Debug.Log(postRequest.error); } else { Debug.Log("Finished Uploading Scores"); Initiate.Fade(restartScene, null, 0.95f); } }
public IEnumerator ScreenshotHappy(int playerCount) { //Miro dove stanno i giocatori (trucco: con 0 fa tutto lo schermo Vector2 imageFrom = playerCount <=1 ? new Vector2(0, 0) : new Vector2(Screen.width / 2, Screen.height / 2); Vector2 imageTo = playerCount == 1 ? new Vector2(Screen.width / 2, Screen.height / 2) : new Vector2(Screen.width, Screen.height); byte[] temp = GetScreenshot(CaptureMethod.RenderToTex_Synch, imageFrom, imageTo).EncodeToJPG(); byte[] report = new byte[temp.Length]; for (int i = 0; i < report.Length; i++) { report[i] = (byte)temp[i]; } // for // create a form to send the data to the sever WWWForm form = new WWWForm(); // add the necessary data to the form form.AddBinaryData("upload_file", report, "spinder.jpg", "image/jpeg"); ; // send the data via web WWW www2 = new WWW("http://risingpixel.azurewebsites.net/other/apps/spinder/upload.php", form); // wait for the post completition while (!www2.isDone) { Debug.Log("I'm waiting... " + www2.uploadProgress); yield return new WaitForEndOfFrame(); } // while // print the server answer on the debug log Debug.Log(www2.text); // destroy the www www2.Dispose(); yield return null; taking = false; yield return new WaitForSeconds(.2f); }
public IEnumerator SendPurchasedLog(string price, string purchasedData, string signature) { string hash = Md5Sum(secretKey).ToLower(); string userUniNumber = ValueDeliverScript.UserID; float tempTime = 0; float ServerConnectionTimeout = 10.0f; WWWForm form = new WWWForm(); form.AddField("Unique_number", userUniNumber); form.AddField("Price", price); form.AddField("Detail_Data", purchasedData); form.AddField("Signature", signature); form.AddField("hash", hash); WWW www = new WWW(UpdatePurchasedLogUrl, form); yield return(www); while (!www.isDone && www.error == null && tempTime < ServerConnectionTimeout) { tempTime += Time.deltaTime; yield return(0); } if (www.error != null || tempTime >= ServerConnectionTimeout) { Debug.Log("Disconnected!!!!!!!!!!!!!!!!!!!!!!!!!!!"); Debug.Log(www.error); } else { wwwResult = www.text; if (wwwResult == "PurchaseLogUpdateSuccess") { Debug.Log(wwwResult); //여기에 결제 이후 처리내역 기입. if (price == "1.99") { Goods01.GetComponent <StoreCoinGoodScript>().Purchase(); GoogleIAB.consumeProduct("com.joywinggames.maydayaos001"); } if (price == "4.99") { Goods02.GetComponent <StoreCoinGoodScript>().Purchase(); GoogleIAB.consumeProduct("com.joywinggames.maydayaos002"); } if (price == "9.99") { Goods03.GetComponent <StoreCoinGoodScript>().Purchase(); GoogleIAB.consumeProduct("com.joywinggames.maydayaos003"); } if (price == "29.99") { Goods04.GetComponent <StoreCoinGoodScript>().Purchase(); GoogleIAB.consumeProduct("com.joywinggames.maydayaos004"); } if (price == "99.99") { Goods05.GetComponent <StoreCoinGoodScript>().Purchase(); GoogleIAB.consumeProduct("com.joywinggames.maydayaos005"); } } else { Debug.Log("PurchaseLogUpdate Fail!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); Debug.Log(wwwResult); Debug.Log(www.error); } } }
private void LoginClick() { m_loginButton.gameObject.SetActive(false); Text dogText = GameObject.Find("DogText").GetComponent <Text>(); dogText.text = "One moment please... "; string id = m_idField.text; string psw = m_pswField.text; WWWForm form = new WWWForm(); form.AddField("MurdochUserNumber", id); form.AddField("Password", psw); form.AddField("IsSim", 1); Logger.LogToFile("Sending login form"); NetworkManager.Instance.SendRequest(form, "login.php", (string reply) => { // Reply callback JSONObject replyObj = JSONObject.Create(reply); string status = ""; replyObj.GetField(ref status, "Status"); if (status == "ok") { // Extract data JSONObject data = replyObj.GetField("Data"); string firstName = ""; data.GetField(ref firstName, "FirstName"); string lastName = ""; data.GetField(ref lastName, "LastName"); string murdochUserNumber = ""; data.GetField(ref murdochUserNumber, "MurdochUserNumber"); dogText.text = "Welcome " + firstName + " the simulation will start in a moment"; string aMode = ""; data.GetField(out aMode, "AssessmentMode", "false"); bool assessmentMode = aMode.Equals("true"); UnityEngine.Debug.Log("AM " + assessmentMode); string order = ""; if (data.HasField("Layout")) { data.GetField(out order, "Layout", ""); order = order.Substring(2, order.Length - 4); } Debug.Log("Order: " + order); //Save info to PlayerPrefs PlayerPrefs.SetString("FirstName", firstName); PlayerPrefs.SetString("LastName", lastName); PlayerPrefs.SetString("MurdochUserNumber", murdochUserNumber); PlayerPrefs.SetInt("AssessmentMode", assessmentMode? 1 : 0); PlayerPrefs.SetString("InstrumentOrder", order); PlayerPrefs.Save(); StartCoroutine(StartNextScene()); } else { string errorMessage = ""; replyObj.GetField(ref errorMessage, "Message"); dogText.text = errorMessage; m_loginButton.gameObject.SetActive(true); } }, () => { dogText.text = "An error occurred. Please try again later."; m_loginButton.gameObject.SetActive(true); }, () => { // If all attempts to connect fail Logger.LogToFile("All attempts failed to log in, application will quit"); Application.Quit(); }); }
protected void DrawEntries() { _entriesHelpRect = EditorHelper.ShowHideableHelpBox("GameFramework.LocalisationEditorWindow.Entries", "Entries contain a set of unique tags that identify the text that you want to localise. You can further associate different translations with these tags for the different languages that you have setup.", _entriesHelpRect); // filter EditorGUILayout.BeginHorizontal(); GUI.changed = false; EditorGUI.BeginChangeCheck(); _filter = EditorGUILayout.TextField(_filter, GuiStyles.ToolbarSearchField, GUILayout.ExpandWidth(true)); if (EditorGUI.EndChangeCheck()) { foreach (var entryReference in _entryReferenceList) { entryReference.MatchesFilter = entryReference.Key.IndexOf(_filter, StringComparison.OrdinalIgnoreCase) >= 0; } } if (GUILayout.Button("", string.IsNullOrEmpty(_filter) ? GuiStyles.ToolbarSearchFieldCancelEmpty : GuiStyles.ToolbarSearchFieldCancel, GUILayout.ExpandWidth(false))) { _filter = ""; GUIUtility.keyboardControl = 0; foreach (var entryReference in _entryReferenceList) { entryReference.MatchesFilter = true; } } EditorGUILayout.EndHorizontal(); if (_entryReferenceList.Count == 0) { GUILayout.Space(20); EditorGUILayout.LabelField("Create new localisation entries below.", GuiStyles.CenteredLabelStyle, GUILayout.ExpandWidth(true)); GUILayout.Space(20); } else { _entriesScrollPosition = EditorGUILayout.BeginScrollView(_entriesScrollPosition, false, false, GUILayout.ExpandHeight(false)); //Debug.Log(Event.current.type + ": " +_entriesScrollHeight + ", " + _entriesScrollPosition); // here we avoid using properties due to them being very slow! var indexForDeleting = -1; //var accumulativeHeightDrawn = 0; //var accumulativeSpace = 0; for (var i = 0; i < _entryReferenceList.Count; i++) { var entryReference = _entryReferenceList[i]; if (entryReference.MatchesFilter) { //// if top is below viewport or bottom is above then this item is not visible. For repaint events we need to use the //// previously recorded display state to avoid changing the number of controls drawn. ////if ((Event.current.type == EventType.Repaint && entryData.IsShown == false) || //// (Event.current.type != EventType.Repaint && //if (((Event.current.type != EventType.Layout && entryReference.IsShown == false) || // (Event.current.type == EventType.Layout && // (accumulativeHeightDrawn > _entriesScrollPosition.y + _entriesScrollHeight || // accumulativeHeightDrawn + entryReference.Height < _entriesScrollPosition.y))) && !entryReference.IsExpanded) //{ // accumulativeHeightDrawn += entryReference.Height; // accumulativeSpace += entryReference.Height; // entryReference.IsShown = false; //} //else //{ // // fill space from skipped. // if (accumulativeSpace > 0) GUILayout.Space(accumulativeSpace); // accumulativeSpace = 0; // draw the displayed item entryReference.IsShown = true; var localisationEntry = _targetLocalisationData.GetEntry(_entryReferenceList[i].Key); EditorGUILayout.BeginHorizontal(); EditorGUI.indentLevel++; //var oldExpanded = entryReference.IsExpanded; entryReference.IsExpanded = EditorGUILayout.Foldout(entryReference.IsExpanded, localisationEntry.Key); // if we are not using a static default height (see below) then we need to flag changes to the expanded state, and in OnInspectorGUI // call repaint within a 'if (Event.current.type == EventType.Repaint && _updatePostRepaint)' check. This so that if an entry // decreases in size we correctly draw items that might previously have been hidden. //if (entryReference.IsExpanded != oldExpanded) // force repaint on changes incase new items become visable due to collapsing // _updatePostRepaint = true; EditorGUI.indentLevel--; if (GUILayout.Button("-", EditorStyles.miniButton, GUILayout.Width(GuiStyles.RemoveButtonWidth))) { indexForDeleting = i; break; } EditorGUILayout.EndHorizontal(); //if (Event.current.type == EventType.Repaint) //entryData.Height = (int)GUILayoutUtility.GetLastRect().height; // only works on repaint. entryReference.Height = _entriesDefaultRowHeight; // handle expended status if (entryReference.IsExpanded) { EditorGUILayout.BeginVertical(); EditorGUI.indentLevel++; for (var li = 0; li < localisationEntry.Languages.Length; li++) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(_targetLocalisationData.Languages[li].Name, GUILayout.Width(100)); EditorGUI.BeginChangeCheck(); var lang = EditorGUILayout.TextArea(localisationEntry.Languages[li], GuiStyles.WordWrapStyle, GUILayout.Width(Screen.width - 100 - 60 - 50)); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(_targetLocalisationData, "Edit Localisation Entry"); localisationEntry.Languages[li] = lang; _targetChanged = true; } // TODO: Move to a callback so we don't block the UI if (li > 0 && GUILayout.Button("Translate", EditorStyles.miniButton, GUILayout.Width(60))) { var sourceCode = _targetLocalisationData.Languages[0].Code; if (!string.IsNullOrEmpty(sourceCode)) { var targetCode = _targetLocalisationData.Languages[li].Code; if (!string.IsNullOrEmpty(targetCode)) { var sourceText = localisationEntry.Languages[0]; string url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + sourceCode + "&tl=" + targetCode + "&dt=t&q=" + WWW.EscapeURL(sourceText); var wwwForm = new WWWForm(); wwwForm.AddField("username", ""); //var headers = new Dictionary<string, string>(); wwwForm.headers.Add("content-type", "application/json"); var www = new WWW(url, wwwForm); while (!www.isDone) { ; } if (www.error != null) { Debug.LogError(www.error); } else { Debug.Log("Google Translate Response:" + www.text); var json = ObjectModel.Internal.SimpleJSON.JSONNode.Parse(www.text); if (json != null) { var translation = ""; for (var lines = 0; lines < json[0].Count; lines++) { // Dig through and take apart the text to get to the good stuff. var translatedText = json[0][lines][0].ToString(); if (translatedText.Length > 2) { translatedText = translatedText.Substring(1, translatedText.Length - 2); } if (translation.Length > 0) { translation += "\n"; } translation += translatedText.Replace("\\n", "").Replace("\\\"", "\""); } Undo.RecordObject(_targetLocalisationData, "Edit Localisation Entry"); localisationEntry.Languages[li] = translation; _targetChanged = true; } else { Debug.LogError("Unable to parse json response"); } } } else { EditorUtility.DisplayDialog("Localisation Import", "There is no code specified for the language '" + _targetLocalisationData.Languages[li].Name + "'.\n\nPlease enter under the languages tab.", "Ok"); } } else { EditorUtility.DisplayDialog("Localisation Translate", "There is no code specified for the language '" + _targetLocalisationData.Languages[0].Name + "'.\n\nPlease enter under the languages tab.", "Ok"); } } EditorGUILayout.EndHorizontal(); } EditorGUI.indentLevel--; EditorGUILayout.EndVertical(); // repaint events will give a new correct size for the last drawn rect so record here. //if (Event.current.type == EventType.Repaint) // entryReference.Height += (int)GUILayoutUtility.GetLastRect().height; // only works on repaint. //} //accumulativeHeightDrawn += entryReference.Height; // Debug.Log(entryData.LocalisationEntry.Key + ", " + accumulativeHeightDrawn); } } } //if (accumulativeSpace > 0) GUILayout.Space(accumulativeSpace); //Debug.Log(accumulativeHeightDrawn); EditorGUILayout.EndScrollView(); //if (Event.current.type == EventType.Repaint) // _entriesScrollHeight = GUILayoutUtility.GetLastRect().height; // only works on repaint. // delay deleting to avoid editor issues. if (indexForDeleting != -1) { var keyToDelete = _entryReferenceList[indexForDeleting].Key; if (EditorUtility.DisplayDialog("Delete Entry?", String.Format("Are you sure you want to delete the entry '{0}?'", keyToDelete), "Yes", "No")) { Undo.RecordObject(_targetLocalisationData, "Delete Localisation Entry"); _targetLocalisationData.RemoveEntry(keyToDelete); _entryReferenceList.RemoveAt(indexForDeleting); _targetChanged = true; } } } // add functionality EditorGUILayout.BeginHorizontal(); bool entryAddPressed = false; if (GUI.GetNameOfFocusedControl() == "EntryAdd" && Event.current.type == EventType.KeyDown && (Event.current.keyCode == KeyCode.KeypadEnter || Event.current.keyCode == KeyCode.Return)) { entryAddPressed = true; Event.current.Use(); } GUI.SetNextControlName("EntryAdd"); _newKey = EditorGUILayout.TextField("", _newKey, GUILayout.ExpandWidth(true)); var isValidEntry = !string.IsNullOrEmpty(_newKey) && !_targetLocalisationData.ContainsEntry(_newKey); GUI.enabled = isValidEntry; if (entryAddPressed || GUILayout.Button(new GUIContent("Add", "Add the specified entry to the list"), EditorStyles.miniButton, GUILayout.Width(100))) { if (isValidEntry) { Undo.RecordObject(_targetLocalisationData, "Add Localisation Entry"); _targetLocalisationData.AddEntry(_newKey); _targetChanged = true; _languagesCount = _targetLocalisationData.Languages.Count; // set incase a first language was autocreated. var insertIndex = 0; var scrollOffset = 0; for (; insertIndex < _entryReferenceList.Count; insertIndex++) { if (_newKey.CompareTo(_entryReferenceList[insertIndex].Key) < 0) { break; } else { scrollOffset += _entryReferenceList[insertIndex].Height; } } _entryReferenceList.Insert(insertIndex, new EntryReference() { Key = _newKey, MatchesFilter = _newKey.IndexOf(_filter + "", StringComparison.OrdinalIgnoreCase) >= 0, IsExpanded = true }); _entriesScrollPosition.y = scrollOffset; var lastDot = _newKey.LastIndexOf("."); if (lastDot == -1) { _newKey = ""; } else { _newKey = _newKey.Substring(0, lastDot + 1); } } GUI.FocusControl("EntryAdd"); } GUI.enabled = true; EditorGUILayout.EndHorizontal(); GUILayout.Space(5); GUI.enabled = _entryReferenceList.Count > 0; if (GUILayout.Button(new GUIContent("Delete All", "Delete All entries"), EditorStyles.miniButton, GUILayout.Width(100))) { Undo.RecordObject(_targetLocalisationData, "Delete Localisation Entry"); _targetLocalisationData.ClearEntries(); _entryReferenceList.Clear(); _targetChanged = true; } GUI.enabled = true; }
IEnumerator login() { WWWForm form = new WWWForm(); form.AddField("myField", "myData"); using ( UnityWebRequest www = UnityWebRequest.Post("http://game.psikologicare.com/api/login?name=" + nama.text + "&password="******"", form)) { yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { // Debug.Log (www.error); //error.text = www.downloadHandler.text; //error.text = "Username atau Password Anda Salah"; } else { //menulogin.SetActive(false); //menuindentitas.SetActive(true); //Debug.Log(www.downloadHandler.text); //string dat = www.downloadHandler.text; JSONNode jsonData = JSON.Parse(System.Text.Encoding.UTF8.GetString(www.downloadHandler.data)); token = jsonData["token"]; id = jsonData["user_id"]; Debug.Log(token); Debug.Log(jsonData); SceneManager.LoadScene("catatan"); if (jsonData == null) { Debug.Log("ora ono"); } else { int namaContoh = jsonData["attribute"].Count; //string namaContoh = jsonData["attribute"]["nama"]["attribute"].ToString(); //string replaceNama = namaContoh.Replace("{", ""); Debug.Log(namaContoh); if (jsonData["attribute"] == "text") { Debug.Log("attribute" + jsonData["attribute"]); } string namaNama = jsonData["attribute"]["nama"]; //Debug.Log(" nama " + namaNama); string[] attributes = { "nama", "tgl_lahir", "jenis_kelamin", "pendidikan", "tempat_lahir", "alamat", "desa" }; string[] namaChid = { "attribute", "label", "type", "validator" }; for (int i = 0; i <= attributes.Length - 1; i++) { //Debug.Log(jsonData[attributes[0]]); if (jsonData["attribute"][attributes[i]][namaChid[2]] == "text") { //string [] text = { jsonData["attribute"][attributes[i]][namaChid[1]] }; //Debug.Log("bentuk "+ jsonData["attribute"][attributes[i]][namaChid[1]]); //Debug.Log("label nama count" + text.Length); //labelTempat_lahir.text = jsonData["attribute"][attributes[i]][namaChid[1]]; //Debug.Log("input text" + jsonData["attribute"][attributes[i]][namaChid[1]]); if (jsonData["attribute"][attributes[i]][namaChid[1]] == "Nama") { //Nama.SetActive(true); } if (jsonData["attribute"][attributes[i]][namaChid[1]] == "Tempat Lahir") { //Tempat_Lahir.SetActive(true); } if (jsonData["attribute"][attributes[i]][namaChid[1]] == "Kewarganegaraan") { // Kewarganegaraan.SetActive(true); } } if (jsonData["attribute"][attributes[i]][namaChid[2]] == "date") { if (jsonData["attribute"][attributes[i]][namaChid[1]] == "Tgl Lahira") { //Tgl_lahir.SetActive(true); } if (jsonData["attribute"][attributes[i]][namaChid[1]] == "Tgl Tes") { //Tgl_Tes.SetActive(true); } //labelTgl_lahir.text = jsonData["attribute"][attributes[i]][namaChid[1]]; //Debug.Log("input date"); } if (jsonData["attribute"][attributes[i]][namaChid[2]] == "radio") { if (jsonData["attribute"][attributes[i]][namaChid[1]] == "Gender") { //Jenis_kelamin.SetActive(true); } //labelJenis_kelamin.text = jsonData["attribute"][attributes[i]][namaChid[1]]; //Debug.Log("input radio"); } if (jsonData["attribute"][attributes[i]][namaChid[2]] == "dropdown") { if (jsonData["attribute"][attributes[i]][namaChid[1]] == "Pendidikan Terakhir") { // Pendidikan.SetActive(true); } //labelPendidikan.text = jsonData["attribute"][attributes[i]][namaChid[1]]; //Debug.Log("input dropdown"); } if (jsonData["attribute"][attributes[i]][namaChid[2]] == "textarea") { if (jsonData["attribute"][attributes[i]][namaChid[1]] == "Alamat Tinggal") { //Alamat.SetActive(true); } //labelAlamat.text = jsonData["attribute"][attributes[i]][namaChid[1]]; //Debug.Log("input textarea"); } } string value = "replaceNama"; //string[] result = namaContoh.Split(','); ///Debug.Log(result); char[] array = value.ToCharArray(); for (int i = 0; i < array.Length; i++) { char letter = array[i]; //Debug.Log("letter : " + letter); } } } } }
internal static IEnumerator SendRequest(HttpRequest request, Action <int /*statusCode*/, string /*data*/, string /*error*/> completionHandler) { // timeout feature added in 5.6.2f1 #if UNITY_5_6_OR_NEWER && !UNITY_5_6_0 && !UNITY_5_6_1 UnityWebRequest www = new UnityWebRequest(); www.url = request.URL; www.timeout = request.TimeoutSeconds; www.downloadHandler = new DownloadHandlerBuffer(); if (request.HTTPMethod == HttpRequest.HTTPMethodType.POST) { www.method = UnityWebRequest.kHttpVerbPOST; foreach (var entry in request.getHeaders()) { www.SetRequestHeader(entry.Key, entry.Value); } byte[] bytes = Encoding.UTF8.GetBytes(request.HTTPBody); www.uploadHandler = new UploadHandlerRaw(bytes); #if !UNITY_2019_3_OR_NEWER www.chunkedTransfer = false; #endif } else { www.method = UnityWebRequest.kHttpVerbGET; } #if UNITY_2017_2_OR_NEWER yield return(www.SendWebRequest()); #else yield return(www.Send()); #endif if (completionHandler != null) { completionHandler((int)www.responseCode, www.downloadHandler.text, www.error); } #else WWW www; if (request.HTTPMethod == HttpRequest.HTTPMethodType.POST) { Dictionary <string, string> headers = new Dictionary <string, string>(); WWWForm form = new WWWForm(); foreach (var entry in Utils.HashtableToDictionary <string, string>(form.headers)) { headers[entry.Key] = entry.Value; } foreach (var entry in request.getHeaders()) { headers[entry.Key] = entry.Value; } byte[] bytes = Encoding.UTF8.GetBytes(request.HTTPBody); www = new WWW(request.URL, bytes, headers); } else { www = new WWW(request.URL); } float timer = 0; bool timedout = false; while (!www.isDone) { if (timer > request.TimeoutSeconds) { timedout = true; break; } timer += Time.deltaTime; yield return(null); } int statusCode = 1001; string data = null; string error = null; if (timedout) { www.Dispose(); error = "connect() timed out"; } else { statusCode = ReadStatusCode(www); data = www.text; error = www.error; } if (completionHandler != null) { completionHandler(statusCode, data, error); } #endif // UNITY_5_6_OR_NEWER }
/// <summary> /// Installs the target application on the target device. /// </summary> /// <param name="appFullPath"></param> /// <param name="targetDevice"></param> /// <param name="waitForDone">Should the thread wait until installation is complete?</param> /// <returns>True, if Installation was a success.</returns> public static bool InstallApp(string appFullPath, ConnectInfo targetDevice, bool waitForDone = true) { bool success = false; try { // Calculate the cert and dependency paths string fileName = Path.GetFileName(appFullPath); string certFullPath = Path.ChangeExtension(appFullPath, ".cer"); string certName = Path.GetFileName(certFullPath); string depPath = Path.GetDirectoryName(appFullPath) + @"\Dependencies\x86\"; // Post it using the REST API var form = new WWWForm(); // APPX file Debug.Assert(appFullPath != null); using (var stream = new FileStream(appFullPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var reader = new BinaryReader(stream)) { form.AddBinaryData(fileName, reader.ReadBytes((int)reader.BaseStream.Length), fileName); } } // CERT file Debug.Assert(certFullPath != null); using (var stream = new FileStream(certFullPath, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var reader = new BinaryReader(stream)) { form.AddBinaryData(certName, reader.ReadBytes((int)reader.BaseStream.Length), certName); } } // Dependencies FileInfo[] depFiles = new DirectoryInfo(depPath).GetFiles(); foreach (FileInfo dep in depFiles) { using (var stream = new FileStream(dep.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) { using (var reader = new BinaryReader(stream)) { string depFilename = Path.GetFileName(dep.FullName); form.AddBinaryData(depFilename, reader.ReadBytes((int)reader.BaseStream.Length), depFilename); } } } // Query string query = string.Format(API_InstallQuery, FinalizeUrl(targetDevice.IP)); query += "?package=" + WWW.EscapeURL(fileName); var response = WebRequestPost(query, form, GetBasicAuthHeader(targetDevice)); if (string.IsNullOrEmpty(response)) { Debug.LogErrorFormat("Failed to install {0} on {1}.\n", fileName, targetDevice.MachineName); return(false); } // Wait for done (if requested) DateTime waitStartTime = DateTime.Now; while (waitForDone && (DateTime.Now - waitStartTime).TotalSeconds < MaxWaitTime) { EditorUtility.DisplayProgressBar("Connecting to Device Portal", "Installing...", (float)((DateTime.Now - waitStartTime).TotalSeconds / MaxWaitTime)); AppInstallStatus status = GetInstallStatus(targetDevice); if (status == AppInstallStatus.InstallSuccess) { Debug.LogFormat("Successfully installed {0} on {1}.", fileName, targetDevice.MachineName); success = true; break; } if (status == AppInstallStatus.InstallFail) { Debug.LogErrorFormat("Failed to install {0} on {1}.\n", fileName, targetDevice.MachineName); break; } // Wait a bit and we'll ask again Thread.Sleep(1000); } EditorUtility.ClearProgressBar(); } catch (Exception e) { Debug.LogException(e); success = false; } return(success); }
/// <summary> /// Send a Unity Web Request to POST. /// </summary> /// <param name="query">Full Query to GET</param> /// <param name="postData">Post Data</param> /// <param name="auth">Authorization Header</param> /// <param name="showDialog">Show the progress dialog.</param> /// <returns>Response string.</returns> private static string WebRequestPost(string query, WWWForm postData, string auth, bool showDialog = true) { try { using (var webRequest = UnityWebRequest.Post(query, postData)) { webRequest.SetRequestHeader("Authorization", auth); #if UNITY_2017_1_OR_NEWER webRequest.timeout = (int)TimeOut; #endif // HACK: Workaround for extra quotes around boundary. string contentType = webRequest.GetRequestHeader("Content-Type"); if (contentType != null) { contentType = contentType.Replace("\"", ""); webRequest.SetRequestHeader("Content-Type", contentType); } #if UNITY_2017_2_OR_NEWER webRequest.SendWebRequest(); #else webRequest.Send(); #endif while (!webRequest.isDone) { if (webRequest.uploadProgress > -1 && showDialog) { EditorUtility.DisplayProgressBar("Connecting to Device Portal", "Uploading...", webRequest.uploadProgress); } else if (webRequest.downloadProgress > -1 && showDialog) { EditorUtility.DisplayProgressBar("Connecting to Device Portal", "Progress...", webRequest.downloadProgress); } } EditorUtility.ClearProgressBar(); if ( #if UNITY_2017_1_OR_NEWER webRequest.isNetworkError || webRequest.isHttpError && #else webRequest.isNetworkError&& #endif // UNITY_2017_1_OR_NEWER webRequest.responseCode != 401) { string response = string.Empty; var responseHeaders = webRequest.GetResponseHeaders(); if (responseHeaders != null) { response = responseHeaders.Aggregate(string.Empty, (current, header) => string.Format("{0}{1}: {2}\n", current, header.Key, header.Value)); } Debug.LogErrorFormat("Network Error: {0}\n{1}", webRequest.error, response); return(string.Empty); } switch (webRequest.responseCode) { case 200: case 202: return(webRequest.downloadHandler.text); case 401: Debug.LogError("Unauthorized: Access is denied due to invalid credentials."); break; default: Debug.LogError(webRequest.responseCode); break; } } } catch (Exception e) { Debug.LogException(e); } return(string.Empty); }
/// <summary> /// 增加 Web 请求任务。 /// </summary> /// <param name="webRequestUri">Web 请求地址。</param> /// <param name="wwwForm">WWW 表单。</param> /// <param name="priority">Web 请求任务的优先级。</param> /// <param name="userData">用户自定义数据。</param> /// <returns>新增 Web 请求任务的序列编号。</returns> public int AddWebRequest(string webRequestUri, WWWForm wwwForm, int priority, object userData) { return(AddWebRequest(webRequestUri, null, wwwForm, priority, userData)); }
/// <summary> /// 增加 Web 请求任务。 /// </summary> /// <param name="webRequestUri">Web 请求地址。</param> /// <param name="wwwForm">WWW 表单。</param> /// <returns>新增 Web 请求任务的序列编号。</returns> public int AddWebRequest(string webRequestUri, WWWForm wwwForm) { return(AddWebRequest(webRequestUri, null, wwwForm, DefaultPriority, null)); }
/// <summary> /// 增加 Web 请求任务。 /// </summary> /// <param name="webRequestUri">Web 请求地址。</param> /// <param name="postData">要发送的数据流。</param> /// <param name="wwwForm">WWW 表单。</param> /// <param name="priority">Web 请求任务的优先级。</param> /// <param name="userData">用户自定义数据。</param> /// <returns>新增 Web 请求任务的序列编号。</returns> private int AddWebRequest(string webRequestUri, byte[] postData, WWWForm wwwForm, int priority, object userData) { return(m_WebRequestManager.AddWebRequest(webRequestUri, postData, priority, WWWFormInfo.Create(wwwForm, userData))); }
IEnumerator LoginAccountFromServer(string email, string password) { WWWForm form1 = new WWWForm(); form1.AddField("email", email); form1.AddField("password", password); WWW www = new WWW(loginaccounturl, form1); yield return(www); print("message came" + www.text); if (www.text == "Incorrect password") { statusText.text = "Incorrect password"; statusText.color = Color.red; } else if (www.text == "server error") { statusText.text = "Server is in the maintainence"; statusText.color = Color.red; } else if (www.text == "") { statusText.text = "Check the connection"; statusText.color = Color.red; } else { if (www.text.Contains("id:")) { //account created successfully statusText.text = "Account created successfully"; statusText.color = Color.green; //update name on the top //extracting username string username = GetDataValue(www.text, "username:"******"id:"); int idnumber = Convert.ToInt32(idinstring); print(idnumber); saveload.id = idnumber; saveload.username = username; saveload.email = email; saveload.Save(); ActivatePanel(HomepagePannel.name); UpdateTopDetails(); EmailLoginInputText.text = ""; PasswordLoginInputText.text = ""; } else { statusText.text = "Server is in the maintainence"; statusText.color = Color.red; } } }
/// <summary> /// 增加 Web 请求任务。 /// </summary> /// <param name="webRequestUri">Web 请求地址。</param> /// <param name="wwwForm">WWW 表单。</param> /// <param name="priority">Web 请求任务的优先级。</param> /// <returns>新增 Web 请求任务的序列编号。</returns> public int AddWebRequest(string webRequestUri, WWWForm wwwForm, int priority) { return(AddWebRequest(webRequestUri, null, wwwForm, priority, null)); }
internal static IEnumerator SendRequest(HttpRequest request, Action <int /*statusCode*/, string /*data*/, string /*error*/> completionHandler) { WWW www; if (request.HTTPMethod == HttpRequest.HTTPMethodType.POST) { Dictionary <string, string> headers = new Dictionary <string, string>(); WWWForm form = new WWWForm(); foreach (var entry in Utils.HashtableToDictionary <string, string>(form.headers)) { headers[entry.Key] = entry.Value; } foreach (var entry in request.getHeaders()) { headers[entry.Key] = entry.Value; } byte[] bytes = Encoding.UTF8.GetBytes(request.HTTPBody); www = new WWW(request.URL, bytes, headers); } else { www = new WWW(request.URL); } float timer = 0; bool timedout = false; while (!www.isDone) { if (timer > request.TimeoutSeconds) { timedout = true; break; } timer += Time.deltaTime; yield return(null); } int statusCode = 1001; string data = null; string error = null; if (timedout) { www.Dispose(); error = "connect() timed out"; } else { statusCode = ReadStatusCode(www); data = www.text; error = www.error; } if (completionHandler != null) { completionHandler(statusCode, data, error); } }
public WWW(string dataUrl, WWWForm form) { }
public IEnumerator SendData(WWWForm form) { using (UnityWebRequest www = UnityWebRequest.Post("http://logs-01.loggly.com/inputs/ec76e028-01be-4652-99c6-e7f67eaeffb9/tag/Unity3D", form)) { yield return(www.SendWebRequest()); } }
IEnumerator CreateAccountFromServer(string username, string email, string password) { WWWForm form1 = new WWWForm(); form1.AddField("username", username); form1.AddField("email", email); form1.AddField("password", password); WWW www = new WWW(createaccounturl, form1); yield return(www); print("message came" + www.text); if (www.text == "Account Already Exist") { statusText.text = "Account alrady Exist"; statusText.color = Color.red; } else if (www.text == "") { statusText.text = "Check the connection"; statusText.color = Color.red; } else if (www.text == "Connection Failed") { statusText.text = "Server is in the maintainence"; statusText.color = Color.red; } else { if (www.text.Contains("id:")) { //account created successfully statusText.text = "Account created successfully"; statusText.color = Color.green; //update name on the top int temp = www.text.IndexOf(":"); string idinstring = www.text.Substring(temp + 1); int idnumber = Convert.ToInt32(idinstring); saveload.id = idnumber; saveload.username = username; saveload.email = email; saveload.Save(); ActivatePanel(HomepagePannel.name); UpdateTopDetails(); } else { statusText.text = "Server is in the maintainence"; statusText.color = Color.red; } } }
void OnGUI() { GUI.Label(new Rect(0, 0, 80, 20), username_label); username_input = GUI.TextField(new Rect(80, 0, 100, 20), username_input); GUI.Label(new Rect(0, 30, 80, 20), password_label); password_input = GUI.TextField(new Rect(80, 30, 100, 20), password_input); GUI.Label(new Rect(0, 60, 80, 20), password_label2); password_input2 = GUI.TextField(new Rect(80, 60, 100, 20), password_input2); GUI.Label(new Rect(0, 90, 80, 20), email_label); email_input = GUI.TextField(new Rect(80, 90, 100, 20), email_input); GUI.Label(new Rect(0, 160, 80, 20), callback_label); callback_label2 = GUI.TextField(new Rect(50, 160, 160, 20), callback_label2); if (GUI.Button(new Rect(0, 120, 100, 30), "Login")) { form = new WWWForm(); form.AddField("name", username_input); form.AddField("password", password_input); // string url = "http://192.168.100.98:8084/ddt/UserLogin.jsp"; url = "http://192.168.10.85:8050"; www = new WWW(url, form); StartCoroutine(WaitForRequestUserNameLogin(www)); } if (GUI.Button(new Rect(120, 120, 100, 30), "Register")) { form = new WWWForm(); form.AddField("id", SystemInfo.deviceUniqueIdentifier); form.AddField("name", username_input); form.AddField("password", password_input); form.AddField("retry_password", password_input2); form.AddField("email", email_input); // url = "http://192.168.100.98:8084/ddt/registerUser.jsp"; url = "http://192.168.10.85:8050"; www = new WWW(url, form); StartCoroutine(WaitForRequestRegister(www)); } // if (GUI.Button(new Rect(240, 120, 100, 30), "non-reg to play")) // { // form = new WWWForm(); // form.AddField("id", SystemInfo.deviceUniqueIdentifier); // //form.AddField("name", username_input); // //form.AddField("password", password_input); // //form.AddField("retry_password", password_input2); // //form.AddField("email", email_input); // url = "http://192.168.100.98:8084/ddt/NonRegPlay.jsp"; // www = new WWW(url, form); // StartCoroutine(WaitForRequestPhoneIdLogin(www)); // } // // if (GUI.Button(new Rect(200, 0, 130, 20), "Check UserName")) // { // form = new WWWForm(); // form.AddField("name", username_input); // Debug.Log("username_input...." + username_input); // url = "http://192.168.100.98:8084/ddt/CheckUserIsExist.jsp"; // www = new WWW(url, form); // StartCoroutine(WaitForRequestCheck(www)); // } // if (GUI.Button(new Rect(0, 200, 50, 30), "IMEI")) // { // callback_label2 = SystemInfo.deviceUniqueIdentifier; // } }
IEnumerator JoinPool() { WHOTMultiplayerManager.Instance.isOpponentReady = false; WHOTMultiplayerManager.Instance.isPlayerReady = false; WHOTMultiplayerManager.Instance.GetPhotonToken(); Debug.Log("Join Pool"); WWWForm form = new WWWForm(); form.AddField("poolid", poolId); UnityWebRequest www = UnityWebRequest.Post(UserDetailsManager.serverUrl + "joinpool", form); www.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded"); www.SetRequestHeader("Authorization", "Bearer " + UserDetailsManager.accessToken); www.timeout = 15; yield return(www.SendWebRequest()); Debug.Log("Join Pool Response: " + www.downloadHandler.text); var joinPoolDetails = MiniJSON.Json.Deserialize(www.downloadHandler.text) as IDictionary; if (www.error != null || www.isNetworkError) { Debug.Log("Error while trying o join pool: " + www.error); WhotUiManager.instance.errorPopup.GetComponent <PopUP>().title.text = "ERROR"; WhotUiManager.instance.errorPopup.GetComponent <PopUP>().msg.text = www.error; WhotUiManager.instance.errorPopup.SetActive(true); } else { if (www.downloadHandler.text.Contains("error")) { var errorDetails = (IDictionary)joinPoolDetails["result"]; WhotUiManager.instance.errorPopup.GetComponent <PopUP>().title.text = "ERROR"; WhotUiManager.instance.errorPopup.GetComponent <PopUP>().msg.text = errorDetails["error"].ToString(); WhotUiManager.instance.errorPopup.SetActive(true); } else { WHOTMultiplayerManager.Instance.startGameButton.gameObject.SetActive(false); WHOTMultiplayerManager.Instance.poolId = poolId; WHOTMultiplayerManager.Instance.canLeavePool = false; WHOTMultiplayerManager.Instance.winAmt = int.Parse(winningAmount); WHOTMultiplayerManager.Instance.betAmount = int.Parse(betAmount); if (senderName != UserDetailsManager.userName) { Debug.Log("playerNameText.text: " + senderName + " " + UserDetailsManager.userName); ChatGui.instance.sendPhotonNotification(senderName, UserDetailsManager.userName, " has accept your challenge"); } RoomOptions roomOptions = new RoomOptions(); roomOptions.PublishUserId = true; roomOptions.CustomRoomPropertiesForLobby = new string[] { "ownername", "ownerid", "bet", "isAvailable", "appVer", "poolId", "isChallenge", "game" }; roomOptions.CustomRoomProperties = new ExitGames.Client.Photon.Hashtable() { { "ownername", UserDetailsManager.userName }, { "ownerid", UserDetailsManager.userId }, { "bet", betAmount }, { "isAvailable", true }, { "appVer", Application.version }, { "poolId", poolId }, { "isChallenge", true }, { "game", "Whot" } }; //ExitGames.Client.Photon.Hashtable expectedCustomRoomProperties = new ExitGames.Client.Photon.Hashtable() { { "bet", MAtchMakeString }, { "isAvailable", true }, { "appVer", Application.version } }; roomOptions.MaxPlayers = 2; roomOptions.IsVisible = true; roomOptions.IsOpen = true; PhotonNetwork.JoinOrCreateRoom(poolId, roomOptions, TypedLobby.Default); } } }
IEnumerator GetQuesDataFromServer(int num) { WWWForm form1 = new WWWForm(); form1.AddField("id", num); WWW www = new WWW(GetQuesDataLink, form1); sendOnPath++; ActivateLoadingDatafromServerPannel(); yield return(www); sendOnPath--; if (www.text.Contains("|")) { sendOnPath--; QuesText.text = SymbolDecoder(GetDataValue(www.text, "Ques:")); Option1Text.text = SymbolDecoder(GetDataValue(www.text, "Option1:")); Option2Text.text = SymbolDecoder(GetDataValue(www.text, "Option2:")); Option3Text.text = SymbolDecoder(GetDataValue(www.text, "Option3:")); Option4Text.text = SymbolDecoder(GetDataValue(www.text, "Option4:")); ExplanationText.text = SymbolDecoder(GetDataValue(www.text, "Explanation:")); YoutubeText.text = SymbolDecoder(GetDataValue(www.text, "YoutubeLink:")); //set drop downs //Course Dropdown int dropdownindex = 0; string temp = GetDataValue(www.text, "Course:"); for (int i = 0; i < courseValues.Count; i++) { if (temp == courseValues[i]) { dropdownindex = i; break; } } courseDropdown.value = dropdownindex; //Subject Dropdown dropdownindex = 0; temp = GetDataValue(www.text, "Subject:"); for (int i = 0; i < subjectValues.Count; i++) { if (temp == subjectValues[i]) { dropdownindex = i; break; } } subjectDropdown.value = dropdownindex; //Company Dropdown dropdownindex = 0; temp = GetDataValue(www.text, "Company:"); for (int i = 0; i < companyValues.Count; i++) { if (temp == companyValues[i]) { dropdownindex = i; break; } } CompanyDropdown.value = dropdownindex; //corect int correct = int.Parse(GetDataValue(www.text, "Correct:")); CorrectOptionSelect(correct); } }
IEnumerator InsertarEquipo() { int id; int.TryParse(i.text.ToString(), out id); int idRes; int.TryParse(res.text.ToString(), out idRes); // Debug.Log(idRes + "," + id + "," + idTip + ","); WWWForm form = new WWWForm(); Debug.Log(DateTime.Today.ToString()); form.AddField("id_equipo", id); //No repetir porque debe ser único form.AddField("marca", m.text.Replace("\u200b", "")); //Número de 1 a 3 form.AddField("modelo", mo.text.Replace("\u200b", "")); //Viene del text input form.AddField("serie", s.text.Replace("\u200b", "")); form.AddField("proveedor_equipo", p.text.Replace("\u200b", "")); //Viene del text input form.AddField("fecha_adquisicion", date.text.Replace("\u200b", "")); //Viene del text input form.AddField("garantia", ga.text.Replace("\u200b", "")); //Viene del text input form.AddField("descripcion_larga", dl.text.Replace("\u200b", "")); //Viene del text input form.AddField("descripcion_corta", dc.text.Replace("\u200b", "")); //Viene del text input form.AddField("ubicacion", ub.text.Replace("\u200b", "")); //Viene del text input form.AddField("mantenimiento", ma.text.Replace("\u200b", "")); //Viene del text input form.AddField("id_tipo", tipo); //Viene del text input form.AddField("responsable", idRes); //Viene del text input //form.AddField("id_equipo", 152); //No repetir porque debe ser único //form.AddField("marca", "ASF"); //Número de 1 a 3 //form.AddField("modelo", "1234"); //Viene del text input //form.AddField("serie", "1234"); //form.AddField("proveedor_equipo", "1234"); //Viene del text input //form.AddField("fecha_adquisicion", "10/10/1998"); //Viene del text input //form.AddField("garantia", "1234"); //Viene del text input //form.AddField("descripcion_larga", "1234"); //Viene del text input //form.AddField("descripcion_corta", "1234"); //Viene del text input //form.AddField("ubicacion", "1234"); //Viene del text input //form.AddField("mantenimiento", "1234"); //Viene del text input //form.AddField("id_tipo", 2); //Viene del text input //form.AddField("responsable", 1); //Viene del text input WWW www = new WWW("https://lab.anahuac.mx/~a00289882/DS/insertarequipo.php", form); yield return(www); if (www.text[0] == '0') { Debug.Log("Equipo Creado Exitosamente."); InstantiateSuccess("Operación exitosa", "Equipo creado exitosamente"); MostrarEquipo(); } else if (www.text[0] == '1') { InstantiateSuccess("Error: " + www.text, "No se creo el equipo, el id del responsable no existe"); Debug.Log("No se creo equipo. Error #" + www.text); } else if (www.text[0] == '2') { InstantiateSuccess("Error: " + www.text, "No se creo el equipo, el id del equipo ya existe"); Debug.Log("No se creo equipo. Error #" + www.text); } }
public void Register() { var username = registerUsername.text; var email = registerEmail.text; var password = registerPassword.text; var passwordConfirmation = registerPasswordConfirmation.text; registerError.color = errorColor; if (String.IsNullOrEmpty(username)) { registerError.text = "Please fill in a username"; return; } if (String.IsNullOrEmpty(email)) { registerError.text = "Please fill in an email"; return; } if (String.IsNullOrEmpty(password)) { registerError.text = "Please fill in a password"; return; } if (password.Length < Web.minPassLength) { registerError.text = $"Password should be at least {Web.minPassLength} characters long"; return; } if (String.IsNullOrEmpty(passwordConfirmation)) { registerError.text = "Please repeat your password"; return; } if (password != passwordConfirmation) { registerError.text = "These passwords are not the same"; return; } var form = new WWWForm(); form.AddField("username", username); form.AddField("password", password); form.AddField("password-confirmation", passwordConfirmation); form.AddField("email", email); using (var www = UnityWebRequest.Post(Web.registerUrl, form)) { www.SendWebRequest(); //TODO(Simon): Async?? while (!www.isDone) { } if (www.responseCode != 200) { registerError.text = www.downloadHandler.text; return; } if (www.isNetworkError || www.isHttpError) { registerError.text = www.error; return; } answered = true; var response = JsonUtility.FromJson <LoginResponse>(www.downloadHandler.text); Web.sessionCookie = response.session; Toasts.AddToast(5, "Registered succesfully"); Toasts.AddToast(5, "Logged in"); } }
public void Put(string action, WWWForm form) { Restful(ERestful.Put, action, form); }
IEnumerator webPostAnswer(string edstring, List <string> pics, string key, string guid) { WWWForm form = new WWWForm(); form.AddField("UserID", PollsConfig.netUserID); form.AddField("Token", PollsConfig.netUserToken); form.AddField("Data", edstring); form.AddField("Version", Application.version.ToString()); if (pics.Count >= 1) { form.AddField("Pic1", pics[0]); } if (pics.Count >= 2) { form.AddField("Pic2", pics[1]); } if (pics.Count >= 3) { form.AddField("Pic3", pics[2]); } if (pics.Count >= 4) { form.AddField("Pic4", pics[3]); } WWW www = new WWW("http://47.106.71.112/api/importuseranswer.aspx", form); yield return(www); if (www.isDone && www.error == null && www.text != "") { var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; retWithoutData ret = JsonConvert.DeserializeObject <retWithoutData>(www.text, settings); if (ret.ret == 1) { //Toast.ShowToast("导入数据库成功"); removeList.Add(key); if (removeListEx.ContainsKey(key)) { removeListEx[key].Add(guid); } else { List <string> _list = new List <string>(); removeListEx.Add(key, _list); removeListEx[key].Add(guid); } Debug.Log(ret.info); } else { Debug.LogError(ret.info); Toast.ShowToast(ret.info); } www.Dispose(); } else { Debug.Log("导出错误,请稍后再试"); } }
IEnumerator CreateUser(string student_id, string password, string fname, string mname, string lname, string username) { errorfield.text = ""; canvasLoad.SetActive(true); lblLoader.text = "Creating account..... wait for response"; // first if checking internet connection ang web serve response pare if (Validation1.checkConnectionfail() == true) { errorfield.text = "Error: Internet Connection"; canvasLoad.SetActive(false); } else { //Checking web server response WWWForm form = new WWWForm(); form.AddField("student_id", student_id); form.AddField("password", password); form.AddField("fname", fname); form.AddField("mname", mname); form.AddField("lname", lname); form.AddField("name", username); using (UnityWebRequest www = UnityWebRequest.Post(CreateUserUrl, form)) { www.chunkedTransfer = false; yield return(www.SendWebRequest()); Debug.Log(www.error + " "); if (www.error != null) { errorfield.text = "Error webserver request error: " + www.error; canvasLoad.SetActive(false); } else { Debug.Log("Response" + www.downloadHandler.text); Validation1.UserDetail userDetail = JsonUtility.FromJson <Validation1.UserDetail> (www.downloadHandler.text); //reponse details if (userDetail.status == 1) { canvasLoad.SetActive(false); errorfield.text = userDetail.message; StartCoroutine(loadaftercreate()); } else { errorfield.text = www.downloadHandler.text; canvasLoad.SetActive(false); } } } } }
public IEnumerator CoGetMatchesHistory() { ManuManager._instance.LoadingPupUp.SetActive(true); Debug.Log("CoGetMatchesHistory" + "|||||||||||||||||||||||"); WWWForm wwwform = new WWWForm(); wwwform.AddField("p", currentPlayer.PlayerID + "||." + 5); WWW www = new WWW(webServiceLink + "/fbresulthistory.php", wwwform); for (int i = 0; i < ManuManager._instance.ResultsContentHolder.transform.childCount; i++) { Destroy(ManuManager._instance.ResultsContentHolder.transform.GetChild(i).gameObject); } ManuManager._instance.ResultsContentHolder.GetComponent <RectTransform> ().localPosition = Vector3.zero; yield return(www); if (www.error == null) { Debug.Log(www.text); var serializer = new XmlSerializer(typeof(PlayerMatchesResult), new XmlRootAttribute("PlayerMatches")); using (TextReader reader = new StringReader(www.text)) { var playerMatchesResult = (PlayerMatchesResult)serializer.Deserialize(reader); for (int i = 0; i < playerMatchesResult.Play.Count; i++) { ResultFeild resultFeild = Instantiate(ResultFeild).GetComponent <ResultFeild> (); resultFeild.transform.SetParent(ManuManager._instance.ResultsContentHolder.transform); ManuManager._instance.ResultsContentHolder.GetComponent <RectTransform> ().localPosition = new Vector3(ManuManager._instance.ResultsContentHolder.GetComponent <RectTransform> ().localPosition.x, ManuManager._instance.ResultsContentHolder.GetComponent <RectTransform> ().localPosition.y - 365, 0); if (playerMatchesResult.Play [i].HostFacebookId == currentPlayer.FbId) { resultFeild.PSetName(playerMatchesResult.Play [i].HostUsername); resultFeild.PSetRank(playerMatchesResult.Play [i].HostUserRank); resultFeild.PSetScore(playerMatchesResult.Play [i].HostUserScoreMulti); resultFeild.PSetFBID(playerMatchesResult.Play [i].HostFacebookId); FBGraph.GetFBImage(playerMatchesResult.Play [i].HostFacebookId, resultFeild.PPic); resultFeild.FSetName(playerMatchesResult.Play [i].GuestUsername); resultFeild.FSetRank(playerMatchesResult.Play [i].GuestUserRank); resultFeild.FSetScore(playerMatchesResult.Play [i].GuestUserScoreMulti); resultFeild.FSetFBID(playerMatchesResult.Play [i].GuestFacebookId); FBGraph.GetFBImage(playerMatchesResult.Play [i].GuestFacebookId, resultFeild.FPic); resultFeild.SetResult(int.Parse(playerMatchesResult.Play [i].HostUserScore), int.Parse(playerMatchesResult.Play [i].GuestUserScore)); } else { resultFeild.FSetName(playerMatchesResult.Play [i].HostUsername); resultFeild.FSetRank(playerMatchesResult.Play [i].HostUserRank); resultFeild.FSetScore(playerMatchesResult.Play [i].HostUserScoreMulti); resultFeild.FSetFBID(playerMatchesResult.Play [i].HostFacebookId); FBGraph.GetFBImage(playerMatchesResult.Play [i].HostFacebookId, resultFeild.FPic); resultFeild.PSetName(playerMatchesResult.Play [i].GuestUsername); resultFeild.PSetRank(playerMatchesResult.Play [i].GuestUserRank); resultFeild.PSetScore(playerMatchesResult.Play [i].GuestUserScoreMulti); resultFeild.PSetFBID(playerMatchesResult.Play [i].GuestFacebookId); FBGraph.GetFBImage(playerMatchesResult.Play [i].GuestFacebookId, resultFeild.PPic); resultFeild.SetResult(int.Parse(playerMatchesResult.Play [i].GuestUserScore), int.Parse(playerMatchesResult.Play [i].HostUserScore)); } } //add The List is empty statment. if (ManuManager._instance.ResultsContentHolder.transform.childCount == 0) { GameObject EmptyListFeild = Instantiate(EmptyListField3); EmptyListFeild.transform.SetParent(ManuManager._instance.ResultsContentHolder.transform); } reader.Close(); } //yield return new WaitForSeconds (0.5f); ManuManager._instance.LoadingPupUp.SetActive(false); } else { Debug.Log(www.error + " error"); ManuManager._instance.ConnictionErrorPanel.SetActive(true); } }
public IEnumerator SendData(WWWForm form) { //Send WWW Form to Loggly, replace TOKEN with your unique ID from Loggly WWW sendLog = new WWW("https://logs-01.loggly.com/inputs/{loggly-input-guid}/tag/http/", form); yield return sendLog; }
public IEnumerator CoGetHostPendingMatches() { Debug.Log("CoGetHostPendingMatches" + "|||||||||||||||||||||||"); WWWForm wwwform = new WWWForm(); wwwform.AddField("p", currentPlayer.PlayerID + "||." + 1); WWW www = new WWW(webServiceLink + "/fbpendsessions.php", wwwform); for (int i = 0; i < ManuManager._instance.MyFriendsRuquestsHolder.transform.childCount; i++) { Destroy(ManuManager._instance.MyFriendsRuquestsHolder.transform.GetChild(i).gameObject); } ManuManager._instance.MyFriendsRuquestsHolder.GetComponent <RectTransform> ().localPosition = Vector3.zero; yield return(www); if (www.error == null) { Debug.Log(www.text); var serializer = new XmlSerializer(typeof(PlayerMatches), new XmlRootAttribute("PlayerMatches")); using (TextReader reader = new StringReader(www.text)) { var playerMatches = (PlayerMatches)serializer.Deserialize(reader); for (int i = 0; i < playerMatches.Match.Count; i++) { MyRequestsFeild myFriendsField = Instantiate(MyRequestsFeild).GetComponent <MyRequestsFeild> (); myFriendsField.transform.SetParent(ManuManager._instance.MyFriendsRuquestsHolder.transform); ManuManager._instance.MyFriendsRuquestsHolder.GetComponent <RectTransform> ().localPosition = new Vector3(ManuManager._instance.MyFriendsRuquestsHolder.GetComponent <RectTransform> ().localPosition.x, ManuManager._instance.MyFriendsRuquestsHolder.GetComponent <RectTransform> ().localPosition.y - 150, 0); myFriendsField.SetName(playerMatches.Match [i].OpUserName); myFriendsField.SetRank(playerMatches.Match [i].OpUserRank); myFriendsField.SetScore(playerMatches.Match [i].OpUserScore); myFriendsField.SetFBID(playerMatches.Match [i].OpUserFacebookId); myFriendsField.SetTime(Convert.ToDateTime(playerMatches.Match [i].Remainingtime)); LastFBSessionID = playerMatches.Match [i].FacebookSession; FBGraph.GetFBImage(playerMatches.Match [i].OpUserFacebookId, myFriendsField.Pic); } //add The List is empty statment. if (playerMatches.Match.Count == 0) { GameObject myFriendsField = Instantiate(EmptyListField1); myFriendsField.transform.SetParent(ManuManager._instance.MyFriendsRuquestsHolder.transform); } reader.Close(); } //ManuManager._instance.OpenLayout (LayoutStates._FriendsListPanel.ToString ()); } else { Debug.Log(www.error + " error"); ManuManager._instance.ConnictionErrorPanel.SetActive(true); } }
IEnumerator FeedbackFromPHP(string user_username, string user_password) { WWWForm form = new WWWForm(); form.AddField("check_usernamePost", check_username); form.AddField("check_passwordPost", check_password); WWW www = new WWW(LoginCheckURL, form); yield return(www); string respond = www.text; respond_code = respond.Split(';'); if (respond_code[0] == "200") // 200 = login successful { send_ID = respond_code[1]; yield return(StartCoroutine(ReturnFramePHP(respond_code[1]))); PlayerPrefs.SetString("userID", respond_code[1]); Debug.Log(FrameCode); PlayerPrefs.SetString("Frame", FrameCode); BinaryFormatter binaryFormatter = new BinaryFormatter(); FileStream file = File.OpenWrite(Application.persistentDataPath + "/playerinfo.dat"); PlayerData data = new PlayerData(); data.username = check_username; data.password = check_password; data.FrameCode = FrameCode; binaryFormatter.Serialize(file, data); file.Close(); SceneManager.LoadScene("2.0_front"); //loggin_panel.SetActive(true); //loggin_warntext.text = "Login Successful! \n Press Next to continue..."; //Back_button.SetActive(false); //Next_button.SetActive(true); } else if (respond_code[0] == "1139") //1139 = wrong password { loggin_panel.SetActive(true); loggin_warntext.text = "Wrong password or username. \n Please try again."; Next_button.SetActive(false); Back_button.SetActive(true); } else if (respond_code[0] == "404") // 404 = no username { loggin_panel.SetActive(true); loggin_warntext.text = "Wrong password or username. \n Please try again."; Next_button.SetActive(false); Back_button.SetActive(true); } else if (respond_code[0] == "0000") { loggin_panel.SetActive(true); loggin_warntext.text = "Account inactive. \n Please check your email to activate account."; Next_button.SetActive(false); Back_button.SetActive(true); } }
public IEnumerator CoGetUser(string _username, string _DeviceID, string _FBID) { ManuManager._instance.OpenLayout(LayoutStates._loading.ToString()); //TODO Show the Loading screen var wwwForm = new WWWForm(); //ManuManager._instance.loadingLayout.SetActive (true); wwwForm.AddField("p", _username + "||." + _DeviceID + "||." + _FBID); if (PlayerPrefs.GetString("_username") == "") { //Create a texture the size of the screen, RGB24 format Texture2D profileTex = ManuManager._instance.InputprofilePic.mainTexture as Texture2D; byte[] bytes = profileTex.EncodeToPNG(); Debug.Log("Uploading the Image"); wwwForm.AddBinaryData("img", bytes, "ProfilePic.png", "image/png"); } WWW www = new WWW(webServiceLink + "/login.php", wwwForm); yield return(www); if (www.error == null) { Debug.Log(www.text); var serializer = new XmlSerializer(typeof(Player), new XmlRootAttribute("Player")); using (TextReader reader = new StringReader(www.text)) { try { currentPlayer = (Player)serializer.Deserialize(reader); Debug.Log(currentPlayer.Header); PlayerPrefs.SetString("_username", currentPlayer.PlayerName); PlayerPrefs.SetString("_deviceid", _DeviceID); PlayerPrefs.SetString("_playerid", currentPlayer.PlayerID); PlayerPrefs.SetString("_FBID", _FBID); Debug.Log("_username " + currentPlayer.PlayerName); isLoggedIn = true; //set the player name Texts ManuManager._instance.SetPlayerNameText(); reader.Close(); StartCoroutine(CoGetImage(currentPlayer.PlayerID)); ManuManager._instance.OpenLayout(LayoutStates._loading.ToString()); //yield return new WaitForSeconds (2); //ManuManager._instance.loadingLayout.SetActive (false); GetGuestPendingMatches(true); } catch { Debug.Log("Xml Parsing Exception caught."); ManuManager._instance.ConnictionErrorPanel.SetActive(true); //Handle the interconiction error and restart the game } } } else { //TODO close the Loading screen & Player logined //ManuManager._instance.OpenLayout (LayoutStates._login.ToString ()); Debug.Log(www.error + " error"); ManuManager._instance.ConnictionErrorPanel.SetActive(true); } }
public IEnumerator CoGetGuestPendingMatches(bool ShowPobUp) { Debug.Log("CoGetGuestPendingMatches" + "|||||||||||||||||||||||"); WWWForm wwwform = new WWWForm(); wwwform.AddField("p", currentPlayer.PlayerID + "||." + 2); WWW www = new WWW(webServiceLink + "/fbpendsessions.php", wwwform); for (int i = 0; i < ManuManager._instance.FriendsRequestsHolder.transform.childCount; i++) { Destroy(ManuManager._instance.FriendsRequestsHolder.transform.GetChild(i).gameObject); } ManuManager._instance.FriendsRequestsHolder.GetComponent <RectTransform> ().localPosition = Vector3.zero; yield return(www); if (www.error == null) { Debug.Log(www.text); var serializer = new XmlSerializer(typeof(PlayerMatches), new XmlRootAttribute("PlayerMatches")); using (TextReader reader = new StringReader(www.text)) { var playerMatches = (PlayerMatches)serializer.Deserialize(reader); for (int i = 0; i < playerMatches.Match.Count; i++) { FriendsRequestsFeild friendsRequestsFeild = Instantiate(FriendsRequestsFeild).GetComponent <FriendsRequestsFeild> (); friendsRequestsFeild.transform.SetParent(ManuManager._instance.FriendsRequestsHolder.transform); ManuManager._instance.FriendsRequestsHolder.GetComponent <RectTransform> ().localPosition = new Vector3(ManuManager._instance.FriendsRequestsHolder.GetComponent <RectTransform> ().localPosition.x, ManuManager._instance.FriendsRequestsHolder.GetComponent <RectTransform> ().localPosition.y - 150, 0); friendsRequestsFeild.SetName(playerMatches.Match [i].OpUserName); friendsRequestsFeild.SetRank(playerMatches.Match [i].OpUserRank); friendsRequestsFeild.SetScore(playerMatches.Match [i].OpUserScore); friendsRequestsFeild.SetFBID(playerMatches.Match [i].OpUserFacebookId); // friendsRequestsFeild.SetTime (Convert.ToDateTime (playerMatches.Match [i].Expiry)); friendsRequestsFeild.SetFBSessionID((playerMatches.Match [i].FacebookSession)); friendsRequestsFeild.SetTime(Convert.ToDateTime(playerMatches.Match [i].Remainingtime)); LastFBSessionID = playerMatches.Match [i].FacebookSession; foreach (Text text in ManuManager._instance.notificationsNum) { if (playerMatches.Match.Count > 0) { text.transform.parent.gameObject.SetActive(true); text.text = playerMatches.Match.Count.ToString(); if (ShowPobUp) { ManuManager._instance.NotificationsPupUp.SetActive(true); } //TODO PupUP for Notification } else { text.transform.parent.gameObject.SetActive(false); } } FBGraph.GetFBImage(playerMatches.Match [i].UserFacebookId, friendsRequestsFeild.Pic); } //add The List is empty statment. if (playerMatches.Match.Count == 0) { GameObject EmptyListFeild = Instantiate(EmptyListField2); EmptyListFeild.transform.SetParent(ManuManager._instance.FriendsRequestsHolder.transform); } reader.Close(); } ManuManager._instance.LoadingPupUp.SetActive(false); } else { Debug.Log(www.error + " error"); ManuManager._instance.ConnictionErrorPanel.SetActive(true); } }