Parse() private method

private Parse ( string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false ) : void
str string
maxDepth int
storeExcessLevels bool
strict bool
return void
Exemplo n.º 1
0
    public void FinishGame()
    {
        JSONObject body = new JSONObject();

        body.Add("UserID", UserSingleton.Instance.UserID);
        body.Add("Point", StagePoint.ToString());

        HTTPClient.Instance.POST(
            Singleton.Instance.HOST + "/UpdateResult/Post",
            body.ToString(),
            delegate(WWW obj) {
            JSONObject json = JSONObject.Parse(obj.text);
            Debug.Log("Response is : " + json.ToString());

            Application.LoadLevel("Lobby");
        }
            );
    }
        public object GetFarmKeyValueAsObject(string key)
        {
            string val = Convert.ToString(m_iisWebServiceApplication.Properties[key]);

            object result;

            //Attempt to convert the string into a JSON Object.
            try
            {
                result = JSONObject.Parse(Engine, val, null);
            }
            catch
            {
                result = val;
            }

            return(result);
        }
Exemplo n.º 3
0
    public void unirsePartida(string codigo, string nombreJugador, string deviceID)
    {
        string json = JsonString.unirseAPartida(codigo, nombreJugador, deviceID);

        setupSocket();
        writeSocket(json);
        string dataIn = readSocket();

        closeSocket();
        if (dataIn != "")
        {
            JSONObject jsRes = JSONObject.Parse(dataIn);
            controlador.crearPartida(codigo);
            controlador.establecerAvatarJugador(jsRes["avatar"].Str);
            controlador.establecerIdJugador((int)jsRes["jugadorID"].Number);
            controlador.responderConexion(jsRes["aceptado"].Boolean);
        }
    }
Exemplo n.º 4
0
    public void LoadTotalRank(Action callback)
    {
        HTTPClient.Instance.GET(Singleton.Instance.HOST + "/Rank/Total?Start=1&Count=50", delegate(WWW www) {
            string response = www.text;

            JSONObject obj = JSONObject.Parse(response);

            JSONArray arr = obj["Data"].Array;

            foreach (JSONValue item in arr)
            {
                int rank = (int)item.Obj["Rank"].Number;
                TotalRank.Add(rank, item.Obj);
            }

            callback();
        });
    }
Exemplo n.º 5
0
        public IEnumerator upsertObjectInstance(ObjectInstance objectInstance)
        {
            // Assemble payload
            JSONObject jsonBody = new JSONObject();

            jsonBody.Add("instance", objectInstance.toJson());
            // Send request
            Coroutine <string> routine = owner.StartCoroutine <string>(
                sfClient.runApex("POST", "ObjectInstance", jsonBody.ToString(), null)
                );

            yield return(routine.coroutine);

            // Parse JSON response
            JSONObject jsonResponse = JSONObject.Parse(routine.getValue());

            yield return(new ObjectInstance(jsonResponse));
        }
Exemplo n.º 6
0
        void OpenAction(string[] filenames)
        {
            questionnairePanel.questionnaires = new List <Questionnaire>();

            for (int i = 0; i < filenames.Length; i++)
            {
                string filename = filenames[i];
                print("open: " + filename);
                string     file = File.ReadAllText(filename);
                JSONObject json = JSONObject.Parse(file);

                questionnairePanel.questionnaires.Add(GenerateQuestionnaire(json));
                GenerateQuestionnaireUI(questionnairePanel.questionnaires.Last(), questionnairePanel.skinData);
            }
            GenerateSubmitQuestionnaireUI();

            questionnairePanel.ApplySkin();
        }
    /*Color32 copyColors(Color32 array){
     *      var retr = new Color32[array.length];
     * }*/

    async void PostData(int index, bool isLeaving)
    {
        var client = new HttpClient();
        //client.BaseAddress = new System.Uri("https://gateway.watsonplatform.net");
        var request = new HttpRequestMessage(HttpMethod.Post, "https://gateway.watsonplatform.net/visual-recognition/api/v3/detect_faces?version=2018-03-1");

        var byteArray = new UTF8Encoding().GetBytes("apikey:ZOrzfoyOJYQQtiewyE_iMxPCMRjVYWdnWNaJTo3D4xJP");

        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(byteArray));

        var fileBytes   = System.IO.File.ReadAllBytes("FaceCapture" + (isLeaving?"Sub":"Add") + index + ".png");
        var fileContent = new ByteArrayContent(fileBytes, 0, fileBytes.Length);
        MultipartFormDataContent multipartContent = new MultipartFormDataContent();

        multipartContent.Add(fileContent, "images_file", "FaceCapture" + (isLeaving?"Sub":"Add") + index + ".png");
        HttpResponseMessage response = await client.PostAsync("https://gateway.watsonplatform.net/visual-recognition/api/v3/detect_faces?version=2018-03-19", multipartContent);

        HttpContent responseContent = response.Content;

        string JSON;

        // Get the stream of the content.
        using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
        {
            // Write the output.
            JSON = await reader.ReadToEndAsync();

            UnityEngine.Debug.Log(JSON);
        }
        var jsonObject  = JSONObject.Parse(JSON);
        var images      = jsonObject.GetArray("images");
        var faceCounter = 0;

        foreach (var i in images)
        {
            foreach (var j in JSONObject.Parse(i.ToString()).GetArray("faces"))
            {
                faceCounter++;
                var face_location = JSONObject.Parse(j.ToString()).GetObject("face_location");
                cropImage((int)face_location.GetNumber("left"), (int)face_location.GetNumber("top"), (int)face_location.GetNumber("width"), (int)face_location.GetNumber("height"), index, faceCounter, isLeaving);
                //UnityEngine.Debug.Log(face_location);
            }
        }
    }
Exemplo n.º 8
0
/*
 * 저자의 경우 오는 페이스북 로그인 결과
 *
 * {"is_logged_in":true,
 * "user_id":"10204997009661738",
 * "access_token":"~~~",
 * "access_token_expires_at":"01/01/0001 00:00:00"}
 */

    public void FacebookLogin(Action <bool, string> callback, int retryCount = 0)
    {
        FB.LogInWithReadPermissions(new List <string>()
        {
            "public_profile", "email", "user_friends"
        },
                                    delegate(ILoginResult result) {
            if (result.Error != null && retryCount >= 3)
            {
                Debug.LogError(result.Error);

                callback(false, result.Error);
                return;
            }

            if (result.Error != null)
            {
                Debug.LogError(result.Error);

                retryCount = retryCount + 1;
                FacebookLogin(callback, retryCount);
                return;
            }

            Debug.Log(result.RawResult);

            Debug.Log("FB Login Result: " + result.RawResult);


            // 페이스북 로그인 결과를 JSON 파싱합니다.
            JSONObject obj = JSONObject.Parse(result.RawResult);

            // 페이스북 아이디를 UserSingleton에 저장합니다.
            // 이 변수는 게임이 껏다 켜져도 유지되도록 환경변수에 저장하도록 구현되있습니다.
            UserSingleton.Instance.FacebookID       = obj["user_id"].Str;
            UserSingleton.Instance.FacebookPhotoURL = "http://graph.facebook.com/" + UserSingleton.Instance.FacebookID + "/picture?type=square";

            // 페이스북 액세스 토큰을 UserSingleton에 저장힙니다.
            // 이 변수 역시 게임이 껏다 켜져도 유지됩니다.
            UserSingleton.Instance.FacebookAccessToken = obj["access_token"].Str;

            callback(true, result.RawResult);
        });
    }
Exemplo n.º 9
0
        private ImportedAnimationInfo ImportJSONAndCreateAnimations(string basePath, string name)
        {
            string imagePath = basePath;

            if (_saveSpritesToSubfolder)
            {
                imagePath += "/Sprites";
            }

            string    imageAssetFilename = imagePath + "/" + name + ".png";
            string    textAssetFilename  = imagePath + "/" + name + ".json";
            TextAsset textAsset          = AssetDatabase.LoadAssetAtPath <TextAsset>(textAssetFilename);

            if (textAsset != null)
            {
                // parse the JSON file
                JSONObject            jsonObject    = JSONObject.Parse(textAsset.ToString());
                ImportedAnimationInfo animationInfo = AsepriteImporter.GetAnimationInfo(jsonObject);

                if (animationInfo == null)
                {
                    return(null);
                }

                animationInfo.basePath             = basePath;
                animationInfo.name                 = name;
                animationInfo.nonLoopingAnimations = _animationNamesThatDoNotLoop;

                // delete JSON file afterwards
                AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(textAsset));

                CreateSprites(animationInfo, imageAssetFilename);

                CreateAnimations(animationInfo, imageAssetFilename);

                return(animationInfo);
            }
            else
            {
                Debug.LogWarning("Problem with JSON file: " + textAssetFilename);
            }

            return(null);
        }
Exemplo n.º 10
0
        private IEnumerator SignUpRoutine(string email, string password, string password_confirmation, string username, Action <string, bool> callback = null)
        {
            Log("CloudLogin Sign Up: " + email);

            if (GetGameId() == null)
            {
                throw new CloudLoginException("Please set up your game with PainLessAuth.SetUpGame before signing up users");
            }

            WWWForm form = new WWWForm();

            form.AddField("email", email);
            form.AddField("password", password);
            form.AddField("password_confirmation", password_confirmation);
            form.AddField("username", username);

            form.AddField("game_id", GetGameId());
            form.AddField("game_token", GetGameToken());

            var request = UnityWebRequest.Post(baseURL + "/users", form);

            yield return(request.SendWebRequest());

            if (CloudLoginUtilities.RequestIsSuccessful(request))
            {
                Log("CloudLogin Sign Up Success: " + email);
                var        data = request.downloadHandler.text;
                JSONObject json = JSONObject.Parse(data);
                CloudLoginUser.CurrentUser.SetSignedInInternal();
                CloudLoginUser.CurrentUser.SetScoreInternal(Convert.ToInt32(json.GetNumber("score")));
                CloudLoginUser.CurrentUser.SetCreditsInternal(Convert.ToInt32(json.GetNumber("credits")));
                CloudLoginUser.CurrentUser.SetUsernameInternal(json.GetString("username"));
                CloudLoginUser.CurrentUser.SetLastLoginInternal(DateTime.Parse(json.GetString("last_login")));
                CloudLoginUser.CurrentUser.SetNumberOfLoginsInternal(Convert.ToInt32(json.GetNumber("number_of_logins")));
                CloudLoginUser.CurrentUser.SetAuthenticationTokenInternal(json.GetString("authentication_token"));
                CloudLoginUser.CurrentUser.SetIDInternal(Convert.ToInt32(json.GetNumber("id")));
                CloudLoginUser.CurrentUser.DownloadAttributes(true, callback); // Chain next request - download users attributes
            }
            else
            {
                Log("CloudLogin Sign Up Failure: " + email);
                CloudLoginUtilities.HandleCallback(request, "User could not sign up: " + request.error, callback);
            }
        }
Exemplo n.º 11
0
 public string RefreshUserSession(string json)
 {
     if (json == "")
     {
         return(json);
     }
     else
     {
         JSONObject jsonObject = JSONObject.Parse(json);
         sessionToken = jsonObject.GetString("sessionToken");
         if (sessionToken != "" || readOnly)
         {
             UpdateMemberVariables(jsonObject);
             rawJson     = json;
             initialized = true;
         }
         return(sessionToken);
     }
 }
Exemplo n.º 12
0
        private IEnumerator PurchaseStoreItemRoutine(int storeItemId, Action <string, bool> callback = null)
        {
            CloudLogin.Log("CloudLoginUser Purchase Store Items: ");

            if (CloudLogin.GetGameId() == null)
            {
                throw new CloudLoginException("Please set up your game with CloudLogin.SetUpGame before modifying users");
            }

            WWWForm form = new WWWForm();

            form.AddField("authentication_token", GetAuthenticationToken());
            form.AddField("store_item_id", storeItemId.ToString());

            var request = UnityWebRequest.Post(CloudLogin.GetBaseURL() + "/users/" + CurrentUser.id + "/purchase_game_user_store_item", form);

            request.SetRequestHeader("authentication_token", CloudLoginUser.CurrentUser.GetAuthenticationToken());

            yield return(request.SendWebRequest());

            if (CloudLoginUtilities.RequestIsSuccessful(request))
            {
                CloudLogin.Log("CloudLoginUser Purchase Store Items Success: ");

                var        data = request.downloadHandler.text;
                JSONObject json = JSONObject.Parse(data);
                var        game_user_store_items = json.GetArray("game_user_store_items");
                CurrentUser.SetCreditsInternal(Convert.ToInt32(json.GetNumber("credits")));
                purchasedStoreItems.Clear();

                foreach (var item in game_user_store_items)
                {
                    purchasedStoreItems.Add(new CloudLoginStoreItem(
                                                item.Obj.GetString("name"),
                                                item.Obj.GetString("category"),
                                                item.Obj.GetString("description"),
                                                Convert.ToInt32(item.Obj.GetNumber("cost")),
                                                Convert.ToInt32(item.Obj.GetNumber("id"))));
                }
            }

            CloudLoginUtilities.HandleCallback(request, "Store Item has been purchased by user", callback);
        }
Exemplo n.º 13
0
    }                            //end public

//login user

    public IEnumerator LoginUser(string email, string password)
    {
        Debug.Log("f*****g:  " + email);

        string url = "http://mobile.coachparrot.com/login/run";

        // Create a form object for sending high score data to the server
        var form = new WWWForm();

        // Assuming the perl script manages high scores for different games
        form.AddField("email", email);
        // The name of the player submitting the scores
        form.AddField("password", password);

        // Create a download object
        var downloadbabe = new WWW(url, form);

        // Wait until the download is done
        yield return(downloadbabe);

        if (downloadbabe.error != null)
        {
            Debug.Log("Error downloading: " + downloadbabe.error);
            //return;
        }
        else
        {
            // show the highscores
            Debug.Log(downloadbabe.text);
        }

        //WWW www = new WWW (url);
        //yield return www;

        if (downloadbabe.size <= 2)
        {
            yield return(null);
        }
        else
        {
            fuckdata = JSONObject.Parse(downloadbabe.text);
        }
    }            //end
Exemplo n.º 14
0
    private void ServerLoginCheck(WWW www)
    {
        if (www.text.Length == 0)
        {
            Debug.LogError("서버 로그인 정보 값이 전달 되지 않았습니다..");

            return;
        }

        int        nResultCode  = 0;
        JSONObject jsonResponse = null;

        jsonResponse = JSONObject.Parse(www.text);
        nResultCode  = (int)jsonResponse["ResultCode"].Number;

        Debug.Log(www.text);

        if (nResultCode == 1 || nResultCode == 2)
        {
            string     strIDCode = "";
            JSONObject jsonData  = null;

            jsonData  = jsonResponse.GetObject("Data");
            strIDCode = nResultCode == 1 ? "새로 가입하는 ID입니다!" : "이미 존재하는 ID입니다!";

            UserSingleton.GetInstance().m_nUserID        = int.Parse(jsonData["UserID"].Number.ToString());
            UserSingleton.GetInstance().m_strAccessToken = jsonData["AccessToken"].Str;

            Debug.Log("현재 접속한 ID는 " + strIDCode);
            Debug.Log("ID : " + UserSingleton.GetInstance().m_nUserID.ToString());
            Debug.Log("AccessToken : " + UserSingleton.GetInstance().m_strAccessToken);
            Debug.Log("서버 로그인 성공!");

            InvokeRepeating("LoadDataFromGameServer", 0.01f, 0.2f);
        }
        else
        {
            Debug.LogError("로그인에 실패했습니다..");

            return;
        }
    }
Exemplo n.º 15
0
    /*public void obtenerSprint(){
     *  setupSocket();
     *  string json = JsonString.sprintPlanning(controlador.obtenerPartida().getID());
     *  writeSocket(json);
     *  string receieved_data = readSocket();
     *  closeSocket();
     *
     *  if (receieved_data != ""){
     *      JSONObject respuesta = JSONObject.Parse(receieved_data);
     *      int restantes = (int)respuesta["restantes"].Number;
     *      int numero = (int)respuesta["numero"].Number;
     *      controlador.obtenerProyecto().setSprintRestante(restantes);
     *      controlador.obtenerProyecto().setSprintActual(numero);
     *  }
     * }*/

    public void obtenerProyecto()
    {
        setupSocket();
        string json = JsonString.pedirProyecto(controlador.obtenerPartida().Id);

        writeSocket(json);
        string received_data = readSocket();

        closeSocket();

        if (received_data != "")
        {
            JSONObject respuesta               = JSONObject.Parse(received_data);
            string     nombre                  = respuesta["nombre"].Str;
            string     descripcion             = respuesta["descripcion"].Str;
            JSONArray  jHistorias              = respuesta.GetArray("historias");
            List <HistoriaDeUsuario> historias = new List <HistoriaDeUsuario>();

            for (int i = 0; i < jHistorias.Length; i++)
            {
                JSONObject        historia      = jHistorias[i].Obj;
                List <CriterioHU> criterios     = new List <CriterioHU>();
                string            nombreHU      = historia["nombre"].Str;
                string            descripcionHU = historia["descripcion"].Str;
                string            puntos        = historia["puntos"].Str;
                int prioridad = (int)historia["prioridad"].Number;
                //Debug.Log("WebClient.obtenerProyecto() -> Prioridad HU:" + prioridad);
                JSONArray crit   = historia.GetArray("criterios");
                bool      estado = historia["estado"].Boolean;
                for (int j = 0; j < crit.Length; j++)
                {
                    criterios.Add(new CriterioHU(crit[j].Str));
                    //Debug.Log("WebClient.obtenerProyecto() -> Descripción de criterio: " + criterios[j].getDescripcion());
                }

                HistoriaDeUsuario historiaDeUsuario = new HistoriaDeUsuario(nombreHU, descripcionHU, prioridad, puntos, criterios, estado);
                historias.Add(historiaDeUsuario);
            }
            Proyecto proyecto = new Proyecto(nombre, descripcion, historias, (int)respuesta["numeroSprints"].Number, (int)respuesta["duracionSprints"].Number);
            controlador.establecerProyecto(proyecto);
        }
    }
Exemplo n.º 16
0
        public BaseResponse(string body)
        {
            JSONObject ob;

            try
            {
                ob = JSONObject.Parse(body);
            }
            catch (Exception x)
            {
                throw new APIReplyParseException("JSON Parse exception: " + body + "\n" + x.Message);
            }

            if (ob == null)
            {
                throw new APIReplyParseException("JSON Parse exception: " + body);
            }
            status     = (bool?)ob["status"];
            errCode    = new ERR_CODE((string)ob["errorCode"]);
            errorDescr = (string)ob["errorDescr"];
            returnData = (JSONAware)ob["returnData"];
            customTag  = (string)ob["customTag"];

            if (status == null)
            {
                Console.Error.WriteLine(body);
                throw new APIReplyParseException("JSON Parse error: " + "\"status\" is null!");
            }

            if ((status == null) || ((bool)!status))
            {
                // If status is false check if redirect exists in given response
                if (ob["redirect"] == null)
                {
                    if (errorDescr == null)
                    {
                        errorDescr = ERR_CODE.getErrorDescription(errCode.StringValue);
                    }
                    throw new APIErrorResponse(errCode, errorDescr, body);
                }
            }
        }
Exemplo n.º 17
0
    public void Upgrade(string UpgradeType)
    {
        JSONObject obj = new JSONObject();

        obj.Add("UserID", UserSingleton.Instance.UserID);
        obj.Add("UpgradeType", UpgradeType);
        Debug.Log("URL : " + Singleton.Instance.HOST + "/Upgrade/Execute");
        Debug.Log("DATA : " + obj.ToString());
        HTTPClient.Instance.POST(Singleton.Instance.HOST + "/Upgrade/Execute", obj.ToString(), delegate(WWW www) {
            Debug.Log(www.text);
            JSONObject res = JSONObject.Parse(www.text);
            int ResultCode = (int)res["ResultCode"].Number;
            if (ResultCode == 1)             // Success!
            // Upgrade Success => Load User data again
            {
                UserSingleton.Instance.Refresh(delegate() {
                    NotificationCenter.Instance.Notify(NotificationCenter.Subject.PlayerData);
                });
                // Alert Dialog
                DialogDataAlert alert = new DialogDataAlert(Language.Instance.GetLanguage("Upgrade Success Title"),
                                                            Language.Instance.GetLanguage("Upgrade Success"), delegate() {
                });
                DialogManager.Instance.Push(alert);
            }
            else if (ResultCode == 4)              // Max Level
            {
                // Alert Dialog
                DialogDataAlert alert = new DialogDataAlert(Language.Instance.GetLanguage("Upgrade Failed Title"),
                                                            Language.Instance.GetLanguage("Max Level"), delegate() {
                });
                DialogManager.Instance.Push(alert);
            }
            else if (ResultCode == 5)             // Not enough diamond
            {
                // Alert Dialog
                DialogDataAlert alert = new DialogDataAlert(Language.Instance.GetLanguage("Upgrade Failed Title"),
                                                            Language.Instance.GetLanguage("Not Enough Diamond"), delegate() {
                });
                DialogManager.Instance.Push(alert);
            }
        });
    }
Exemplo n.º 18
0
        private static void LoadLanguageFile(string languageId, TextAsset asset = null)
        {
            // load json file from Resources folder
            if (asset == null)
            {
                asset = Resources.Load(dataDirectory + "text_" + languageId) as TextAsset;
            }

            // parse language data
            if (asset != null)
            {
                Dictionary <string, string> languageData = _data[languageId];

                JSONObject data = JSONObject.Parse(asset.ToString());
                foreach (var item in data)
                {
                    languageData[item.Key] = item.Value.Str;
                }
            }
        }
Exemplo n.º 19
0
    private JSONObject difficultySettings;//time, dimensions, nodeCount, errorMargin

    private void Awake()
    {
        current = new string[difficulties.Length, data.Length];
        if (!PlayerPrefs.HasKey("difficultySettings"))
        {
            createNonExistentSettings();
        }

        difficultySettings = JSONObject.Parse(PlayerPrefs.GetString("difficultySettings"));
        for (int i = 0; i < difficulties.Length; i++)
        {
            JSONObject difficulty = difficultySettings.GetObject(difficulties[i].ToString());
            current[(int)difficulties[i], (int)Data.NodeCount]   = ((int)difficulty.GetNumber(nodeCount)).ToString();
            current[(int)difficulties[i], (int)Data.Time]        = ((float)difficulty.GetNumber(time)).ToString();
            current[(int)difficulties[i], (int)Data.ErrorMargin] = ((float)difficulty.GetNumber(errorMargin)).ToString();
            JSONObject vector = difficulty.GetObject(dimensions);
            current[(int)difficulties[i], (int)Data.DimensionX] = ((int)vector.GetNumber("x")).ToString();
            current[(int)difficulties[i], (int)Data.DimensionY] = ((int)vector.GetNumber("y")).ToString();
        }
    }
Exemplo n.º 20
0
    public void FinishGame()
    {
        JSONObject body = new JSONObject();

        body.Add("UserID", UserSingleton.Instance.UserID);
        body.Add("Point", StagePoint);

        HTTPClient.Instance.POST(
            "http://unity-action.azurewebsites.net/UpdateResult",
            body.ToString(),
            delegate(WWW obj) {
            JSONObject json = JSONObject.Parse(obj.text);
            Debug.Log("Response is : " + json.ToString());

            UserSingleton.Instance.Refresh(delegate() {
                Application.LoadLevel("Lobby");                          //
            });
        }
            );
    }
Exemplo n.º 21
0
 public async static void GetPluginUpdateInfo()
 {
     Plugin.Log("Fetching Update Info...");
     updateMessageInfo.message     = "";
     updateMessageInfo.messageType = "Update";
     try
     {
         var PluginInfo = JSONObject.Parse(await httpClient.GetStringAsync(PluginUpdateInfo));
         Plugin.Log("Update Info Downloaded");
         Plugin.Log(PluginInfo.ToString());
         if (Convert.ToInt32(PluginInfo["latest"]["VersionNumber"].Value) > LocalVersionNumber)
         {
             updateMessageInfo.message = "<color=#FFFFC13C>【更新】StreamCore (bilibili edition) Plugin could update to " + PluginInfo["latest"]["Version"].Value + "!" + " What's New: " + PluginInfo["latest"]["ChangeLog"]["English"].Value + " StreamCore (bilibilil版)插件有新版本啦! 快升级到" + PluginInfo["latest"]["Version"].Value + "吧!" + "更新说明" + PluginInfo["latest"]["ChangeLog"]["ChineseSimplified"].Value + " Download at(下载地址): " + PluginInfo["latest"]["Download"].Value + "</color>";
             Plugin.Log(updateMessageInfo.message);
         }
     }
     catch (Exception e) {
         Plugin.Log(e.Message);
     }
 }
Exemplo n.º 22
0
            public override object CallLateBound(object thisObject, params object[] argumentValues)
            {
                var path = argumentValues.ElementAtOrDefault(0);

                if (path == Undefined.Value ||
                    path == Null.Value || path == null)
                {
                    return(thisObject);
                }

                var sPath = TypeConverter.ToString(path);

                var s1 = JSONObject.Stringify(this.Engine, thisObject, null, null);
                var o1 = JToken.Parse(s1);

                var token  = o1.SelectToken(sPath, false);
                var result = JSONObject.Parse(this.Engine, token.ToString(), null);

                return(result);
            }
Exemplo n.º 23
0
    private void OnEnable()
    {
        string path = Path.Combine(Application.dataPath + "/Playlists");

        if (Directory.Exists(path))
        {
            foreach (var dir in Directory.GetDirectories(path))
            {
                if (Directory.Exists(dir) && Directory.GetFiles(dir, "info.dat").Length > 0)
                {
                    JSONObject infoFile = JSONObject.Parse(File.ReadAllText(Path.Combine(dir, "info.dat")));

                    var song = new Song();
                    song.Path           = dir;
                    song.Name           = infoFile.GetString("_songName");
                    song.AuthorName     = infoFile.GetString("_songAuthorName");
                    song.BPM            = infoFile.GetNumber("_beatsPerMinute").ToString();
                    song.CoverImagePath = Path.Combine(dir, infoFile.GetString("_coverImageFilename"));
                    song.AudioFilePath  = Path.Combine(dir, infoFile.GetString("_songFilename"));
                    song.PlayingMethods = new List <PlayingMethod>();

                    var difficultyBeatmapSets = infoFile.GetArray("_difficultyBeatmapSets");
                    foreach (var beatmapSets in difficultyBeatmapSets)
                    {
                        PlayingMethod playingMethod = new PlayingMethod();
                        playingMethod.CharacteristicName = beatmapSets.Obj.GetString("_beatmapCharacteristicName");
                        playingMethod.Difficulties       = new List <string>();

                        foreach (var difficultyBeatmaps in beatmapSets.Obj.GetArray("_difficultyBeatmaps"))
                        {
                            playingMethod.Difficulties.Add(difficultyBeatmaps.Obj.GetString("_difficulty"));
                        }

                        song.PlayingMethods.Add(playingMethod);
                    }

                    AllSongs.Add(song);
                }
            }
        }
    }
        public JSONNode OverwriteBaseArchetypeData(JSONNode baseArchetypeData, JSONNode newArchetypeData)
        {
            JSONNode originalData = JSONNode.Parse(newArchetypeData.ToString());

            baseArchetypeData = m_dataLocator.GetComponentData(baseArchetypeData);
            newArchetypeData  = m_dataLocator.GetComponentData(newArchetypeData);

            JSONNode      replacedValues = JSONObject.Parse(baseArchetypeData.ToString());
            List <string> valueKeys      = new List <string>();

            bool hasComponent = false;

            foreach (JSONObject newComponent in newArchetypeData.Children)
            {
                hasComponent = false;
                foreach (JSONObject baseComponent in replacedValues.Children)
                {
                    if (m_dataLocator.GetComponentName(baseComponent) != m_dataLocator.GetComponentName(newComponent))
                    {
                        continue;
                    }

                    hasComponent = true;
                    valueKeys    = newComponent.GetKeys();

                    foreach (var newValueKey in valueKeys)
                    {
                        baseComponent.Add(newValueKey, newComponent[newValueKey]);
                    }
                }

                if (hasComponent == false)
                {
                    replacedValues.Add(newComponent);
                }
            }

            m_dataLocator.SetComponentData(originalData, replacedValues);

            return(originalData);
        }
Exemplo n.º 25
0
    // Methods(Member Functions)

    // Load Me Method.
    public void LoadFacebookMe(Action <bool, string> actCallback, int nRetryCount = 0)
    {
        FB.API
        (
            "/me",
            HttpMethod.GET,
            delegate(IGraphResult graphResult)
        {
            if (graphResult.Error != null)
            {
                if (nRetryCount >= 3)
                {
                    actCallback(false, graphResult.Error);

                    Debug.LogError(graphResult.Error);

                    return;
                }
                else
                {
                    Debug.LogError("Error occured, start retrying.. " + graphResult.Error);

                    LoadFacebookMe(actCallback, nRetryCount + 1);

                    return;
                }
            }

            JSONObject objMe = null;

            objMe = JSONObject.Parse(graphResult.RawResult);

            m_strName = objMe["name"].Str;

            actCallback(true, graphResult.RawResult);

            Debug.Log("Facebook Name : " + m_strName);
            Debug.Log("Load Success!");
        }
        );
    }
Exemplo n.º 26
0
    // Load Friend List Method.
    // 페이스북 친구 목록을 "JSON" 리스트로 불러옵니다.
    public void LoadFacebookFriend(Action <bool, string> actCallback, int nRetryCount = 0)
    {
        FB.API
        (
            "/me/friends",
            HttpMethod.GET,
            delegate(IGraphResult graphResult)
        {
            if (graphResult.Error != null)
            {
                if (nRetryCount >= 3)
                {
                    actCallback(false, graphResult.Error);

                    Debug.LogError(graphResult.Error);

                    return;
                }
                else
                {
                    Debug.LogError("Error occured, start retrying.. " + graphResult.Error);

                    LoadFacebookFriend(actCallback, nRetryCount + 1);

                    return;
                }
            }

            JSONArray arrayResponse = null;
            JSONObject objResponse  = null;

            objResponse   = JSONObject.Parse(graphResult.RawResult);
            arrayResponse = objResponse["data"].Array;

            m_arrayFriendList = arrayResponse;

            actCallback(true, graphResult.RawResult);
            Debug.Log("친구 데이터 : " + graphResult.RawResult);
        }
        );
    }
Exemplo n.º 27
0
    //------------------------------------------------------------
    //---------------- Util Methods For Building -----------------
    //------------------------------------------------------------

    public static void BuildOpportunityRings(JSONArray opportunityRecords, Transform parentTransform, Transform Ring, Transform Block, Transform blockBox)
    {
        List <Opportunity> oppList = new List <Opportunity>();

        foreach (JSONValue row in opportunityRecords)
        {
            JSONObject rec = JSONObject.Parse(row.ToString());

            Opportunity opp = Opportunity.CreateInstance("Opportunity") as Opportunity;
            opp.init(rec);
            oppList.Add(opp);
        }

        int i = 0;

        foreach (Opportunity opp in oppList)
        {
            createRing(opp, i, parentTransform, Ring, Block, blockBox);
            i++;
        }
    }
    public void LeaderboardRating(Action <int> action)
    {
        new GetLeaderboardEntriesRequest()
        .SetLeaderboards(new List <string>()
        {
            "allTime"
        })
        .Send((response) => {
            if (response.HasErrors)
            {
                return;
            }

            JSONObject results = JSONObject.Parse(response.JSONString);

            if (action != null)
            {
                action((int)results.GetObject("allTime").GetNumber("rank"));
            }
        });
    }
Exemplo n.º 29
0
        private IEnumerator GetLeaderboardRoutine(int limit, bool onePerUser, Action <string, bool> callback = null)
        {
            CloudLogin.Log("CloudLoginUser Get Leaderboard: " + limit.ToString());

            if (CloudLogin.GetGameId() == null)
            {
                throw new CloudLoginException("Please set up your game with CloudLogin.SetUpGame before modifying users");
            }

            var parameters = "?authentication_token=" + GetAuthenticationToken() + "&limit=" + limit.ToString() + "&one_per_user="******"/users/" + CurrentUser.id + "/leaderboard_entries" + parameters);

            request.SetRequestHeader("authentication_token", CloudLoginUser.CurrentUser.GetAuthenticationToken());

            yield return(request.SendWebRequest());

            if (CloudLoginUtilities.RequestIsSuccessful(request))
            {
                CloudLogin.Log("CloudLoginUser Get Leaderboard Success: : " + limit.ToString());

                var        data = request.downloadHandler.text;
                JSONObject json = JSONObject.Parse(data);
                Debug.Log("got " + json);
                var storeItems = json.GetArray("leaderboard_entries");
                CloudLogin.Instance.leaderboardEntries.Clear();
                foreach (var storeItem in storeItems)
                {
                    CloudLogin.Instance.leaderboardEntries.Add(new CloudLoginLeaderboardEntry(
                                                                   storeItem.Obj.GetString("username"),
                                                                   Convert.ToInt32(storeItem.Obj.GetNumber("score")),
                                                                   storeItem.Obj.GetString("leaderboard_name"),
                                                                   storeItem.Obj.GetString("extra_attributes"),
                                                                   Convert.ToInt32(storeItem.Obj.GetNumber("game_user_id"))
                                                                   )
                                                               );
                }
            }

            CloudLoginUtilities.HandleCallback(request, "Store Item has been removed", callback);
        }
Exemplo n.º 30
0
        private IEnumerator DownloadStoreItemsRoutine(bool chainedFromLogin, Action <string, bool> callback = null)
        {
            CloudLogin.Log("CloudLoginUser Download Store Items: ");

            if (CloudLogin.GetGameId() == null)
            {
                throw new CloudLoginException("Please set up your game with CloudLogin.SetUpGame before modifying users");
            }

            var parameters = "?authentication_token=" + GetAuthenticationToken();


            var request = UnityWebRequest.Get(CloudLogin.GetBaseURL() + "/users/" + CurrentUser.id + "/game_user_store_items" + parameters);

            request.SetRequestHeader("authentication_token", CloudLoginUser.CurrentUser.GetAuthenticationToken());

            yield return(request.SendWebRequest());

            if (CloudLoginUtilities.RequestIsSuccessful(request))
            {
                CloudLogin.Log("CloudLoginUser Download Store Items Success: ");

                var        data = request.downloadHandler.text;
                JSONObject json = JSONObject.Parse(data);
                var        game_user_store_items = json.GetArray("game_user_store_items");
                purchasedStoreItems.Clear();

                foreach (var item in game_user_store_items)
                {
                    purchasedStoreItems.Add(new CloudLoginStoreItem(
                                                item.Obj.GetString("name"),
                                                item.Obj.GetString("category"),
                                                item.Obj.GetString("description"),
                                                Convert.ToInt32(item.Obj.GetNumber("cost")),
                                                Convert.ToInt32(item.Obj.GetNumber("id"))));
                }
            }

            CloudLoginUtilities.HandleCallback(request, chainedFromLogin ? "Users has been signed in successfully" : "Users store items have been downloaded", callback);
        }