/** Create a document for productStatus in database*/ public async Task <bool> CreateProductStatus(ProductStatus productStatus) { // Get productStatus reference DocumentReference productDocumentRef = firestoreDb.Collection(DB_STATUS_COLLECTION).Document(); // Set up data for productStatus in database Dictionary <string, object> productUpdateDictionary = new Dictionary <string, object> { { DB_STATUS_USER_ID, productStatus.UserId }, { DB_STATUS_PRODUCT_ID, productStatus.Product.Id }, { DB_STATUS_PRODUCT_STATUS, productStatus.Status }, { DB_STATUS_PRODUCT_PURCHASE_DATE, productStatus.PurchaseDate } }; try { // Update productStatus await productDocumentRef.CreateAsync(productUpdateDictionary); } catch (Exception e) { // Return false because task was not successful return(false); } // Return true because task was successful return(true); }
/** Validates if basket needs to be created and adds product's id to it */ public async Task <bool> AddProductToBasket(string basketId, string productId) { // List that holds products ids that are in the basket List <string> productsIds = new List <string>(); // Add product to list productsIds.Add(productId); // Get Basket var docRef = firestoreDb.Collection(DB_BASKET_COLLECTION).Document(basketId); DocumentSnapshot snapshot = await docRef.GetSnapshotAsync(); // If it exists if (snapshot.Exists) { // Get basket's products list productsIds.AddRange(snapshot.GetValue <List <string> >("ProductIds")); // Set new value for basket's products list Dictionary <string, object> basket = new Dictionary <string, object> { { "ProductIds", productsIds } }; try { // Update Basket await docRef.UpdateAsync(basket); } catch (Exception e) { // If error occoured return false return(false); } } else { // If basket doesnt exist // Create basket with productsIds Dictionary <string, object> basket = new Dictionary <string, object> { { "ProductIds", productsIds } }; // Get Reference to basket with provided id DocumentReference addedDocRef = firestoreDb.Collection(DB_BASKET_COLLECTION).Document(basketId); try { // Create basket in database WriteResult wr = await addedDocRef.CreateAsync(basket); } catch (Exception e) { // If error occoured return false return(false); } } // Task was successfull return true return(true); }
public async Task Listening1() { DocumentReference doc = db.Collection("testecsharp").Document(); FirestoreChangeListener listener = doc.Listen(snapshot => { Console.WriteLine($"Callback received document snapshot"); Console.WriteLine($"Document exists? {snapshot.Exists}"); if (snapshot.Exists) { Console.WriteLine($"docs: {snapshot.GetValue<string>("name")} {snapshot.GetValue<string>("lastname")} - {snapshot.GetValue<int?>("age")}"); } Console.WriteLine(); }); Console.WriteLine("Creating document"); await doc.CreateAsync(new { name = "name", lastname = "one", age = 10 }); await Task.Delay(1000); Console.WriteLine($"Updating document"); await doc.SetAsync(new { name = "name", lastname = "one point one", age = 11 }); await Task.Delay(1000); Console.WriteLine($"Deleting document"); await doc.DeleteAsync(); await Task.Delay(1000); Console.WriteLine("Creating document again"); await doc.CreateAsync(new { name = "name", lastname = "one", age = 10 }); await Task.Delay(1000); Console.WriteLine("Stopping the listener"); await listener.StopAsync(); Console.WriteLine($"Updating document (no output expected)"); await doc.SetAsync(new { name = "name", lastname = "two", age = 20 }); await Task.Delay(1000); }
private static async Task ListenDocument(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START fs_listen_document] DocumentReference docRef = db.Collection("cities").Document("SF"); FirestoreChangeListener listener = docRef.Listen(snapshot => { Console.WriteLine("Callback received document snapshot."); Console.WriteLine("Document exists? {0}", snapshot.Exists); if (snapshot.Exists) { Console.WriteLine("Document data for {0} document:", snapshot.Id); Dictionary <string, object> city = snapshot.ToDictionary(); foreach (KeyValuePair <string, object> pair in city) { Console.WriteLine("{0}: {1}", pair.Key, pair.Value); } } }); // [END fs_listen_document] // Create a new document at cities/SF to demonstrate realtime listener Console.WriteLine("Creating document"); Dictionary <string, object> cityObject = new Dictionary <string, object> { { "Name", "San Francisco" }, { "State", "CA" }, { "Country", "USA" }, { "Capital", false }, { "Population", 860000 } }; await docRef.CreateAsync(cityObject); await Task.Delay(1000); // Stop the listener when you no longer want to receive updates. Console.WriteLine("Stopping the listener"); // [START fs_detach_listener] await listener.StopAsync(); // [END fs_detach_listener] }
private static async Task ListenMultiple(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START fs_listen_multiple] CollectionReference citiesRef = db.Collection("cities"); Query query = db.Collection("cities").WhereEqualTo("State", "CA"); FirestoreChangeListener listener = query.Listen(snapshot => { Console.WriteLine("Callback received query snapshot."); Console.WriteLine("Current cities in California:"); foreach (DocumentSnapshot documentSnapshot in snapshot.Documents) { Console.WriteLine(documentSnapshot.Id); } }); // [END fs_listen_multiple] // Create a new document at cities/LA to demonstrate realtime listener Console.WriteLine("Creating document"); DocumentReference docRef = db.Collection("cities").Document("LA"); Dictionary <string, object> cityObject = new Dictionary <string, object> { { "Name", "Los Angeles" }, { "State", "CA" }, { "Country", "USA" }, { "Capital", false }, { "Population", 3900000 } }; await docRef.CreateAsync(cityObject); await Task.Delay(1000); // Stop the listener when you no longer want to receive updates. Console.WriteLine("Stopping the listener"); await listener.StopAsync(); }
/** CREATE **/ /** Saves product to database and get generated id */ public async Task <Product> Create(Product product) { // Get Collection reference DocumentReference addedDocRef = firestoreDb.Collection(DB_PRODUCT_COLLECTION).Document(); product.PictureUrl = SaveImageWithDownloadUlr(product.Picture, addedDocRef.Id).Result; product.Picture = ""; // Set up data product in database Dictionary <string, object> productDictionary = new Dictionary <string, object> { { "Title", product.Title }, { "Description", product.Description }, { "Brand", product.Brand }, { "Type", product.Type }, { "Price", product.Price }, { "PictureUrl", product.PictureUrl }, { "Amount", product.Amount }, }; try { // Try to add product WriteResult addedProductRef = await addedDocRef.CreateAsync(productDictionary); // Set id to product product.Id = addedDocRef.Id; } catch (Exception e) { // NO-OP } // Return product with id return(product); }
private async Task InitializeAsync(ulong id, CollectionReference playerCollection) { PlayerCollection = playerCollection; PlayerDoc = PlayerCollection.Document(id.ToString()); var playerDocSnap = await PlayerDoc.GetSnapshotAsync(); if (!playerDocSnap.Exists) { await PlayerDoc.CreateAsync(new Dictionary <string, object>() { { "boost", 0 }, { "demo-count", 0 }, { "death-count", 0 }, { "demo-rate", (DemoData.MinDemoChance + DemoData.MaxDemoChance) / 2 }, { "avoid-rate", (DemoData.MinAvoidChance + DemoData.MaxAvoidChance) / 2 }, { "avoid-count", 0 }, { "miss-count", 0 } }); playerDocSnap = await PlayerDoc.GetSnapshotAsync(); } if (!playerDocSnap.ContainsField("avoid-count")) { await PlayerDoc.UpdateAsync("avoid-count", 0); await PlayerDoc.UpdateAsync("miss-count", 0); } if (!playerDocSnap.TryGetValue("avoid-count", out int avoidCount)) { avoidCount = 0; } if (!playerDocSnap.TryGetValue("miss-count", out int missCount)) { missCount = 0; } if (!playerDocSnap.TryGetValue("boost-used", out int boostUsed)) { boostUsed = 0; } Data = new DemoData( playerDocSnap.GetValue <int>("boost"), playerDocSnap.GetValue <int>("demo-count"), playerDocSnap.GetValue <int>("death-count"), playerDocSnap.GetValue <double>("demo-rate"), playerDocSnap.GetValue <double>("avoid-rate"), avoidCount, missCount); RecentMessages = new List <DbMessage>(); var recentMsgSnap = await PlayerDoc.Collection("recent-messages").GetSnapshotAsync(); if (recentMsgSnap.Count > 0) { foreach (var message in recentMsgSnap) { //content, createTime if (!message.TryGetValue("content", out string content)) { content = ""; } if (!message.TryGetValue("create-time", out DateTime createTime)) { createTime = new DateTime(0); } if (!message.TryGetValue("is-successful-command", out bool isSuccessfulCommand)) { isSuccessfulCommand = false; } RecentMessages.Add(await DbMessage.CreateAsync(content, createTime, isSuccessfulCommand, id, PlayerCollection, message.Id)); } } }
private static async Task ListenForChanges(string project) { FirestoreDb db = FirestoreDb.Create(project); // [START fs_listen_for_changes] CollectionReference citiesRef = db.Collection("cities"); Query query = db.Collection("cities").WhereEqualTo("State", "CA"); FirestoreChangeListener listener = query.Listen(snapshot => { foreach (DocumentChange change in snapshot.Changes) { if (change.ChangeType.ToString() == "Added") { Console.WriteLine("New city: {0}", change.Document.Id); } else if (change.ChangeType.ToString() == "Modified") { Console.WriteLine("Modified city: {0}", change.Document.Id); } else if (change.ChangeType.ToString() == "Removed") { Console.WriteLine("Removed city: {0}", change.Document.Id); } } }); // [END fs_listen_for_changes] // Create a new document at cities/MTV to demonstrate realtime listener Console.WriteLine("Creating document"); DocumentReference docRef = db.Collection("cities").Document("MTV"); Dictionary <string, object> cityObject = new Dictionary <string, object> { { "Name", "Mountain View" }, { "State", "CA" }, { "Country", "USA" }, { "Capital", false }, { "Population", 80000 } }; await docRef.CreateAsync(cityObject); await Task.Delay(1000); // Modify the cities/MTV document to demonstrate detection of the 'Modified change Console.WriteLine("Modifying document"); Dictionary <string, object> city = new Dictionary <string, object> { { "Name", "Mountain View" }, { "State", "CA" }, { "Country", "USA" }, { "Capital", false }, { "Population", 90000 } }; await docRef.SetAsync(city); await Task.Delay(1000); // Modify the cities/MTV document to demonstrate detection of the 'Modified change Console.WriteLine("Deleting document"); await docRef.DeleteAsync(); await Task.Delay(1000); // Stop the listener when you no longer want to receive updates. Console.WriteLine("Stopping the listener"); await listener.StopAsync(); }