Ejemplo n.º 1
0
        public async Task <BlogPost> GetBlogPostById(string blogPostId)
        {
            var reference        = _blogPostsCollection.Document(blogPostId);
            var documentSnapshot = await reference.GetSnapshotAsync();

            return(documentSnapshot?.ConvertTo <BlogPost>());
        }
Ejemplo n.º 2
0
        public async Task SaveAsync(MessageInfo info, CancellationToken cancellationToken)
        {
            var messageRef      = _messagesCollection.Document(info.ChatId).Collection(info.Date).Document(info.UserId);
            var messageSnapshot = await messageRef.GetSnapshotAsync(cancellationToken);

            if (!messageSnapshot.Exists)
            {
                await _usersCollection.Document(info.UserId)
                .SetAsync(
                    new
                {
                    info.FirstName,
                    info.LastName,
                    info.UserName
                },
                    null,
                    cancellationToken);

                var update = new Dictionary <string, object> {
                    { info.MessageType, 1 }
                };
                await messageRef.SetAsync(update, null, cancellationToken);
            }
            else
            {
                await messageRef.UpdateAsync(info.MessageType, FieldValue.Increment(1), Precondition.None,
                                             cancellationToken);
            }
        }
        public async Task <Project> GetProjectById(string projectId)
        {
            var reference        = _projectCollection.Document(projectId);
            var documentSnapshot = await reference.GetSnapshotAsync();

            return(documentSnapshot?.ConvertTo <Project>());
        }
Ejemplo n.º 4
0
        public async Task <string> AddAsync <T>(T entity)
        {
            var document = _collection.Document();

            await document.SetAsync(entity);

            return(document.Id);
        }
Ejemplo n.º 5
0
        public async Task InsertAsync(Feed feed)
        {
            if (feed == null)
            {
                return;
            }

            var docRef = _feeds.Document(feed.Id.ToString());
            await docRef.SetAsync(feed, SetOptions.Overwrite);
        }
 public Task <Configuration> GetConfiguration()
 {
     return(configurations
            .Document("factory")
            .GetSnapshotAsync()
            .ContinueWith(result => {
         var data = result.Result;
         return configurationConverter.ToModel(data.Id, data.ToDictionary());
     }));
 }
Ejemplo n.º 7
0
        private static async Task RetrieveCreateExamples(string project)
        {
            FirestoreDb db = FirestoreDb.Create(project);
            // [START fs_retrieve_create_examples]
            CollectionReference citiesRef = db.Collection("cities");
            await citiesRef.Document("SF").SetAsync(new Dictionary <string, object>()
            {
                { "Name", "San Francisco" },
                { "State", "CA" },
                { "Country", "USA" },
                { "Capital", false },
                { "Population", 860000 }
            });

            await citiesRef.Document("LA").SetAsync(new Dictionary <string, object>()
            {
                { "Name", "Los Angeles" },
                { "State", "CA" },
                { "Country", "USA" },
                { "Capital", false },
                { "Population", 3900000 }
            });

            await citiesRef.Document("DC").SetAsync(new Dictionary <string, object>()
            {
                { "Name", "Washington D.C." },
                { "State", null },
                { "Country", "USA" },
                { "Capital", true },
                { "Population", 680000 }
            });

            await citiesRef.Document("TOK").SetAsync(new Dictionary <string, object>()
            {
                { "Name", "Tokyo" },
                { "State", null },
                { "Country", "Japan" },
                { "Capital", true },
                { "Population", 9000000 }
            });

            await citiesRef.Document("BJ").SetAsync(new Dictionary <string, object>()
            {
                { "Name", "Beijing" },
                { "State", null },
                { "Country", "China" },
                { "Capital", true },
                { "Population", 21500000 }
            });

            Console.WriteLine("Added example cities data to the cities collection.");
            // [END fs_retrieve_create_examples]
        }
        public static async Task <Solicitud> GetSolicitudFromFireStore(string _ID)
        {
            Solicitud solicitud = new Solicitud();

            try {
                FirestoreDb         db         = conexionDB();
                CollectionReference collection = db.Collection("Solicitudes");
                DocumentReference   docRef     = collection.Document(_ID);
                DocumentSnapshot    document   = await docRef.GetSnapshotAsync();

                if (!document.Exists)
                {
                    collection = db.Collection("Renovaciones");
                    docRef     = collection.Document(_ID);
                    document   = await docRef.GetSnapshotAsync();
                }
                if (document.Exists)
                {
                    solicitud             = document.ConvertTo <Solicitud>();
                    solicitud.solicitudID = _ID;

                    List <Documento> documentosAux = new List <Documento>();
                    foreach (Documento doc in solicitud.documentos)
                    {
                        var aux_doc = documentosAux.Find(x => x.tipo == doc.tipo);
                        if (aux_doc == null)
                        {
                            documentosAux.Add(doc);
                        }
                        else
                        {
                            if (aux_doc.version < doc.version)
                            {
                                documentosAux.Remove(aux_doc);
                                documentosAux.Add(doc);
                            }
                        }
                    }
                    solicitud.documentos = documentosAux;
                }
                else
                {
                    solicitud.grupoNombre = "La solicitud con el id " + _ID + " no existe en la FSDB.\r\nVuelva a cargar la página desde la bandeja, si no se muestra información de la solicitud vuelva a cargar los datos de la bandeja";//Auxiliar para mostrar un mensaje de error
                }
            } catch (Exception ex) {
                solicitud.grupoNombre = ex.Message;//Auxiliar para mostrar un mensaje de error
                Log.Information("*****Error Exception GetSolicitudFromFireStore: {0}", ex.Message);
            }
            return(solicitud);
        }
Ejemplo n.º 9
0
 private static void CheckScores()
 {
     if (FirebaseAuthManager.Instance.User is null)
     {
         SceneManager.LoadScene("Scenes/Scoreboard");
     }
     else
     {
         Debug.Log("Starting check...");
         CollectionReference remoteLeaderboard = FirebaseFirestore.DefaultInstance.Collection(
             $"leaderboards/{CrossSceneLevelContainer.Instance.level.id}/leaders");
         if (remoteLeaderboard is null)
         {
             Debug.Log("Leaderboard is null!");
             GoToScoreQuery();
         }
         else
         {
             Debug.Log("Leaderboard is not null! Proceeding...");
             remoteLeaderboard.Document(FirebaseAuthManager.Instance.User.UserId).GetSnapshotAsync()
             .ContinueWithOnMainThread(
                 LeaderboardCallback);
         }
     }
 }
Ejemplo n.º 10
0
        public async Task <IActionResult> Producten(string documentId)
        {
            db = FirestoreDatabase.LoadDatabase();

            CollectionReference klantenColl  = db.Collection("Klanten");
            DocumentReference   document     = klantenColl.Document(documentId);
            DocumentSnapshot    klantMetNaam = await document.GetSnapshotAsync();

            DocumentKlant documentKlant = new DocumentKlant
            {
                DocumentId = document.Id,
                Klant      = klantMetNaam.ConvertTo <Klant>()
            };

            Query query = klantenColl.WhereEqualTo("Naam", documentKlant.Klant.Naam);

            FirestoreChangeListener listener = query.Listen(snapshot =>
            {
                foreach (DocumentChange change in snapshot.Changes)
                {
                    DocumentSnapshot documentSnapshot = change.Document;

                    if (documentSnapshot.Exists)
                    {
                        documentKlant.DocumentId = document.Id;
                        documentKlant.Klant      = documentSnapshot.ConvertTo <Klant>();
                    }
                }
            });

            await listener.StopAsync();

            return(View(documentKlant));
        }
Ejemplo n.º 11
0
        public static async Task <bool> Insert8ballFor(ulong guildID, string btype, string msg)
        {
            try
            {
                CollectionReference ballCollection = Db.Document(Convert.ToString(guildID)).Collection("8ball");

                DocumentReference messages         = ballCollection.Document("messages");
                DocumentSnapshot  messagesSnapshot = await messages.GetSnapshotAsync();

                if (messagesSnapshot.TryGetValue(btype, out List <string> got))
                {
                    got.Add(msg);
                }
                else
                {
                    got = new List <string>()
                    {
                        msg
                    }
                };
                Dictionary <string, List <string> > update = new Dictionary <string, List <string> > {
                    [btype] = got
                };
                WriteResult wrire = await messages.SetAsync(update, SetOptions.MergeAll);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 12
0
        public async Task <bool> Create(Dictionary <string, object> dictionary)
        {
            DocumentReference docRef = collection.Document();
            await docRef.SetAsync(dictionary);

            return(true);
        }
        //public static async Task<List<Solicitud>> GetGrupoFromFireStore(string grupoID){
        public static async Task <GrupoDetalle> GetGrupoFromFireStore(string grupoID)
        {
            GrupoDetalle     grupoDetalle = new GrupoDetalle();
            List <Solicitud> solicitudes  = new List <Solicitud>();

            try{
                FirestoreDb db = conexionDB();

                CollectionReference collection  = db.Collection("Grupos");
                DocumentReference   docRef      = collection.Document(grupoID);
                DocumentSnapshot    documentGpo = await docRef.GetSnapshotAsync();

                if (documentGpo.Exists)
                {
                    grupoDetalle.grupo = documentGpo.ConvertTo <Grupo>();
                }

                Query         capitalQuery         = db.Collection("Solicitudes").WhereEqualTo("grupoID", grupoID);
                QuerySnapshot capitalQuerySnapshot = await capitalQuery.GetSnapshotAsync();

                foreach (DocumentSnapshot document in capitalQuerySnapshot.Documents)
                {
                    Solicitud solicitud = document.ConvertTo <Solicitud>();
                    solicitud.solicitudID = document.Id;
                    solicitudes.Add(solicitud);
                }
            }
            catch (Exception ex) {
                Log.Information("*****Error Exception GetGrupoFromFireStore: {0}", ex.Message);
            }
            grupoDetalle.solicitudes = solicitudes;
            return(grupoDetalle);
        }
Ejemplo n.º 14
0
        public static async Task <List <ulong> > GetChannelmodsFor(ulong guildID, ISocketMessageChannel channel)
        {
            CollectionReference channelCollection = Db.Document(Convert.ToString(guildID)).Collection("channels");

            DocumentReference channelDoc = channelCollection.Document(Convert.ToString(channel.Id));
            DocumentSnapshot  channelSettingsSnapshot = await channelDoc.GetSnapshotAsync();

            if (channelSettingsSnapshot.Exists)
            {
                Dictionary <string, object> dict = channelSettingsSnapshot.ToDictionary();

                if (dict.ContainsKey("mods"))
                {
                    List <object> mods = dict["mods"] as List <object>;

                    List <ulong> casted = new List <ulong>();
                    foreach (object id in mods)
                    {
                        casted.Add(Convert.ToUInt64(id));
                    }

                    return(casted);
                }
            }

            return(new List <ulong>());
        }
Ejemplo n.º 15
0
        /** READ **/

        /** Executes query to find products and extracts data from query **/
        public async Task <IEnumerable <Product> > GetProductsAsync(Filter filter)
        {
            List <Product> products = new List <Product>();

            // Get products collection reference
            CollectionReference productCollectionRef = firestoreDb.Collection(DB_PRODUCT_COLLECTION);

            // Get document snapshot that is last product of the page
            DocumentReference lastProductPageRef  = productCollectionRef.Document(filter.LastItemId);
            DocumentSnapshot  lastProductSnapshot = await lastProductPageRef.GetSnapshotAsync();

            // Query products, sort based on the value in filter and
            Query query = productCollectionRef
                          .OrderBy(filter.OrderBy)
                          // get all documents after last product, limit for pagination
                          .StartAfter(lastProductSnapshot)
                          .Limit(10);

            // Execute query
            QuerySnapshot paginatedProducts = await query.GetSnapshotAsync();

            foreach (DocumentSnapshot documentSnapshot in paginatedProducts.Documents)
            {
                // Try to extract data from documents to product
                Product product = ExtractProductFromSnapshot(documentSnapshot);
                products.Add(product);
            }

            // Return paginated products
            return(products);
        }
Ejemplo n.º 16
0
        public async Task AddQuoteAsync(string type, string context, [Remainder] string content)
        {
            if (!Enum.TryParse(context, true, out Quote.Context quoteContext))
            {
                quoteContext = Quote.Context.Other;
            }

            // determine which collection to use
            type = type.ToLower();

            CollectionReference quotes =
                type == "salt" ? _salt :
                type == "sugar" ? _sugar :
                null;

            int id = await FindLowestAvailableIdAsync(quotes);

            // add the quote/context/id
            Dictionary <string, object> newQuote = new Dictionary <string, object>()
            {
                { "content", content },
                { "context", quoteContext },
                { "id", id }
            };

            await quotes.Document().SetAsync(newQuote);

            Enum.TryParse(context, true, out Quote.Context embedContext);

            await ReplyAsync("Quote added!");
            await DisplayQuoteAsync(quotes, id);
        }
Ejemplo n.º 17
0
        public async Task Channelmod(
            [Summary("The user to cmod")][Remainder] SocketGuildUser user)
        {
            CollectionReference channelCollection = GranularPermissionsStorage.Db.Document(Convert.ToString(this.Context.Guild.Id)).Collection("channels");
            DocumentReference   channelDoc        = channelCollection.Document(Convert.ToString(this.Context.Channel.Id));

            Dictionary <string, object> update = new Dictionary <string, object>();

            List <ulong> mods = await GranularPermissionsStorage.GetChannelmodsFor(this.Context.Guild.Id, this.Context.Channel);

            if (!mods.Contains(user.Id))
            {
                mods.Add(user.Id);
                update["mods"] = mods;

                await channelDoc.SetAsync(update, SetOptions.MergeAll);

                if (this.Context.Channel is SocketGuildChannel sgc)
                {
                    await sgc.AddPermissionOverwriteAsync(user,
                                                          new OverwritePermissions(readMessages : PermValue.Allow, sendMessages : PermValue.Allow, manageMessages : PermValue.Allow));
                }
                await this.Context.Message.AddReactionAsync(new Emoji("👌"));
            }
            else
            {
                mods.RemoveAll(x => x == user.Id);
                update["mods"] = mods;

                await channelDoc.SetAsync(update, SetOptions.MergeAll);

                await this.Context.Channel.SendMessageAsync("Removed a channelmod. (Their Discord permissions were not changed.)");
            }
        }
        public static async Task <Renovacion> GetRenovacionFromFireStore(string _ID)
        {
            Renovacion solicitud = new Renovacion();

            try
            {
                FirestoreDb         db         = conexionDB();
                CollectionReference collection = db.Collection("Renovaciones");
                DocumentReference   docRef     = collection.Document(_ID);
                DocumentSnapshot    document   = await docRef.GetSnapshotAsync();

                if (document.Exists)
                {
                    solicitud             = document.ConvertTo <Renovacion>();
                    solicitud.solicitudID = _ID;
                }
                else
                {
                    solicitud.grupoNombre = "La solicitud con el id " + _ID + " no existe en la FSDB.\r\nVuelva a cargar la página desde la bandeja, si no se muestra información de la solicitud vuelva a cargar los datos de la bandeja";
                }
            }
            catch (Exception ex)
            {
                solicitud.grupoNombre = ex.Message;//Auxiliar para mostrar un mensaje de error
                Log.Information("*****Error Exception GetRenovacionFromFireStore: {0}", ex.Message);
            }
            return(solicitud);
        }
Ejemplo n.º 19
0
    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 Task <ResponseObject> VehiclesLookupAsync(VehicleJsonResponseModel vehiclesData)
        {
            var vehicles = new List <Vehicle>();

            foreach (var item in vehiclesData.Items.Take(10))
            {
                var newVehicleUuid = item.Uuid;
                var document       = await collection.Document(newVehicleUuid).GetSnapshotAsync();

                if (document.Exists)
                {
                    vehicles.Add(document.ConvertTo <Vehicle>());
                }
                else
                {
                    string bulletinUri       = $"https://www.tinglysning.dk/tinglysning/unsecrest/bil/uuid/{newVehicleUuid}";
                    string newVehicleDataXml = HttpWebHandler.DoSSLGet(bulletinUri);

                    var newVehicleData = XmlSerializerHelper <BilSummariskHentResultat> .Deserialaize(newVehicleDataXml);

                    if (newVehicleData != null)
                    {
                        var newVehicle = new Vehicle()
                        {
                            Uuid                    = newVehicleUuid,
                            ChassisNumber           = newVehicleData.BilSummarisk?.BilStamoplysninger?.BilIdentifikator?.Stelnummer,
                            CarManufacturer         = newVehicleData.BilSummarisk?.BilStamoplysninger?.BilStruktur?.BilMaerke?.BilFabrikatTekst,
                            CarModel                = newVehicleData.BilSummarisk?.BilStamoplysninger?.BilStruktur?.BilMaerke?.BilModelTekst,
                            Variant                 = newVehicleData.BilSummarisk?.BilStamoplysninger?.BilStruktur?.BilMaerke?.BilVariantTekst,
                            RegistrationNumber      = newVehicleData.BilSummarisk?.BilStamoplysninger?.BilStruktur?.RegistreringsnummerTekst,
                            FirstRegistrationYear   = newVehicleData.BilSummarisk?.BilStamoplysninger?.BilStruktur?.FoersteRegistreringsAar,
                            ModelId                 = newVehicleData.BilSummarisk?.ModelId,
                            TranscriptDateAndTime   = newVehicleData.UdskriftDatoTid,
                            ReviewReceivedIndicator = newVehicleData.AnmeldelseModtagetIndikator
                        };
                        await collection.Document(newVehicleUuid).SetAsync(newVehicle);

                        vehicles.Add(newVehicle);
                    }
                }
            }
            return(new ResponseObject()
            {
                ResponseStatus = vehicles.Count > 0 ? ResponseStatus.OK : ResponseStatus.NOT_FOUND,
                Content = JsonConvert.SerializeObject(vehicles)
            });
        }
Ejemplo n.º 21
0
        public async Task <Tag> CreateOrFindByTagId(string tagId)
        {
            var tagRef   = _tagsCollection.Document(tagId);
            var snapshot = await tagRef.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                return(snapshot.ConvertTo <Tag>());
            }

            var newTag = new Tag {
                TagId = tagId
            };
            await tagRef.SetAsync(newTag);

            return(newTag);
        }
Ejemplo n.º 22
0
        private async void FirebaseSave()
        {
            //MessageBox.Show(db.ToString());
            // Create a document with a ramdom ID in the "Product" collection
            // A DocumentReference doen't contain the data -it's just a path
            // let fetch the current document
            //DocumentSnapshot snapshot = await document.GetSnapshotAsync();
            //txtName.Text = snapshot.GetValue<string>("Name");
            //txtDetail.Text = snapshot.GetValue<string>("Detail");
            //txtPath.Text = snapshot.GetValue<string>("PathImage");
            //pictureBox1.ImageLocation = txtPath.Text;

            /*
             * new
             *      {
             *              Name = txtName.Text.ToUpper().Trim(),
             *              Detail = txtDetail.Text.Trim(),
             *              PathImage = txtPath.Text.Trim(),
             *              Image = FSBHelper.ConvertImageToBase64(ImageBox.Image)
             *      }
             *
             *      ProductRecord p = new ProductRecord
             *      {
             *              Id = _document,
             *              Name = txtName.Text.Trim(),
             *              Detail = txtDetail.Text.Trim(),
             *              PathImage = txtPath.Text.Trim(),
             *              Image = FSBHelper.ConvertImageToBase64(ImageBox.Image)
             *      };
             */

            // test upload file
            //UploadImageToFireStore();


            CollectionReference collectionReference = db.Collection("Product");

            if (_mode == ActionMode.Add)
            {
                DocumentReference document = await collectionReference.AddAsync(p);
            }
            else if (_mode == ActionMode.Edit)
            {
                Dictionary <FieldPath, object> updates = new Dictionary <FieldPath, object>
                {
                    { new FieldPath("Name"), p.Name },
                    { new FieldPath("Detail"), p.Detail },
                    { new FieldPath("PathImage"), p.PathImage },
                    { new FieldPath("Image"), p.Image }
                };

                await collectionReference.Document(_document).UpdateAsync(updates);

                //DocumentReference docRef =
                //db.Collection("Product").Document(_document);
                //await docRef.SetAsync(p);
            }
        }
Ejemplo n.º 23
0
        public async Task <IActionResult> Factuur(string documentId)
        {
            db = FirestoreDatabase.LoadDatabase();

            CollectionReference klantenColl  = db.Collection("Klanten");
            DocumentReference   document     = klantenColl.Document(documentId);
            DocumentSnapshot    klantMetNaam = await document.GetSnapshotAsync();

            return(View());
        }
Ejemplo n.º 24
0
        private async Task PopulateCollection(CollectionReference collection, IEnumerable <object> documents)
        {
            var batch = FirestoreDb.StartBatch();

            foreach (var doc in documents)
            {
                batch.Create(collection.Document(), doc);
            }
            await batch.CommitAsync();
        }
        public async Task <ActionResult> AddFaculty([Bind(Include = "Id,Name,Email,ContactNumber,Class,Dob")] Faculty fa)
        {
            string institute = Session["user"].ToString();

            if (Session["user"] == null)
            {
                return(RedirectToAction("../Login/Index"));
            }
            else
            {
                string date = "";
                fa.Dob   = fa.Dob.ToString();
                date     = date + fa.Dob[8] + fa.Dob[9] + "/" + fa.Dob[5] + fa.Dob[6] + "/" + fa.Dob[0] + fa.Dob[1] + fa.Dob[2] + fa.Dob[3];
                fa.Dob   = date;
                fa.Icard = "No";
                CollectionReference cr = firestoreDb.Collection("Institute").Document(institute).Collection("Faculty");
                try
                {
                    cr.Document(fa.Id.ToString());
                    await cr.Document(fa.Id.ToString()).SetAsync(fa);

                    SmtpClient client = new SmtpClient
                    {
                        Host                  = "smtp.gmail.com",
                        Port                  = 587,
                        EnableSsl             = true,
                        DeliveryMethod        = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials           = new NetworkCredential("*****@*****.**", "qrcode123")
                    };
                    MailMessage mailMessage = new MailMessage("*****@*****.**", fa.Email);
                    mailMessage.Subject = "Attendance Managment";
                    mailMessage.Body    = "This Mail From Attendance Managment.\nYour Account is Added\n Your id : " + fa.Id + "\nYour Password : "******"{0}", e.Source);
                    throw new Exception(e.Source);
                }
                return(RedirectToAction("../Faculty/Index"));
            }
        }
    //Write data to cloud firestore
    //REMEMBER TO ALLOW WRITE TO CLOUD FIRESTORE FOR IT TO WORK;
    void Write()
    {
        CollectionReference colRef = db.Collection("YourCollectionName");

        colRef.Document("WriteData").SetAsync(new Dictionary <string, object>()
        {
            //Write in Data
            { "Document_Field_Name", "Data" },
            { "Name", "Derived" }
        });
    }
Ejemplo n.º 27
0
        static async Task CreateDocuments(CollectionReference collection, List <Mentor> mentors)
        {
            var batch = collection.Database.StartBatch();

            foreach (var mentor in mentors)
            {
                batch.Create(collection.Document(), mentor);
            }
            var results = await batch.CommitAsync();

            Console.WriteLine($"Created {results.Count} documents");
        }
Ejemplo n.º 28
0
        public async Task CreateAsync(Customer customer)
        {
            DocumentReference           document     = _collection.Document(customer.Id);
            Dictionary <string, object> customerData = new Dictionary <string, object>()
            {
                { nameof(customer.Name), customer.Name },
                { nameof(customer.State), customer.State },
                { nameof(customer.Cpf), customer.Cpf }
            };

            await document.SetAsync(customerData);
        }
        /// <summary>
        /// Async method that remove a member based on id from the database.
        /// </summary>
        /// <param name="personalId">The social security number of the member to be removed.</param>
        public async Task RemoveMemberById(int id)
        {
            CollectionReference colRef  = _db.Collection("members");
            Query         query         = colRef.WhereEqualTo("MemberId", id);
            QuerySnapshot querySnapshot = await query.GetSnapshotAsync();

            foreach (DocumentSnapshot documentSnapshot in querySnapshot.Documents)
            {
                DocumentReference docRef = colRef.Document(documentSnapshot.Id);
                await docRef.DeleteAsync();
            }
        }
Ejemplo n.º 30
0
        private static async Task CollectionGroupQuery(string project)
        {
            FirestoreDb         db        = FirestoreDb.Create(project);
            CollectionReference citiesRef = db.Collection("cities");
            // [START fs_collection_group_query_data_setup]
            await citiesRef.Document("SF").Collection("landmarks").Document()
            .CreateAsync(new { Name = "Golden Gate Bridge", Type = "bridge" });

            await citiesRef.Document("SF").Collection("landmarks").Document()
            .CreateAsync(new { Name = "Legion of Honor", Type = "museum" });

            await citiesRef.Document("LA").Collection("landmarks").Document()
            .CreateAsync(new { Name = "Griffith Park", Type = "park" });

            await citiesRef.Document("DC").Collection("landmarks").Document()
            .CreateAsync(new { Name = "Lincoln Memorial", Type = "memorial" });

            await citiesRef.Document("DC").Collection("landmarks").Document()
            .CreateAsync(new { Name = "National Air And Space Museum", Type = "museum" });

            await citiesRef.Document("TOK").Collection("landmarks").Document()
            .CreateAsync(new { Name = "Ueno Park", Type = "park" });

            await citiesRef.Document("TOK").Collection("landmarks").Document()
            .CreateAsync(new { Name = "National Museum of Nature and Science", Type = "museum" });

            await citiesRef.Document("BJ").Collection("landmarks").Document()
            .CreateAsync(new { Name = "Jingshan Park", Type = "park" });

            await citiesRef.Document("BJ").Collection("landmarks").Document()
            .CreateAsync(new { Name = "Beijing Ancient Observatory", Type = "museum" });

            // [END fs_collection_group_query_data_setup]

            // [START fs_collection_group_query]
            Query         museums       = db.CollectionGroup("landmarks").WhereEqualTo("Type", "museum");
            QuerySnapshot querySnapshot = await museums.GetSnapshotAsync();

            foreach (DocumentSnapshot document in querySnapshot.Documents)
            {
                Console.WriteLine($"{document.Reference.Path}: {document.GetValue<string>("Name")}");
            }
            // [END fs_collection_group_query]
        }