private void Cart_Click(object sender, EventArgs e) { if (productadded) { Intent cartpage = new Intent(this, typeof(CartActivity)); //productpage.PutExtra("productdetail", JsonConvert.SerializeObject(selectedproduct)); StartActivity(cartpage); } else { DocumentReference docRef = database.Collection("carts").Document(); HashMap map = new HashMap(); map.Put("buyername", username); map.Put("productname", selectedProduct.productname); map.Put("imageurl", selectedProduct.imageurl); map.Put("unitprice", 250); //map.Put("productimgurl", selectedProduct.); docRef.Set(map); Toast.MakeText(this, "Product Added to Cart", ToastLength.Long).Show(); cart.Text = "Go To Cart"; } //database = databaseservice.GetDataBase(); //User buyinguser = new User(); //buyinguser = SecondPageActivity.loggedinuser; //username = buyinguser.Fullname; }
public void testNuevaPuntuacion() { // Datos fijos para el test int puntos = 2000; string nombre = "Test"; try { // Creamos un id aleatorio para la colección string id = db.Collection("collection_name").Document().Id; // Creamos el documento con el id aleatorio DocumentReference docRef = db.Collection("puntuaciones").Document(id); // Le implementamos los datos // (esto puede ir incluso vacío, pero mejor lo construyo ya como nueva puntuación) var datos = new Dictionary <string, object> { { "nombre", nombre }, { "puntos", puntos } }; // Lo sincronizamos docRef.SetAsync(datos); Debug.Log("¡Test insertado!"); } catch { Debug.LogWarning("Fallo al insertar"); } }
public void writeData() { if (!string.IsNullOrEmpty(inputData.text)) { //Document(fbHandler.user.UserId) //DocumentReference docRef = db.Collection("InputData").AddAsync(); if (fbHandler.user != null) { Dictionary <string, object> data = new Dictionary <string, object> { { "Input", inputData.text } }; db.Collection(fbHandler.user.UserId).AddAsync(data).ContinueWithOnMainThread(task => { DocumentReference addedDocRef = task.Result; Debug.Log(string.Format("Added document with ID: {0}.", addedDocRef.Id)); }); } else { Debug.LogWarning("Sign In"); } } }
//Log-in process and validation email is clear public void GetAdmin(string email) { Query query = database.Collection("Users").WhereEqualTo("EMail", email); query.Get().AddOnCompleteListener(new QueryListener((task) => { if (task.IsSuccessful) { var snapshot = (QuerySnapshot)task.Result; if (!snapshot.IsEmpty) { var document = snapshot.Documents; foreach (DocumentSnapshot item in document) { string adminemail = item.GetString("EMail"); string adminName = item.GetString("Name"); string adminphonenum = item.GetString("PhoneNum"); string adminsport = item.GetString("Sport"); string profilepic = item.GetString("Profile"); Admin1 a = new Admin1(adminsport, adminName, adminphonenum, adminemail, profilepic); MyStuff.PutToShared(a); } } } Intent i = new Intent(this, typeof(MainPageActivity)); Toasty.Success(this, "Logged-In Successfully", 5, true).Show(); StartActivity(i); } )); }
public void AddUser(string username, string password, Action <StatusCode> completion) { if (!initialized) { completion(StatusCode.UNKNWON); return; } DocumentReference userRef = db.Collection("users").Document(username); StatusCode transactionStatus = StatusCode.OK; db.RunTransactionAsync(async transaction => { DocumentSnapshot user = await transaction.GetSnapshotAsync(userRef); if (user.Exists) { transactionStatus = StatusCode.USER_ALREADY_EXISTS; return(false); } transaction.Set(userRef, new Dictionary <string, object> { { "passwordHash", CreateMD5Hash(password) } }); return(true); }).ContinueWithOnMainThread(task => { completion(transactionStatus); }); }
public void OnClick_SignIn() { auth.SignInWithEmailAndPasswordAsync(EmailInput.text, PasswordInput.text).ContinueWith(task => { if (task.IsCanceled) { Debug.LogError("SignInWithEmailAndPasswordAsync was canceled."); return; } if (task.IsFaulted) { Debug.LogError("SignInWithEmailAndPasswordAsync encountered an error: " + task.Exception); return; } Firebase.Auth.FirebaseUser newUser = task.Result; Debug.LogFormat("User signed in successfully: {0} ({1})", EmailInput.text, newUser.UserId); }); usersRef = db.Collection("users"); docRef = usersRef.Document(EmailInput.text); SaveLogin(); LoadLobby(); }
private async void GetLeaderboard() { if (InternetAvailable()) { DocumentReference recordDocRef = db.Collection("recordStats").Document("total"); /* * Task<DocumentSnapshot> fetchRecordTask = recordDocRef.GetSnapshotAsync(); * await Task.WhenAll(fetchRecordTask, UploadTotalData(flooredTime)); * Dictionary<string, object> recordData = (await fetchRecordTask).ToDictionary(); * timeRecord = (long) recordData["time"]; */ /* * The above code is commented out * because I am using firebase cloud functions * to check when a new playthrough time is added and update the record if it's faster. * This is problematic because when fetching for the record, * I want the old record if the user just set a new record, * and therefore I want to first fetch the record, * then push to the database the user's playthrough time. */ double timeRecord = Math.Round((double)(await recordDocRef.GetSnapshotAsync()).ToDictionary()["time"], 2); await UploadTotalData(time); percentiles.Add(await FetchPercentile(time, "total")); CreateMessage(Math.Round(time, 2), timeRecord, percentiles.ToArray()); } else { CreateMessage(Math.Round(time, 2)); } percentiles = new List <float>(); }
public static void LoadLeaderboardData(int limit, Action <Task, LeaderboardData> callback) { CollectionReference collectionRef = db.Collection(leaderboardId); Query query = collectionRef.OrderByDescending(UserScoreData.USER_SCORE_PROPERTY_NAME).Limit(limit); query.GetSnapshotAsync().ContinueWithOnMainThread(task => { if (!task.IsCompleted) { return; } QuerySnapshot querySnapshot = task.Result; LeaderboardData leaderboardData = new LeaderboardData(); foreach (DocumentSnapshot docSnapshot in querySnapshot.Documents) { UserScoreData userScoreData = docSnapshot.ConvertTo <UserScoreData>(); leaderboardData.scores.Add(userScoreData); } callback?.Invoke(task, leaderboardData); }); }
public void botonIzquierdoPulsado() { DocumentReference docRef = db.Collection("animals").Document(nombres[izquierda].ToLower()); docRef.UpdateAsync("count", FieldValue.Increment(1)); izquierda = random.Next(imagenes.Length); nuevaImagen(botonIzquierda, izquierda); }
public void FetchExpensesTableForMonthYear() { if (!CrossConnectivity.Current.IsConnected) { Toast.MakeText(this, "Please check your internet connection", ToastLength.Long).Show(); return; } CollectionReference monthyearRef = database.Collection("ExpenseTable"); Query query = monthyearRef.WhereEqualTo("DateYear", YearSelected).WhereEqualTo("DateMonth", MonthSelected).WhereEqualTo("UserUid", CurrentUserUid).OrderBy(prefs.GetString("OrderBySelected", ""), Query.Direction.Descending); query.Get().AddOnSuccessListener(this).AddOnFailureListener(this); }
private void FetchAppointmentsWeek() { TaskCompletionListener appointmentsListener = new TaskCompletionListener(); appointmentsListener.Succes += AppointmentsListener_Succes; appointmentsListener.Failure += AppointmentsListener_Failure; _firestoreDb.Collection("Medics").Document(clientLogged.MedicSubscribed.Id).Collection("Appointments") .WhereGreaterThan("startTime", new Date()) .Get().AddOnSuccessListener(appointmentsListener) .AddOnFailureListener(appointmentsListener); }
void FetchExpenseItemsTable() { if (!CrossConnectivity.Current.IsConnected) { Toast.MakeText(Activity, "Please check your internet connection", ToastLength.Long).Show(); return; } CollectionReference ExpenseItemsRef = database.Collection("ExpenseItemsTable"); Query query = ExpenseItemsRef.OrderBy("ExpenseItemName", Query.Direction.Ascending); query.Get().AddOnSuccessListener(this).AddOnFailureListener(this); }
public void FetchData() { try { // add on success listener _firestoreDb.Collection("Medics").Get().AddOnSuccessListener(this).AddOnFailureListener(this); } catch (System.Exception ex) { Console.WriteLine("Error fetching medics:", ex.Message); Toast.MakeText(this, "Error fetching medics!", ToastLength.Long); } }
/// <summary> /// Dialog for editing first and last name /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void EditName_Click(object sender, EventArgs e) { LayoutInflater inflater = LayoutInflater.From(this); View view = inflater.Inflate(Resource.Layout.dialog_profile_name, null); AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.SetView(view); var fName = view.FindViewById <EditText>(Resource.Id.dialog_edit_fname); var lName = view.FindViewById <EditText>(Resource.Id.dialog_edit_lname); //string[] fullName = name.Text.Split(" "); //fName.Text = fullName[0]; //lName.Text = fullName[1]; alertBuilder.SetTitle("Edit Name") .SetPositiveButton("Submit", delegate { try { //get current user if (auth.CurrentUser != null) { var document = db.Collection("users").Document(auth.CurrentUser.Uid); var data = new Dictionary <string, Java.Lang.Object>(); data.Add("FName", fName.Text); data.Add("LName", lName.Text); document.Update((IDictionary <string, Java.Lang.Object>)data); Toast.MakeText(this, "Done!", ToastLength.Long).Show(); } else { Toast.MakeText(this, "Something went wrong. Sorry.", ToastLength.Long).Show(); } } catch (Exception ex) { Toast.MakeText(this, "Failed to update. Sorry.", ToastLength.Long).Show(); } }) .SetNegativeButton("Cancel", delegate { alertBuilder.Dispose(); }); AlertDialog alertDialog = alertBuilder.Create(); alertDialog.Show(); }
//Building the AddStudent Screen private void AddStudentButton_Click(object sender, EventArgs e) { if (IsValidName(NameAddStudentET.Text) && MyStuff.isValidEmail(EmailAddStudentET.Text, this) && currGroup != "Choose Group") { if (Parent1NameAddStudentET.Text != "" && Parent2NameAddStudentET.Text != "") { student = new Student(NameAddStudentET.Text, PhoneNumAddStudentET.Text, EmailAddStudentET.Text, Parent1NameAddStudentET.Text, Parent2NameAddStudentET.Text, AddStudentExplenationET.Text, currGroup); } if (Parent1NameAddStudentET.Text == "" && Parent2NameAddStudentET.Text != "") { student = new Student(NameAddStudentET.Text, PhoneNumAddStudentET.Text, EmailAddStudentET.Text, Parent2NameAddStudentET.Text, AddStudentExplenationET.Text, currGroup); } if (Parent1NameAddStudentET.Text != "" && Parent2NameAddStudentET.Text == "") { student = new Student(NameAddStudentET.Text, PhoneNumAddStudentET.Text, EmailAddStudentET.Text, Parent1NameAddStudentET.Text, AddStudentExplenationET.Text, currGroup); } if (Parent1NameAddStudentET.Text == "" && Parent2NameAddStudentET.Text == "") { student = new Student(NameAddStudentET.Text, PhoneNumAddStudentET.Text, EmailAddStudentET.Text, AddStudentExplenationET.Text, currGroup); } HashMap map = new HashMap(); map.Put("Name", student.name); map.Put("PhoneNum", student.phoneNumber); map.Put("Email", student.email); map.Put("Parent1", student.parentName1); map.Put("Parent2", student.parentName2); map.Put("Notes", student.notes); map.Put("Group", student.group); DocumentReference docref = database.Collection("Users").Document(admin.email).Collection("Students").Document(student.name + " " + student.phoneNumber); docref.Set(map); Toasty.Config.Instance .TintIcon(true) .SetToastTypeface(Typeface.CreateFromAsset(Assets, "Katanf.ttf")); Toasty.Success(this, "Student Added Sucesfully", 5, true).Show(); NameAddStudentET.Text = ""; PhoneNumAddStudentET.Text = "05"; EmailAddStudentET.Text = ""; Parent1NameAddStudentET.Text = ""; Parent2NameAddStudentET.Text = ""; AddStudentExplenationET.Text = ""; spin.SetSelection(0); } else { Toasty.Config.Instance .TintIcon(true) .SetToastTypeface(Typeface.CreateFromAsset(Assets, "Katanf.ttf")); Toasty.Error(this, "Input InValid", 5, true).Show(); } }
/// <summary> /// adds document to collection, with given info /// </summary> /// <param name="cName">collection name</param> /// <param name="dName">document name</param> /// <param name="hmFields">hashmap with fields to enter the document</param> /// <returns>task that is supposed to add document</returns> public Task AddDocumentToCollection(string cName, string dName, HashMap hmFields)//Use Dictionary instead of hashmap { DocumentReference cr; if (dName is null) { cr = firestore.Collection(cName).Document(); } else { cr = firestore.Collection(cName).Document(dName); } return(cr.Set(hmFields)); }
//private void Showgraph_Click(object sender, EventArgs e) //{ // PopupMenu popupmenu = new PopupMenu(this, showgraph); // popupmenu.MenuItemClick += Popupmenu_MenuItemClick; // popupmenu.Menu.Add(Menu.None, 1, 1, "Expenses for the Month"); // popupmenu.Menu.Add(Menu.None, 2, 2, "Expenses for the Year"); // popupmenu.Show(); //} private void FetchExpensesTableForYear() { if (!CrossConnectivity.Current.IsConnected) { generatePDF.Visibility = ViewStates.Invisible; progressBarStats.Visibility = ViewStates.Invisible; Toast.MakeText(this, "Please check your internet connection", ToastLength.Long).Show(); return; } progressBarStats.Visibility = ViewStates.Visible; CollectionReference monthyearRef = database.Collection("ExpenseTable"); Query query = monthyearRef.WhereEqualTo("DateYear", SelectedYear).WhereEqualTo("UserUid", CurrentUserUid); query.Get().AddOnSuccessListener(this).AddOnFailureListener(this); }
void Start() { FirebaseFirestore db = FirebaseFirestore.DefaultInstance; CollectionReference usersRef = db.Collection("InteriorDataCollection"); usersRef.GetSnapshotAsync().ContinueWithOnMainThread(task => { QuerySnapshot snapshot = task.Result; foreach (DocumentSnapshot document in snapshot.Documents) { Debug.Log(String.Format("User: {0}", document.Id)); Dictionary <string, object> documentDictionary = document.ToDictionary(); InteriorData interiorData = new InteriorData(); interiorData.id = int.Parse(documentDictionary["id"].ToString()); string[] prices = documentDictionary["price"].ToString().Split('/'); interiorData.price = float.Parse(prices[0]); interiorData.priceUnit = prices[1]; interiorData.purchaseType = documentDictionary["purchaseType"].ToString(); interiorData.unlockStage = int.Parse(documentDictionary["unlockStage"].ToString()); } Debug.Log("Read all data from the users collection."); }); }
public override void OnViewCreated(View view, Bundle savedInstanceState) { base.OnViewCreated(view, savedInstanceState); // Assigns values to the form controls allItemsPrice = 0.0M; total = view.FindViewById <TextView>(Resource.Id.totalCost); cart = view.FindViewById <LinearLayout>(Resource.Id.shopping_cart); btnPurchase = view.FindViewById <Button>(Resource.Id.btnPurchase); delete = view.FindViewById <ImageView>(Resource.Id.delete); orderedList = view.FindViewById <RecyclerView>(Resource.Id.rcvOrders); db = FirebaseFirestore.GetInstance(FirestoreUtils.App); auth = FirestoreUtils.Auth; btnPurchase.Click += BtnPurchase_Click; userOrders = new List <Order>(); orderFilter = db.Collection("Orders").WhereEqualTo("Uid", auth.CurrentUser.Uid); FetchData(); }
public void guardarNombre() { repe = false; nick = GameObject.Find("inputNick").GetComponent <TextMeshProUGUI>(); Debug.Log(nick); foreach (var nic in nicks) { Debug.Log("entra en el for each"); if (nick.text.Equals(nic)) { repe = true; } } if (repe) { textRepe.SetActive(true); } else { Debug.Log("entrapara meter datos"); DocumentReference docref = db.Collection("jugadores").Document(nick.text); var datos = new Dictionary <string, object> { { "puntos", score } }; docref.SetAsync(datos); guardar.SetActive(false); textRepe.SetActive(false); } }
public async void FBModelImport() { Rootobject result = new Rootobject(); //var allCitiesQuery = DB.Collection("models"); //var docModel = allCitiesQuery.Document("test1"); //Firebase.Firestore.DocumentSnapshot snapshot = await docModel.GetSnapshotAsync(); //if (snapshot.Exists) // { // var st = Newtonsoft.Json.JsonConvert.SerializeObject(snapshot.ToDictionary()); // importModel = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(st); // CreateMaterials.create(importModel.materials); // //Create Main Object // GameObject MainObj = new GameObject(importModel._object.name); // //Create geometries // List<GameObject> createdGeom = Geometries.create(importModel.geometries); // //Create Childrens and assign them to Main Object // ObjChildrens.create(importModel._object.children, MainObj, createdGeom); //} // else // { // Debug.Log("Document {0} does not exist!" + snapshot.Id.ToString()); // } try { DocumentReference docRef = DB.Collection("models").Document("test1"); var listener = docRef.Listen(snapshot => { if (snapshot.Exists) { var st = Newtonsoft.Json.JsonConvert.SerializeObject(snapshot.ToDictionary()); importModel = Newtonsoft.Json.JsonConvert.DeserializeObject <Rootobject>(st); //If the element already exists remove it var gameObjects = SceneManager.GetActiveScene().GetRootGameObjects(); foreach (GameObject go in gameObjects) { if (go.name == importModel._object.name) { Destroy(go); } } CreateMaterials.create(importModel.materials); //Create Main Object //Create main Game object GameObject MainObj = new GameObject(importModel._object.name); //Create geometries List <GameObject> createdGeom = Geometries.create(importModel.geometries); //Create Childrens and assign them to Main Object ObjChildrens.create(importModel._object.children, MainObj, createdGeom); } }); } catch { } }
/** * Function that * 1. Hashes the downloaded map data * 2. Checks to see if the map has a current high score * * */ public void CheckForHighScore() { FirebaseFirestore db = FirebaseFirestore.DefaultInstance; CollectionReference colRef = db.Collection("Maps"); // Get hash value for map data SHA256Managed hash = new SHA256Managed(); byte[] result = hash.ComputeHash(heightData); string hashValue = ""; foreach (byte b in result) { hashValue += b.ToString("x2"); } map_hash_value = hashValue; //query the db to see if the map exists Firebase.Firestore.Query query = colRef.WhereEqualTo("hash", hashValue); query.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask) => { foreach (DocumentSnapshot docSnap in querySnapshotTask.Result.Documents) { Dictionary <string, object> mapObj = docSnap.ToDictionary(); var mapScore = mapObj["score"]; double mapScoreD; double.TryParse(mapScore.ToString(), out mapScoreD); mapHighScore = mapScoreD; } }); }
protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); SetContentView(Resource.Layout.activity_main); Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); SetSupportActionBar(toolbar); recyclerView = (RecyclerView)FindViewById(Resource.Id.myRecyclerView); searchButton = (ImageView)FindViewById(Resource.Id.searchButton); searchText = (EditText)FindViewById(Resource.Id.searchText); phones = DataHelper.SeedData(); db = DataHelper.GetDatabsase(); var a = db.Collection("phones").Document("AIppzUUfprOLuMXga7PC").Get().AddOnSuccessListener(this); SetupRecycleView(); //FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.addNewPhone); //fab.Click += FabOnClick; }
public override void OnViewCreated(View view, Bundle savedInstanceState) { base.OnViewCreated(view, savedInstanceState); // Assigns the control objects to their XAML counterparts orderQuantity = 1; quantity = view.FindViewById <TextView>(Resource.Id.orderQuantity); itemInfo = view.FindViewById <TextView>(Resource.Id.description); itemPrice = view.FindViewById <TextView>(Resource.Id.price); foodChoice = view.FindViewById <Spinner>(Resource.Id.allItems); rootView = view.FindViewById <LinearLayout>(Resource.Id.rootView); increaseQuantity = view.FindViewById <Button>(Resource.Id.quantityIncrease); decreaseQuantity = view.FindViewById <Button>(Resource.Id.quantityDecrease); addToCart = view.FindViewById <Button>(Resource.Id.add_to_cart); db = FirebaseFirestore.GetInstance(FirestoreUtils.App); // Setting up event listeners foodChoice.ItemSelected += FoodChoice_ItemSelected; increaseQuantity.Click += IncreaseQuantity_Click; decreaseQuantity.Click += DecreaseQuantity_Click; addToCart.Click += AddToCart_Click; CollectionReference cr = db.Collection("Items"); cr.Get().AddOnSuccessListener(this); }
// Start is called before the first frame update void Start() { jugador = FindObjectOfType <puntuacionFinal>(); score = jugador.puntos; puntosJugador.GetComponent <TextMeshProUGUI>().text = $" {score} puntos"; textRepe.SetActive(false); db = FirebaseFirestore.GetInstance(FirebaseApp.Create()); CollectionReference jugadoresRef = db.Collection("jugadores"); Query query = jugadoresRef.OrderByDescending("puntos").Limit(5); ListenerRegistration listener = query.Listen(snapshot => { string top5 = "TOP 5 \n\n"; var cont = 1; foreach (DocumentSnapshot documentSnapshot in snapshot.Documents) { Dictionary <string, object> jugador = documentSnapshot.ToDictionary(); top5 += $"{cont}-{documentSnapshot.Id}..........{jugador["puntos"]}\n"; cont += 1; nicks.Add(documentSnapshot.Id.ToString()); } marcador.GetComponent <TextMeshProUGUI>().text = top5; }); }
public void GetUserName() { FirebaseFirestore db = FirebaseFirestore.DefaultInstance; DocumentReference docRef = db.Collection("users").Document(userUID); docRef.GetSnapshotAsync().ContinueWithOnMainThread(task1 => { DocumentSnapshot snapshot = task1.Result; if (snapshot.Exists) { Debug.Log(string.Format("Document data for {0} document:", snapshot.Id)); Dictionary <string, object> user1 = snapshot.ToDictionary(); userName = user1["FirstName"].ToString(); totalCoins = int.Parse(user1["TotalCoins"].ToString()); Debug.Log("userName is " + userName); Debug.Log("remeberMe.isOn value is " + remeberMe.isOn); if (remeberMe.isOn) { Debug.Log("in remember me if condition"); RememberMe(); } signin = true; } }); }
/// <summary> /// Fetch user's account detailsfrom firebase /// </summary> private void GetUserDetails() { //User is logged in if (auth != null) { CollectionReference collection = db.Collection("users"); collection.WhereEqualTo("Uid", auth.Uid).AddSnapshotListener(this); } }
public void CreateUserDocument() // Creates firebase document with UID in "AllUsers" collection. { Debug.Log("in create user doc"); FirebaseFirestore db = FirebaseFirestore.DefaultInstance; Debug.Log("in create user doc after firebase db initialization"); DocumentReference docRef = db.Collection("users").Document(SignUp2.registeredUserID); Dictionary <string, object> user = new Dictionary <string, object> { { "FirstName", firstName.text }, { "LastName", lastName.text }, { "Email", email.text }, { "pincode", pincode.text }, { "Day", dayDropdown.options[dayDropdown.value].text }, { "Month", monthDropDown.options[monthDropDown.value].text }, { "Year", yearDropDown.options[yearDropDown.value].text }, { "Address1", address1.text }, { "Address2", address2.text }, { "City", city.text }, { "Mobile", "+91" + mobile.text }, { "Gender", male.allowSwitchOff }, { "Role", "Patient" }, { "UserID", SignUp2.registeredUserID }, { "TotalCoins", 0 } // {"AddNotification",false }, // {"RequestedTherapistUID","null" }, // {"IsRoutineSessionSet", false }, // {"TherapistUID","null" } }; docRef.SetAsync(user).ContinueWithOnMainThread(task => { Debug.Log("Paitent Added"); }); Debug.Log("Patient UID reg is " + SignUp2.registeredUserID); FirebaseFirestore db2 = FirebaseFirestore.DefaultInstance; DocumentReference docRef2 = db2.Collection("users").Document(SignUp2.registeredUserID).Collection("armable").Document("overallProgress"); Dictionary <string, object> user1 = new Dictionary <string, object> { { "totalGameSessionsPlayed", 0 }, { "totalGameDistanceMoved", 0 }, { "totalTimePlayed", 0 }, { "totalRepetitions", 0 }, { "currentSessionNmbr", 0 }, }; docRef2.SetAsync(user1).ContinueWithOnMainThread(task => { Debug.Log("Overall progress document for armable is initialised"); }); register = true; }
public void Firestore_DefaultInstanceShouldBeStable() { FirebaseFirestore db1 = FirebaseFirestore.DefaultInstance; FirebaseFirestore db2 = FirebaseFirestore.DefaultInstance; Assert.That(db1, Is.SameAs(db2)); Assert.That(db1, Is.SameAs(db1.Collection("a").WhereEqualTo("x", 1).Firestore)); Assert.That(db2, Is.SameAs(db2.Document("a/b").Firestore)); }
void Start() { // Conexión a Firestore db = FirebaseFirestore.DefaultInstance; botonIzquierda = GameObject.Find("BotonIzquierda"); botonDerecha = GameObject.Find("BotonDerecha"); marcador = GameObject.Find("Marcador"); izquierda = random.Next(imagenes.Length); nuevaImagen(botonIzquierda, izquierda); derecha = random.Next(imagenes.Length); nuevaImagen(botonDerecha, derecha); // Crear los documentos vacíos foreach (var nombre in nombres) { DocumentReference docRef = db.Collection("animals").Document(nombre.ToLower()); var datos = new Dictionary <string, object> { }; docRef.SetAsync(datos, SetOptions.MergeAll); } // Observar una colección CollectionReference animalsRef = db.Collection("animals"); Query query = animalsRef.Limit(10).OrderByDescending("count"); ListenerRegistration listener = query.Listen(snapshot => { String top10 = "Top 10\n\n"; foreach (DocumentSnapshot documentSnapshot in snapshot.Documents) { Dictionary <string, object> animal = documentSnapshot.ToDictionary(); top10 += $"{documentSnapshot.Id} ({animal["count"]})\n"; } marcador.GetComponent <TMP_Text>().text = top10; }); }