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));
        }
示例#2
0
        public async Task <IActionResult> ChangeListener(string groupToJoin)
        {
            try
            {
                if (_listener != null)
                {
                    await _listener.StopAsync();
                }
                var provider = new DateTimeFormatInfo();
                provider.LongDatePattern = "yyyyMMdd";
                var         date    = DateTime.ParseExact(groupToJoin.Split('_')[1], "yyyyMMdd", null, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
                var         groupID = groupToJoin.Split('_')[0];
                FirestoreDb db      = FirestoreDb.Create("scrummanager");

                var query = db.Collection("logs")
                            .WhereEqualTo("GroupID", groupID)
                            .WhereGreaterThanOrEqualTo("Date", date.Date)
                            .WhereLessThan("Date", date.AddDays(1).Date);
                var UserID = User.GetUserID();

                _listener = query.Listen(async snapshot =>
                {
                    foreach (DocumentChange change in snapshot.Changes)
                    {
                        var log = change.Document.ConvertTo <Log>();
                        if (log.UserID == UserID)
                        {
                            continue;
                        }

                        if (change.ChangeType == DocumentChange.Type.Added)
                        {
                            await _logHub.LogAdded(groupToJoin, log);
                        }
                        else if (change.ChangeType == DocumentChange.Type.Modified)
                        {
                            await _logHub.LogModified(groupToJoin, log);
                        }
                        else if (change.ChangeType == DocumentChange.Type.Removed)
                        {
                            await _logHub.LogRemoved(groupToJoin, log);
                        }
                    }
                });

                var qs = await query.GetSnapshotAsync();

                return(Json(qs.Documents.Select(x => x.ConvertTo <Log>())));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                return(StatusCode(500));
            }
        }
示例#3
0
        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);
        }
示例#4
0
        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]
        }
示例#5
0
        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();
        }
示例#6
0
文件: Firestore.cs 项目: HHIED/CAD
 public async Task StopListener(FirestoreChangeListener listener)
 {
     await listener.StopAsync();
 }
示例#7
0
        public async Task Listening2()
        {
            CollectionReference collection = db.Collection("testecsharp");
            Query query = collection.WhereGreaterThan("age", 5).OrderByDescending("age");

            FirestoreChangeListener listener = collection.Listen(snapshot =>
            {
                Console.WriteLine($"Callback received query snapshot");
                Console.WriteLine($"Count: {snapshot.Count}");
                Console.WriteLine("Changes:");
                string name = ""; int age = 0;
                foreach (DocumentChange change in snapshot.Changes)
                {
                    DocumentSnapshot document = change.Document;
                    Console.WriteLine($"{document.Reference.Id}: ChangeType={change.ChangeType}; OldIndex={change.OldIndex}; NewIndex={change.NewIndex})");
                    if (document.Exists)
                    {
                        if (document.ContainsField("name"))
                        {
                            name = document.GetValue <string>("name");
                        }
                        if (document.ContainsField("age"))
                        {
                            age = document.GetValue <int>("age");
                        }
                        Console.WriteLine($"  Document data: Name={name}; age={age}");
                    }
                }
                Console.WriteLine();
            });

            Console.WriteLine("Creating document for Sophie (age = 7)");
            DocumentReference doc1Ref = await collection.AddAsync(new { name = "Sophie", age = 7 });

            Console.WriteLine($"Sophie document ID: {doc1Ref.Id}");
            await Task.Delay(1000);

            Console.WriteLine("Creating document for James (age = 10)");
            DocumentReference doc2Ref = await collection.AddAsync(new { name = "James", age = 10 });

            Console.WriteLine($"James document ID: {doc2Ref.Id}");
            await Task.Delay(1000);

            Console.WriteLine("Modifying document for Sophie (set age = 11, higher than age for James)");
            await doc1Ref.UpdateAsync("age", 11);

            await Task.Delay(1000);

            Console.WriteLine("Modifying document for Sophie (set age = 12, no change in position)");
            await doc1Ref.UpdateAsync("age", 12);

            await Task.Delay(1000);

            Console.WriteLine("Modifying document for James (set age = 4, below threshold for query)");
            await doc2Ref.UpdateAsync("age", 4);

            await Task.Delay(1000);

            Console.WriteLine("Deleting document for Sophie");
            await doc1Ref.DeleteAsync();

            await Task.Delay(1000);

            Console.WriteLine("Stopping listener");
            await listener.StopAsync();
        }
示例#8
0
        // code borrowed from https://cloud.google.com/firestore/docs/quickstart-servers#cloud-console
        public static async Task Main(string[] args)
        {
            var projectName  = "blazor-sample";
            var authFilePath = "PATH/TO/blazor-sample-auth.json";

            // environment variable could be configured differently, but for the sample simply hardcode it
            // the Firestore library expects this environment variable to be set
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", authFilePath);
            FirestoreDb firestoreDb = FirestoreDb.Create(projectName);

            // this section creates two document in the users-collection, alovelace and aturing
            CollectionReference         usersCollection = firestoreDb.Collection("users");
            DocumentReference           docRef          = usersCollection.Document("alovelace");
            Dictionary <string, object> user            = new Dictionary <string, object>
            {
                { "First", "Ada" },
                { "Last", "Lovelace" },
                { "Born", 1815 }
            };
            await docRef.SetAsync(user);

            docRef = usersCollection.Document("aturing");
            user   = new Dictionary <string, object>
            {
                { "First", "Alan" },
                { "Middle", "Mathison" },
                { "Last", "Turing" },
                { "Born", 1912 }
            };
            await docRef.SetAsync(user);

            // this section will fetch all users from the users-collection and print them to the console
            QuerySnapshot snapshot = await usersCollection.GetSnapshotAsync();

            foreach (DocumentSnapshot document in snapshot.Documents)
            {
                Console.WriteLine("User: {0}", document.Id);
                Dictionary <string, object> documentDictionary = document.ToDictionary();
                Console.WriteLine("First: {0}", documentDictionary["First"]);
                if (documentDictionary.ContainsKey("Middle"))
                {
                    Console.WriteLine("Middle: {0}", documentDictionary["Middle"]);
                }
                Console.WriteLine("Last: {0}", documentDictionary["Last"]);
                Console.WriteLine("Born: {0}", documentDictionary["Born"]);
                Console.WriteLine();
            }

            // all users will be fetched and send to the lambda callback, when users-collection is modified the changes will be send here in real-time
            // not only the change will be send when collection is modified, the entire collection will be returne
            FirestoreChangeListener firestoreChangeListener = usersCollection
                                                              .Listen((snapshot) =>
            {
                foreach (DocumentSnapshot document in snapshot.Documents)
                {
                    Console.WriteLine("User: {0}", document.Id);
                    Dictionary <string, object> documentDictionary = document.ToDictionary();
                    Console.WriteLine("First: {0}", documentDictionary["First"]);
                    Console.WriteLine("Last: {0}", documentDictionary["Last"]);
                    Console.WriteLine();
                }
            });

            // give some time for the 'Listen' function to be invoked
            await Task.Delay(2000);

            Console.WriteLine("Enter first name:");
            var firstName = Console.ReadLine();

            Console.WriteLine("Enter last name:");
            var lastName = Console.ReadLine();

            Console.WriteLine();

            user = new Dictionary <string, object>
            {
                { "First", firstName },
                { "Last", lastName }
            };
            await usersCollection.AddAsync(user);

            // give some time for the 'Listen' function to be invoked
            await Task.Delay(2000);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
            await firestoreChangeListener.StopAsync();
        }
示例#9
0
 private async void detachListener()
 {
     await listener.StopAsync();
 }
示例#10
0
        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();
        }