FirestoreChangeListener

We found 10 examples in language CSharp for this search. You will see 29 fragments of code.

Other methods


        internal static FirestoreChangeListener Start(WatchStream stream)
        {
            var task = stream.StartAsync();
            return new FirestoreChangeListener(stream, task);
        }


        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));
        }


        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));
        }

        public async Task<string> AddAsync(T entity)
        {
            Dictionary<string, object> entityDic = new Dictionary<string, object>();
            foreach (var property in entity.GetType().GetProperties())
            {
                entityDic.Add(property.Name, property.GetValue(entity));
            }
            var refrance = await _collection.AddAsync(entityDic);
            entityDic.Clear();
            entityDic.Add("Id", refrance.Id);
            await refrance.UpdateAsync(entityDic);
            return refrance.Id;
        }

        public async Task<bool> DeleteAsync(string id)
        {
            await _collection.Document(id).DeleteAsync();
            return true;
        }

        public void Dispose()
        {
            GC.SuppressFinalize(_collection);
            GC.SuppressFinalize(this);
        }

        public async Task<List<T>> GetAllAsync()
        {
            var snapshots = await _collection.GetSnapshotAsync();
            return DeserializeSnapshots<T>(snapshots);
        }


        public async Task<List<T>> GetAsync(List<(string fieldName, object value)> filterFields)
        {
            if (filterFields.Count > 0)
            {
                var query = _collection.WhereArrayContains(filterFields[0].fieldName, filterFields[0].value);
                for (int i = 1; i < filterFields.Count; i++)
                {
                    query = query.WhereArrayContains(filterFields[i].fieldName, filterFields[i].value);
                }
                var snapshots = await query.GetSnapshotAsync();
                return DeserializeSnapshots<T>(snapshots);
            }
            else
                return await GetAllAsync();
        }

        public async Task<T> GetAsync(string id)
        {
            var snapshot = await _collection.Document(id).GetSnapshotAsync();
            if (snapshot.Exists)
            {
                return DeserializeSnapshot<T>(snapshot);
            }
            return default(T);
        }

        public async Task<string> AddAsync(T entity)
        {
            Dictionary<string, object> entityDic = new Dictionary<string, object>();
            foreach (var property in entity.GetType().GetProperties())
            {
                entityDic.Add(property.Name, property.GetValue(entity));
            }
            var refrance = await _collection.AddAsync(entityDic);
            entityDic.Clear();
            entityDic.Add("Id", refrance.Id);
            await refrance.UpdateAsync(entityDic);
            return refrance.Id;
        }

        public async Task<bool> DeleteAsync(string id)
        {
            await _collection.Document(id).DeleteAsync();
            return true;
        }

        public void Dispose()
        {
            GC.SuppressFinalize(_collection);
            GC.SuppressFinalize(this);
        }

        public async Task<List<T>> GetAllAsync()
        {
            var snapshots = await _collection.GetSnapshotAsync();
            return DeserializeSnapshots<T>(snapshots);
        }


        public async Task<List<T>> GetAsync(List<(string fieldName, object value)> filterFields)
        {
            if (filterFields.Count > 0)
            {
                var query = _collection.WhereArrayContains(filterFields[0].fieldName, filterFields[0].value);
                for (int i = 1; i < filterFields.Count; i++)
                {
                    query = query.WhereArrayContains(filterFields[i].fieldName, filterFields[i].value);
                }
                var snapshots = await query.GetSnapshotAsync();
                return DeserializeSnapshots<T>(snapshots);
            }
            else
                return await GetAllAsync();
        }

        public async Task<T> GetAsync(string id)
        {
            var snapshot = await _collection.Document(id).GetSnapshotAsync();
            if (snapshot.Exists)
            {
                return DeserializeSnapshot<T>(snapshot);
            }
            return default(T);
        }


    public abstract Task HandleUsersCreated(IReadOnlyDictionary<string, (ExtraUserRecord parsed, DocumentSnapshot snap)> dict);

    public virtual FirestoreChangeListener InitUsersListen()
    {
        var res = _db.Collection(_settings.UsersCollectionName).Listen(async (snapshot, cancellationToken) =>
        {
            var parsedMap = new Dictionary<string, (ExtraUserRecord parsed, DocumentSnapshot snap)>();
            foreach (var item in snapshot.Documents)
            {
                var parsed = item.ConvertTo<ExtraUserRecord>();
                parsedMap[item.Id] = (parsed, item);
            }
            await HandleUsersCreated(parsedMap);
            var batch = _db.StartBatch();
            foreach (var item in parsedMap)
            {
                batch.Delete(item.Value.snap.Reference);
            }
            await batch.CommitAsync(cancellationToken);

        });
        return res;
    }



        public async Task ListDevelopments()
        {
            CollectionReference collection = db.Collection("developments");
            Console.WriteLine($"coll: {collection.Id}");
            QuerySnapshot querySnapshot = await collection.GetSnapshotAsync();
            Console.WriteLine($"coll.count: {querySnapshot.Count}");
            string name, status;
            DateTime createdAt;
            foreach (DocumentSnapshot queryResult in querySnapshot.Documents)
            {
                name = ""; status = ""; createdAt = new DateTime();
                if (queryResult.ContainsField("name"))
                    name = queryResult.GetValue<string>("name");
                if (queryResult.ContainsField("createdAt"))
                    createdAt = queryResult.GetValue<DateTime>("createdAt");
                if (queryResult.ContainsField("status"))
                    status = queryResult.GetValue<string>("status");
                Console.WriteLine($"{name} - {createdAt} - {status}");
            }

        }

        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);
        }

        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();
        }

        public async Task SetCollection(string collectionName, string id, object data)
        {
            try
            {
                //Console.WriteLine($"    try add doc {id} with {data}");
                CollectionReference collection = db.Collection(collectionName);
                var doc = collection.Document(id);
                //Console.WriteLine(doc);
                if (doc != null)
                {
                    await doc.DeleteAsync();
                }
                var doc1Ref = await doc.CreateAsync(data);
                Console.WriteLine("Ok");
            } catch (Exception ex)
            {
                Console.Write($"erro arq: {id} - {ex.Message}");
                Console.WriteLine();
            }
        }


        /// <summary>
        /// Creates a <see cref="CollectionReference"/> for a child collection of this document.
        /// </summary>
        /// <param name="path">The path to the collection, relative to this document. Must not be null, and must contain
        /// an odd number of slash-separated path elements.</param>
        /// <returns>A <see cref="CollectionReference"/> for the specified collection.</returns>
        public CollectionReference Collection(string path)
        {
            string[] elements = PathUtilities.SplitPath(path);
            GaxPreconditions.CheckArgument((elements.Length & 1) == 1, nameof(path), "Path must have an odd number of elements");
            CollectionReference collectionRef = new CollectionReference(Database, this, elements[0]);
            for (int i = 1; i < elements.Length; i += 2)
            {
                var documentRef = new DocumentReference(Database, collectionRef, elements[i]);
                collectionRef = new CollectionReference(Database, documentRef, elements[i + 1]);
            }
            return collectionRef;
        }

        /// <inheritdoc />
        public override int GetHashCode() => Path.GetHashCode();

        /// <inheritdoc />
        public override bool Equals(object obj) => Equals(obj as DocumentReference);

        /// <inheritdoc />
        public bool Equals(DocumentReference other) => other != null && other.Path == Path;

        /// <inheritdoc />
        public override string ToString() => Path;

        // Note: this implementation wastefully compares the characters in "projects" and "databases" but means we don't need
        // to keep a database-relative path or perform more complex comparisons.
        /// <inheritdoc />
        public int CompareTo(DocumentReference other) => other == null ? 1 : PathComparer.Instance.Compare(Path, other.Path);


        public void AddListenerToFirestoreFetched()
        {
            DocumentReference docRef = Db.Collection("Constants").Document("AppFetch");

            FirestoreChangeListener listener = docRef.Listen(async snapshot =>
            {
                if (snapshot.Exists)
                {
                    Dictionary<string, object> dict = snapshot.ToDictionary();
                    bool appFetched = (bool)dict["appFetched"];
                    if (appFetched || IsFirstRequest)
                    {
                        await snapshot.Reference.UpdateAsync(new Dictionary<string, object> { { "appFetched", false } });
                        Console.WriteLine("Cache Fetched");
                        IsFirstRequest = false;
                        var service = new FirebaseService();
                        service.FetchStocks();
                    }
                }
            });
        }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ResponseEmergencySystem.Code
{
    public static class FireBaseFunctions
    {
        /** Firestore Database Connection **/
        //Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", constants.path);
        //    dataBase = FirestoreDb.Create("dcmanagement-3d402");

        //    CollectionReference messagesRef = dataBase.Collection("chats").Document("1654ec38-ec4f-4e05-9728-46154ad7d9ab").Collection("messages");
        //Query query = messagesRef;

        //FirestoreChangeListener listener = query.Listen(snapshot =>
        //{
        //    foreach (DocumentChange change in snapshot.Changes)
        //    {
        //        if (change.ChangeType.ToString() == "Added")
        //        {
        //            Refresh_Chat(change.Document);

        //        }
        //    }
        //});
    }
}

Google.Cloud.Firestore.FirestoreChangeListener : Object

Methods :

public Task get_ListenerTask()
public Task StopAsync(CancellationToken cancellationToken = null)
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()