Пример #1
0
    public void SyncUnfold(UnfoldData data, Action <UnfoldData> callback, Action <AggregateException> fallback)
    {
        var json = StringSerializationAPI.Serialize(typeof(UnfoldData), data);

        reference.Child("worlds/world_1234/pieces").Push().SetRawJsonValueAsync(json).ContinueWith(task =>
        {
            if (task.IsCanceled || task.IsFaulted)
            {
                fallback(task.Exception);
            }
            else
            {
                callback(data);
            }
        });
    }
Пример #2
0
    private void GetNameEmail()
    {
        DatabaseReference childReference = databaseReference.Child("Users").Child(holderid);

        childReference.GetValueAsync().ContinueWith(task =>
        {
            if (task.IsFaulted)
            {
                // Handle the error...
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                // Do something with snapshot...
                name = snapshot.Child("Name").Value.ToString();
                Debug.Log("Holder name : " + name);
                email = snapshot.Child("email").Value.ToString();
                Debug.Log("Holder mail : " + email);

                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(email))
                {
                    nameObject.GetComponent <Text>().text  = name;
                    emailObject.GetComponent <Text>().text = email;
                }
            }
        });
    }
Пример #3
0
    public void PushData(string path, string data)
    {
        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://art-152.firebaseio.com/");
        DatabaseReference DBreference = FirebaseDatabase.DefaultInstance.RootReference;

        DBreference.Child(path).SetValueAsync(data);
    }
Пример #4
0
    public void AddScore(string iduser)
    {
        nombre      = Nombre.text;
        descripcion = Descripcion.text;
        string Puntaje = "10000";
        string Dinero  = "2000000";

        if (string.IsNullOrEmpty(nombre) || string.IsNullOrEmpty(descripcion))
        {
            DebugLog("invalid score or email.");
            return;
        }
        DebugLog(String.Format("Attempting to add score {0} {1}",
                               nombre, descripcion.ToString()));
        Dictionary <string, object> newScoreMap = new Dictionary <string, object>();

        newScoreMap["nombre"]      = nombre;
        newScoreMap["descripcion"] = descripcion;
        newScoreMap["Puntaje"]     = Puntaje;
        newScoreMap["Dinero"]      = Dinero;
        ;        DatabaseReference reference = FirebaseDatabase.DefaultInstance.GetReference("/usuarios");
        try
        {
            reference.Child(iduser).SetValueAsync(newScoreMap);
            DebugLog("Registro añadido");
            Application.LoadLevel("Main");
        }
        catch (Exception)
        {
            DebugLog("Registro no añadido");
        }
    }
Пример #5
0
    /// <summary>
    /// Automatically call a function whenever a lobby is added, changed, moved or deleted
    /// </summary>
    /// <param name="callbackFunction"></param>
    public void AutoUpdateLoop(System.Action callbackFunction)
    {
        DatabaseReference _ref = FirebaseDatabase.DefaultInstance.RootReference.Child("Lobbies");

        _ref.ChildAdded += (sender, eventArgs) =>
        {
            callbackFunction();
        };

        _ref.ChildChanged += (sender, eventArgs) =>
        {
            callbackFunction();
        };

        _ref.ChildMoved += (sender, eventArgs) =>
        {
            callbackFunction();
        };

        _ref.ChildRemoved += (sender, eventArgs) =>
        {
            //Debug.Log(eventArgs.Snapshot.ToString());
            callbackFunction();
        };

        if (is_in_lobby != "")
        {
            _ref.Child(is_in_lobby).ChildRemoved += (sender, eventArgs) =>
            {
                Debug.Log("Lobby " + is_in_lobby + " got removed!");
            };
        }
    }
Пример #6
0
        protected async void CreateUser(string uid)
        {
            UserProfileModel user = new UserProfileModel();

            user.uid      = uid;
            user.name     = nameText;
            user.email    = emailText;
            user.mobileno = mobileText;
            user.location = locationText;
            user.password = passwordText;

            DatabaseReference database = FirebaseDatabase.Instance.Reference;

            var stringEndPoint = database.Child("User").Child(uid);

            stringEndPoint.Child("name").SetValue(nameText);
            stringEndPoint.Child("uid").SetValue(uid);
            stringEndPoint.Child("email").SetValue(emailText);
            stringEndPoint.Child("mobileno").SetValue(mobileText);
            stringEndPoint.Child("location").SetValue(locationText);
            stringEndPoint.Child("password").SetValue(passwordText);


            ISharedPreferences       prefs  = PreferenceManager.GetDefaultSharedPreferences(Application.Context);
            ISharedPreferencesEditor editor = prefs.Edit();

            editor.PutString("location", locationText);
            editor.Apply();

            Toast.MakeText(this, "Register Success!!", ToastLength.Short).Show();

            MoveToDashboard();
        }
Пример #7
0
    public void SaveCharacter(Character character)
    {
        string json = JsonUtility.ToJson(character);

        // adding character to firebase database
        reference.Child("Characters").Child("Character" + characterCount).SetRawJsonValueAsync(json);
    }
Пример #8
0
    private void SendData()
    {
        counter++;
        string name = modelnametext.text;
        string size = modelsizetext.text;

        Animal modemyl = new Animal(name, size);
        string myjson  = JsonUtility.ToJson(modemyl);

        Debug.LogFormat("MDEL", modemyl);

        reference.Child("Animals").Child(counter + "").Child("name").SetValueAsync(name);
        reference.Child("Animals").Child(counter + "").Child("size").SetValueAsync(size);

        Debug.LogFormat(" UPDATED ");
    }
Пример #9
0
        void Start()
        {
            currentSkin = PlayerPrefs.GetString("CurrentSkin");
            username    = PlayerPrefs.GetString("username");
            GameObject playerPrefab = Resources.Load <GameObject>("Characters/00testCharacter");

            playerPrefab.transform.position = new Vector3(2, 1, 4);
            player = Instantiate(playerPrefab) as GameObject;
            player.AddComponent <TestCharacterScript>();
            StartCoroutine(AddOtherPlayers());
            DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;

            reference.Child("inWorld").GetValueAsync().ContinueWith(task => {
                DataSnapshot snapshot = task.Result;
                if (snapshot.Value != null)
                {
                    Dictionary <string, object> players = snapshot.Value as Dictionary <string, object>;
                    foreach (KeyValuePair <string, object> player in players)
                    {
                        if (player.Key != username)
                        {
                            otherPlayers.Add(player.Key);
                        }
                    }
                    readyToAddOthers = true;
                }
            });
        }
Пример #10
0
    private void writeNewUser(string email, string score, string password)
    {
        User   user = new User(score);
        string json = JsonUtility.ToJson(user);

        reference.Child(email).SetRawJsonValueAsync(json);
    }
Пример #11
0
    /**
     * this method handles writing the newly created data to the database
     * @param json - json string of custom stage data
     */
    private IEnumerator writeCustomStageToFirebase(string json)
    {
        quizId = DBreference.Child("customStage").Push().Key;
        var pokemonTask = DBreference.Child("customStage").Child(quizId).SetRawJsonValueAsync(json);

        yield return(new WaitUntil(predicate: () => pokemonTask.IsCompleted));

        if (pokemonTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {pokemonTask.Exception}");
        }
        else
        {
            Debug.Log("successful update custom stage to DB");
        }
    }
Пример #12
0
    public void writeNewUserData(MazeData data, string userId, string mazeTitle)
    {
        databaseReference = FirebaseDatabase.DefaultInstance.RootReference;
        string json = JsonUtility.ToJson(data);

        databaseReference.Child("users").Child(userId).Child(mazeTitle).SetRawJsonValueAsync(json);
    }
Пример #13
0
        private void getreservationData()
        {
            DatabaseReference database = FirebaseDatabase.Instance.Reference;
            Query             query    = database.Child("Booked").OrderByChild("cust_id").EqualTo(FirebaseAuth.Instance.CurrentUser.Uid);

            query.AddListenerForSingleValueEvent(this);
        }
Пример #14
0
    /**
     * this method gets the custom stage data from database
     * @param id - id of the custom stage requested
     */
    private IEnumerator getCustomStageFromFirebase(string id)
    {
        var DBTask = DBreference.Child("customStage").Child(id).GetValueAsync();

        yield return(new WaitUntil(predicate: () => DBTask.IsCompleted));

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
        else
        {
            DataSnapshot snapshot = DBTask.Result;
            if (snapshot.Value == null)
            {
                if (errorMessage != null)
                {
                    errorMessage.SetActive(true);
                }
            }
            else
            {
                if (errorMessage != null)
                {
                    errorMessage.SetActive(false);
                }
                string     json        = snapshot.GetRawJsonValue();
                GameObject dataManager = GameObject.FindGameObjectWithTag("DataManager");
                customStage      = CustomStage.CreateFromJSON(json);
                customStageCheck = true;
                Debug.Log(customStage.questions[0]);
                SceneManager.LoadScene("test");
            }
        }
    }
Пример #15
0
    private void addNewUser(string userId, string name, string email)
    {
        User   user = new User(name, email);
        string json = JsonUtility.ToJson(user);

        UserListDB.Child("users").Child(userId).SetRawJsonValueAsync(json);
    }
    private void Start()
    {
        multiplayerManagerClass = this;

        //Aktif oyuncu sahneye bağlandığı sırada Database'e kendi verilerini gönderir ve kostüm değişikliği uygulanır.
        userDataRef.Child(auth.CurrentUser.UserId).GetValueAsync().ContinueWithOnMainThread(task =>
        {
            DataSnapshot snapshot = task.Result;
            if (snapshot.GetRawJsonValue() != null)
            {
                UserData me     = JsonUtility.FromJson <UserData>(snapshot.GetRawJsonValue());
                Player playerMe = new Player();
                playerMe.userId = auth.CurrentUser.UserId;
                playerMe.nick   = me.nick;
                playerMe.skin   = me.skin;
                roomRef.Child("GameScene").Child(auth.CurrentUser.UserId).SetRawJsonValueAsync(JsonUtility.ToJson(playerMe));
                playerObject.GetComponent <Renderer>().material.color = me.skin;
            }
        });

        //Aktif oyuncunun bulunduğu odadaki oyuna bağlanacak olan oyuncu sayısı ilgili değişkene atanır.
        roomRef.GetValueAsync().ContinueWithOnMainThread(task =>
        {
            DataSnapshot snapshot = task.Result;
            if (snapshot.GetRawJsonValue() != null)
            {
                RoomData room      = JsonUtility.FromJson <RoomData>(snapshot.GetRawJsonValue());
                playingPlayerCount = room.playingPlayerCount;
            }
        });
    }
Пример #17
0
        public void getFromServer(DatabaseReference databaseReference, BookGetInfoDeleGate callback, string textObject, string imgObject, bool isLeftPage)
        {
            BookGetInfoDetail infoDetail = new BookGetInfoDetail();

            data.Clear();
            databaseReference.Child("public").Child(GlobalVar.LANGUAGE).Child("books").Child(id.ToString()).ValueChanged += (object sender, ValueChangedEventArgs args) => {
                if (args.DatabaseError != null)
                {
                    Debug.LogError(args.DatabaseError.Message);
                    return;
                }
                if (args.Snapshot != null && args.Snapshot.ChildrenCount > 0)
                {
                    infoDetail.name            = args.Snapshot.Child("name").Value.ToString();
                    infoDetail.status          = int.Parse(args.Snapshot.Child("status").Value.ToString());
                    infoDetail.price           = int.Parse(args.Snapshot.Child("price").Value.ToString());
                    infoDetail.picture_url     = args.Snapshot.Child("picture_url_resized").Value.ToString();
                    infoDetail.description     = args.Snapshot.Child("description").Value.ToString();
                    infoDetail.version         = args.Snapshot.Child("version").Value.ToString();
                    infoDetail.min_app_version = args.Snapshot.Child("min_app_version").Value.ToString();
                    infoDetail.assetbundle     = args.Snapshot.Child("assetbundle").Value.ToString();
                    infoDetail.download_url    = args.Snapshot.Child("download_url").Value.ToString();
                    data.Add(infoDetail);
//					Debug.Log("getFromServer: " + data.Count );
//					Debug.Log("getFromServer name: " + data[0].name );
//					Debug.Log("getFromServer description: " + data[0].description );
                    callback(data, textObject, imgObject, isLeftPage);
                }
            };
        }
Пример #18
0
    public void BirdDied()
    {
        //Activate the game over text.
        FinJuego.SetActive(true);
        //Set the game to be over.
        gameOver = true;

        if (!ScoredToServer)
        {
            if (score > 0)
            {
                FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://flappy-game-3699b.firebaseio.com/");

                // Get the root reference location of the database.
                DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;


                User   user = new User(playerName, -score);
                string json = JsonUtility.ToJson(user);

                reference.Child("puntuaciones").Push().SetRawJsonValueAsync(json);
            }
            MostrarMenu(true, false);

            ScoredToServer = true;
        }
    }
Пример #19
0
    public void writeNewPlayer(string playerName, int win, int lose)
    {
        FirebaseDatabase.DefaultInstance
        .GetReference("Player").Child(playerName)
        .GetValueAsync().ContinueWith(task => {
            if (task.IsFaulted)
            {
                Debug.Log("Error");
            }
            else if (task.IsCompleted)
            {
                DataSnapshot snapshot = task.Result;
                if (snapshot.Value != null)
                {
                    var stat = snapshot.Value as Dictionary <string, object>;
                    foreach (var item in stat)
                    {
                        if (item.Key == "win")
                        {
                            win += int.Parse(item.Value.ToString());
                        }
                        if (item.Key == "lose")
                        {
                            lose += int.Parse(item.Value.ToString());
                        }
                    }
                }
            }
            Stat playerStat = new Stat(win, lose);
            string json     = JsonUtility.ToJson(playerStat);

            myDatabaseRef.Child("Player").Child(playerName).SetRawJsonValueAsync(json);
        });
    }
    public void Save()
    {
        //version 3
        Debug.Log("서버에 저장중 !");
        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://unitybossraidgame.firebaseio.com/");
        DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;
        //InventoryObject inventoryObject = new InventoryObject(database,Container);
        string saveData = JsonUtility.ToJson(this, true);

        reference.Child("Items").SetRawJsonValueAsync(saveData);
        Debug.Log("서버에 저장하기 성공 !");

        //version 1
        //string saveData = JsonUtility.ToJson(this, true);
        //BinaryFormatter bf = new BinaryFormatter();
        //FileStream file
        //    = File.Create(string.Concat(Application.persistentDataPath, savePath));
        //bf.Serialize(file, saveData);
        //file.Close();


        //version 2
        //IFormatter formatter = new BinaryFormatter();
        //Stream stream = new FileStream(string.Concat(Application.persistentDataPath, savePath)
        //    , FileMode.Create, FileAccess.Write);
        //Debug.Log(string.Concat(Application.persistentDataPath, savePath));
        //formatter.Serialize(stream, Container);
        //stream.Close();
    }
Пример #21
0
    void SignUp(string UserId, string Name, string email)
    {
        Login  login = new Login(name, email);
        string json  = JsonUtility.ToJson(login);

        mDatabaseRef.Child("users").Child(UserId).SetRawJsonValueAsync(json);
    }
Пример #22
0
    // 닉네임 변경하기
    private void ChangeNickName()
    {
        Debug.Log("ChangeNickName() is started");
        if (user != null && IsSuccessOnReAuth == true)
        {
            // Auth의 DisplayName 바꾸기
            UserProfile profile = new UserProfile {
                DisplayName = nickNameField.text
            };
            AuthManager.User.UpdateUserProfileAsync(profile).ContinueWith(task => {
                if (task.IsCanceled)
                {
                    Debug.LogError("Setting DisplayName was canceled.");
                    return;
                }
                if (task.IsFaulted)
                {
                    Debug.LogError("Setting DisplayName encountered an error: " + task.Exception);
                    return;
                }
                Debug.Log("Successfully changed at Auth: " + AuthManager.User.DisplayName);
            });

            // DB의 닉네임 바꾸기
            DatabaseReference reference = FirebaseDatabase.DefaultInstance.RootReference;

            string key = AuthManager.User.UserId;
            reference.Child("users").Child(key).Child("nickName").SetValueAsync(nickNameField.text);
            Debug.Log("Succesfully changed at DB.");
        }
    }
Пример #23
0
    private void writeNewUser(string userId, string name, string email)
    {
        User   user = new User(name, email);
        string json = JsonUtility.ToJson(user);

        reference.Child("users").Child(userId).SetRawJsonValueAsync(json);
    }
Пример #24
0
 void GetJoinRoomId()
 {
     Debug.Log($"GetJoinRoomId");
     m_referenceMyUser.Child(UserModel.RoomId)
     .GetValueAsync()
     .ContinueWith((System.Action <System.Threading.Tasks.Task <DataSnapshot> >)(task =>
     {
         if (task.Exception != null)
         {
             Debug.LogError(task.Exception);
         }
         else if (task.IsCompleted)
         {
             if (m_joinRoom != null)
             {
                 string roomId = task.Result.GetValue(true).ToString();
                 m_joinRoom(roomId);
             }
         }
         else
         {
             Debug.LogWarning(task);
         }
     }));
 }
Пример #25
0
    private void InitTopBar()
    {
        showLoading();
        Debug.Log("Init top bar");
        //get coin from db
        DatabaseReference userRef = reference.Child("User").Child(PlayerPrefs.GetString("uid"));

        topBarPanel.SetActive(true);

        userRef.Child("Coin").GetValueAsync().ContinueWith(task => {
            if (task.IsFaulted)
            {
                Debug.Log("coin get failed");
                coinText.text = "0";
            }
            else if (task.IsCompleted)
            {
                Debug.Log("coin get complete");

                DataSnapshot snapshot = task.Result;
                Debug.Log("coin = " + snapshot.Value.ToString());
                //int coin = (int) snapshot.Value;
                coinText.text = snapshot.Value.ToString();
            }
            disableLoading();
        });
    }
Пример #26
0
    /**
     * this method handles loading email data of users from database
     */
    private IEnumerator LoadEmailData()
    {
        var DBTask = DBreference.Child("emails").GetValueAsync();


        yield return(new WaitUntil(predicate: () => DBTask.IsCompleted));

        if (DBTask.Exception != null)
        {
            Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
        }
        else
        {
            //Data has been retrieved
            DataSnapshot snapshots = DBTask.Result;


            foreach (var childSnapshot in snapshots.Children)
            {
                string email = childSnapshot.Child("email").Value.ToString();
                emailist.Add(email);
            }
            dropdown.AddOptions(emailist);
        }
    }
    private void writeNewPosition()
    {
        string cameraJson = JsonUtility.ToJson(Camera.main.transform.position);

        mDatabaseRef.Child("User/CameraPosition").SetRawJsonValueAsync(cameraJson);

        Vector3 leftHandPosition = leftHand.transform.GetChild(0).gameObject.transform.position;
        string  leftJson         = JsonUtility.ToJson(leftHandPosition);

        mDatabaseRef.Child("User/LeftHandPosition").SetRawJsonValueAsync(leftJson);

        Vector3 rightHandPosition = rightHand.transform.GetChild(0).gameObject.transform.position;
        string  rightJson         = JsonUtility.ToJson(rightHandPosition);

        mDatabaseRef.Child("User/RightHandPosition").SetRawJsonValueAsync(rightJson);
    }
Пример #28
0
    public FirebaseManager CreateNew(string id)
    {
#if UNITY_EDITOR
        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://pcgtalk-81074.firebaseio.com/");
        if (FirebaseApp.DefaultInstance.Options.DatabaseUrl != null)
        {
            FirebaseApp.DefaultInstance.SetEditorDatabaseUrl(FirebaseApp.DefaultInstance.Options.DatabaseUrl);
        }
#endif

        m_RootReference = FirebaseDatabase.DefaultInstance.RootReference;
        DatabaseReference current = string.IsNullOrEmpty(id) ? m_RootReference.Push() : m_RootReference.Child(id);

        m_RootReference.Child("current").SetValueAsync(current.Key).ContinueWith(

            task => {
            if (task.IsFaulted)
            {
                ScheduleLog("Error in CreateNew");
            }
            else if (task.IsCompleted)
            {
                InitDatabase(/*current.Key*/);
            }
        }

            );

        return(this);
    }
Пример #29
0
    //Whent he return button is pressed, the balance of the player is udated on the database and the world scene is loaded
    public void returnButton()
    {
        reference.Child("users").Child(userID).Child("balance").SetValueAsync(userBalance);

        SceneManager.LoadSceneAsync(1);
        //SceneManager.LoadScene(1);
    }
Пример #30
0
    // Use this for initialization
    void Start()
    {
        auth = Firebase.Auth.FirebaseAuth.DefaultInstance;
        user = auth.CurrentUser;

        if (user != null)
        {
            // テキストの表示
            this.userName.text = user.DisplayName;
            Debug.Log(user.DisplayName);
        }

        FirebaseApp.DefaultInstance.SetEditorDatabaseUrl("https://hamukatsu2-9bebb.firebaseio.com/");

        // Get the root reference location of the database.
        reference = FirebaseDatabase.DefaultInstance.RootReference;

        Debug.Log(user.UserId);
        Debug.Log(user.DisplayName);


        User newUser = new User(user.DisplayName);

        string json = JsonUtility.ToJson(newUser);

        reference.Child("users").Child(user.UserId).SetRawJsonValueAsync(json);

        FirebaseDatabase.DefaultInstance.GetReference("users").ValueChanged += HandleValueChanged;
    }