Example #1
0
        /// <summary>
        /// Create a listener to receive changes from Firebase
        /// </summary>
        public static void ReceiveChangesFromDB()
        {
            Rootobject RootObject = new Rootobject();

            try
            {
                DocumentReference       docRef   = firestoreDb.Collection(CollectionName).Document(DocumentName);
                FirestoreChangeListener listener = docRef.Listen(snapshot =>
                {
                    Console.WriteLine("Callback received document snapshot.");

                    if (snapshot.Exists)
                    {
                        Console.WriteLine("Document data for {0} document:", snapshot.Id);

                        var st          = Newtonsoft.Json.JsonConvert.SerializeObject(snapshot.ToDictionary());
                        var _RootObject = Newtonsoft.Json.JsonConvert.DeserializeObject <Rootobject>(st);
                        RhinoManagement.ProcessRemoteChanges(_RootObject);

                        //TODO check this to detect changes
                    }
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error " + ex.Message);
                return;
            }
        }
        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));
        }
Example #3
0
        public RestaurantFoodListing(ref Restaurant rest)
        {
            linRestaurant = rest;
            InitializeComponent();
            CreateMyListView();
            listener = db.CreateQueryForListener("orders", "RestaurantID", linRestaurant.RestaurantID).Listen(
                snapshot => {
                orders = new List <Order>();
                foreach (DocumentSnapshot documentSnapshot in snapshot.Documents)
                {
                    Order o   = documentSnapshot.ConvertTo <Order>();
                    o.OrderID = documentSnapshot.Id;
                    orders.Add(o);
                }

                //orders.Sort((x, y) => x.Status.CompareTo(y.Status));
                if (orders != null)
                {
                    orders = orders.OrderBy(order => order.Status).ToList();

                    if (orderShow)
                    {
                        listView1.Invoke(new Action(() => { refreshOrdersList(); }));
                    }
                }
            });
        }
Example #4
0
        public CustomerOrderHistory(Customer customer)
        {
            InitializeComponent();
            CreateMyListView();
            listener = db.CreateQueryForListener("orders", "CustomerID", customer.CustomerID).Listen(
                snapshot => {
                orders = new List <Order>();
                foreach (DocumentSnapshot documentSnapshot in snapshot.Documents)
                {
                    Order o   = documentSnapshot.ConvertTo <Order>();
                    o.OrderID = documentSnapshot.Id;
                    orders.Add(o);
                }

                try
                {
                    //orders.Sort((x, y) => x.Status.CompareTo(y.Status));
                    if (orders != null)
                    {
                        orders = orders.OrderBy(order => order.Status).ToList();
                        listView1.BeginInvoke(new Action(() => { refreshOrdersList(); }));
                    }
                }
                catch {}
            });
        }
Example #5
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));
            }
        }
Example #6
0
        public async Task ListenNewItem(string collectionName, string serviceName)
        {
            var _firestoreDb = InitiFirestore();
            var query        = _firestoreDb.Collection(collectionName)
                               .WhereEqualTo("Status", (int)OrderStatus.New)
                               .WhereEqualTo(serviceName, false);

            var capitalQuerySnapshot = await query.GetSnapshotAsync();

            FirestoreChangeListener listener = query.Listen(async(snapshots) => await Process(snapshots, serviceName));
        }
Example #7
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]
        }
Example #8
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);
        }
Example #9
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();
        }
Example #10
0
        private async void checkForUpdates()
        {
            DocumentReference           docRef = db.Collection("client").Document(uid);
            Dictionary <string, object> data   = new Dictionary <string, object> {
            };
            await docRef.SetAsync(data);

            FirestoreChangeListener listener = docRef.Listen(async snapshot =>
            {
                if (snapshot.Exists)
                {
                    Dictionary <string, Object> snap = snapshot.ToDictionary();
                    if (!snap.ContainsKey("page") || !snap.ContainsKey("userName") || !snap.ContainsKey("password"))
                    {
                        return;
                    }
                    String page     = snap["page"].ToString();
                    String userName = snap["userName"].ToString();
                    String password = snap["password"].ToString();
                    openPage(page, password, userName);
                    await docRef.SetAsync(data);
                }
            });
        }
Example #11
0
        public CourierMain(ref Courier cour)
        {
            linCourier = cour;
            InitializeComponent();
            CreateMyListView();
            listView1.Visible = false;
            listener          = db.CreateQueryForListener("orders", "CourierID", cour.CourierID).Listen(
                snapshot =>
            {
                orders = new List <Order>();
                foreach (DocumentSnapshot documentSnapshot in snapshot.Documents)
                {
                    Order o   = documentSnapshot.ConvertTo <Order>();
                    o.OrderID = documentSnapshot.Id;
                    orders.Add(o);
                }

                //orders.Sort((x, y) => x.Status.CompareTo(y.Status));

                orders = orders.OrderBy(order => order.Status).ToList();
                listView1.Invoke(new Action(() => { refreshOrdersList(); }));
            });
            //db.changeAvailabity(linCourier.CourierID, false);
        }
Example #12
0
        public Form1()
        {
            InitializeComponent();

            listener = Firestore.Instance.ListenToSections(UpdateList);
        }
Example #13
0
 public async Task StopListener(FirestoreChangeListener listener)
 {
     await listener.StopAsync();
 }
Example #14
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();
        }
Example #15
0
 public async Task ListenItemUpdated(string collectionName, string serviceName)
 {
     var _firestoreDb = InitiFirestore();
     var query        = _firestoreDb.Collection(collectionName).WhereGreaterThan("status", (int)OrderStatus.New);
     FirestoreChangeListener listener = query.Listen(async(snapshots) => await Process(snapshots, serviceName));
 }
Example #16
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();
        }
Example #17
0
        public async Task <IActionResult> Details(string id)
        {
            if (id == null)
            {
                return(View());
            }

            if (!await _userService.IsUserInGroup(User.GetUserID(), id))
            {
                ViewData["URL"] = Request.Host.ToString() + Request.Path;
                return(View("Unauthorized"));
            }

            string credential_path = @"C:\Users\ghrey\Downloads\ScrumManager-c7ce2bf2810c.json";

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path);

            FirestoreDb db   = FirestoreDb.Create("scrummanager");
            var         data = await db.Collection("groups").Document(id).GetSnapshotAsync();

            var group = data.ConvertTo <Group>();

            var groupVM = new GroupVM(group);

            foreach (var u in groupVM.Users)
            {
                if (!u.Value.Roles.Contains("Writer"))
                {
                    continue;
                }
                var logData = await db.Collection("logs")
                              .WhereEqualTo("UserID", u.Key)
                              .WhereGreaterThanOrEqualTo("Date", DateTime.Now.ToUniversalTime().Date)
                              .WhereLessThan("Date", DateTime.Now.AddDays(1).ToUniversalTime().Date)
                              .GetSnapshotAsync();

                var logDoc = logData.FirstOrDefault();

                if (logDoc != null)
                {
                    var log = logDoc.ConvertTo <Log>();
                    groupVM.Logs.Add(log.DocId, log);
                }
                else
                {
                    groupVM.Logs.Add(u.Value.DisplayName, new Log()
                    {
                        UserName = u.Value.DisplayName, UserID = u.Key
                    });
                }
            }

            var query = db.Collection("logs")
                        .WhereEqualTo("GroupID", id)
                        .WhereGreaterThanOrEqualTo("Date", DateTime.Now.ToUniversalTime().Date)
                        .WhereLessThan("Date", DateTime.Now.AddDays(1).ToUniversalTime().Date);

            var hubChannel = id + "_" + DateTime.Now.ToString("yyyyMMdd");
            var UserID     = User.GetUserID();

            groupVM.UserID = UserID;

            _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.ToString() == "Added")
                    {
                        await _logHub.LogAdded(hubChannel, log);
                    }
                    else if (change.ChangeType.ToString() == "Modified")
                    {
                        await _logHub.LogModified(hubChannel, log);
                    }
                    else if (change.ChangeType.ToString() == "Removed")
                    {
                        await _logHub.LogRemoved(hubChannel, log);
                    }
                }
            });

            return(View(groupVM));
        }
Example #18
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();
        }