/**
         * Tests a *very* basic trip through the Firestore API.
         */
        protected IEnumerator GetKnownValue()
        {
            DocumentReference doc1 = db.Collection("col1").Document("doc1");
            var task = doc1.GetSnapshotAsync();

            yield return(new WaitForTaskCompletion(this, task));

            if (!(task.IsFaulted || task.IsCanceled))
            {
                DocumentSnapshot             snap = task.Result;
                IDictionary <string, object> dict = snap.ToDictionary();
                if (dict.ContainsKey("field1"))
                {
                    fieldContents = dict["field1"].ToString();
                }
                else
                {
                    DebugLog("ERROR: Successfully retrieved col1/doc1, but it doesn't contain 'field1' key");
                }
            }
        }
        public void MissingDocument()
        {
            var db       = FirestoreDb.Create("proj", "db", new FakeFirestoreClient());
            var readTime = new Timestamp(10, 2);
            var document = DocumentSnapshot.ForMissingDocument(db, "projects/proj/databases/db/documents/col1/doc1/col2/doc2", readTime);

            Assert.Equal(db.Document("col1/doc1/col2/doc2"), document.Reference);
            Assert.Equal("doc2", document.Id);
            Assert.Same(db, document.Database);
            Assert.Null(document.Document);
            Assert.Null(document.CreateTime);
            Assert.Null(document.UpdateTime);
            Assert.Equal(readTime, document.ReadTime);
            Assert.False(document.Exists);
            Assert.Null(document.ToDictionary());
            Assert.Null(document.ConvertTo <SampleData>());
            Assert.Throws <InvalidOperationException>(() => document.GetValue <string>("name"));
            Assert.Throws <InvalidOperationException>(() => document.GetValue <string>(new FieldPath("name")));
            Assert.False(document.TryGetValue("name", out string name1));
            Assert.False(document.TryGetValue(new FieldPath("name"), out string name2));
        }
        private static DocumentSnapshot GetSampleSnapshot()
        {
            var poco = new SampleData
            {
                Name   = "Test",
                Nested = new NestedData {
                    Score = 20
                }
            };
            var db       = FirestoreDb.Create("proj", "db", new FakeFirestoreClient());
            var readTime = new Timestamp(10, 2);
            var proto    = new Document
            {
                CreateTime = CreateProtoTimestamp(1, 10),
                UpdateTime = CreateProtoTimestamp(2, 20),
                Name       = "projects/proj/databases/db/documents/col1/doc1/col2/doc2",
                Fields     = { ValueSerializer.SerializeMap(poco) }
            };

            return(DocumentSnapshot.ForDocument(db, proto, readTime));
        }
Exemple #4
0
        /*
         * Tek bir oyuncu bilgisini dokümand ıd değerine göre çeken fonksiyonumuz
         */
        public async Task <Player> GetPlayerById(string documentId)
        {
            // Doküman referansını bulup
            DocumentReference document = db.Collection("players").Document(documentId);
            // bir görüntüsünü çekiyoruz
            DocumentSnapshot snapshot = await document.GetSnapshotAsync();

            Player player = new Player();

            if (snapshot.Exists) // Eğer snapshot içeriği mevcutsa
            {
                player.DocumentId = snapshot.Id;
                // oyuncu bilgilerini dokümandan GetValue ile alıyoruz
                player.Fullname = snapshot.GetValue <string>("Fullname");
                player.Position = snapshot.GetValue <string>("Position");
                player.SomeInfo = snapshot.GetValue <string>("SomeInfo");
                player.Length   = snapshot.GetValue <string>("Length");
            }

            return(player);
        }
Exemple #5
0
        public void ArrayContainsIsEquality()
        {
            var collection = s_db.Collection("col");
            var document   = new Document
            {
                CreateTime = CreateProtoTimestamp(0, 0),
                UpdateTime = CreateProtoTimestamp(0, 0),
                Name       = collection.Document("doc").Path,
                Fields     = { { "field", CreateArray(CreateValue(1), CreateValue(2)) } }
            };
            var snapshot = DocumentSnapshot.ForDocument(s_db, document, Timestamp.FromProto(document.CreateTime));
            // An inequality filter would create an implicit ordering here, but "array contains"
            // is effectively an equality filter, so we should end up with document ID ordering instead.
            var query           = s_db.Collection("col").WhereArrayContains("field", 1).StartAt(snapshot);
            var structured      = query.ToStructuredQuery();
            var documentIdOrder = new Order {
                Direction = Direction.Ascending, Field = FieldPath.DocumentId.ToFieldReference()
            };

            Assert.Equal(new[] { documentIdOrder }, structured.OrderBy);
        }
        public void ConvertTo_ValueType()
        {
            var db       = FirestoreDb.Create("proj", "db", new FakeFirestoreClient());
            var readTime = new Timestamp(10, 2);
            var proto    = new Document
            {
                CreateTime = CreateProtoTimestamp(1, 10),
                UpdateTime = CreateProtoTimestamp(2, 20),
                Name       = "projects/proj/databases/db/documents/col1/doc1/col2/doc2",
                Fields     =
                {
                    ["Name"]  = CreateValue("text"),
                    ["Value"] = CreateValue(100)
                }
            };
            var document = DocumentSnapshot.ForDocument(db, proto, readTime);
            var value    = document.ConvertTo <SerializationTestData.CustomValueType>();

            Assert.Equal("text", value.Name);
            Assert.Equal(100, value.Value);
        }
Exemple #7
0
        public override void Extract(DocumentSnapshot snapshot)
        {
            Dictionary <string, object> value;

            if (!snapshot.TryGetValue(firestoreField, out value))
            {
                return;
            }

            // remove anything not in the new dictionary
            var oldPairs = _dictionary.ToArray();

            foreach (var pair in oldPairs)
            {
                if (value == null || !value.ContainsKey(pair.Key.ToString()))
                {
                    _dictionary.Remove(pair.Key);
                    removed?.Invoke(this, pair.Key);
                }
            }

            // add anything not in the old dictionary
            if (value != null)
            {
                foreach (var pair in value)
                {
                    var    newKey   = (TKey)Convert.ChangeType(pair.Key, typeof(TKey));
                    var    newValue = (TValue)_converterFromFirestore(pair.Value);
                    TValue oldValue;
                    if (!(
                            _dictionary.TryGetValue(newKey, out oldValue) &&
                            Object.Equals(oldValue, newValue)
                            ))
                    {
                        _dictionary[newKey] = newValue;
                        set?.Invoke(this, new KeyValuePair <TKey, TValue>(newKey, newValue));
                    }
                }
            }
        }
        // Users 1 and 2 adding each other
        public async Task addUser()
        {
            FirestoreDb db = FirestoreDb.Create("networking-application");

            Console.WriteLine("Created Cloud Firestore client with project ID: {0}", "networking-application");

            // Adding User 1 to User 2's friend list
            DocumentReference user1Ref = db.Collection("Users").Document("user1");
            DocumentSnapshot  snapshot = await user1Ref.GetSnapshotAsync();

            Dictionary <string, object> user1Info = snapshot.ToDictionary();
            object addingUser1 = user1Info.FirstOrDefault(x => x.Key == "userName").Value;

            DocumentReference doc2Ref = db.Collection("Users").Document("user2").Collection("Friends").Document(addingUser1.ToString());

            Dictionary <string, object> newUser2Friend = new Dictionary <string, object>
            {
                { "TimeofAdd", Timestamp.GetCurrentTimestamp() }
            };

            await doc2Ref.SetAsync(newUser2Friend);

            // Adding User 2 to User 1's friend list
            FirestoreDb       bake      = FirestoreDb.Create("networking-application");
            DocumentReference user2Ref  = bake.Collection("Users").Document("user2");
            DocumentSnapshot  snapshot2 = await user2Ref.GetSnapshotAsync();

            Dictionary <string, object> user2Info = snapshot2.ToDictionary();

            object addingUser2 = user2Info.FirstOrDefault(x => x.Key == "userName").Value;

            DocumentReference           docRef         = bake.Collection("Users").Document("user1").Collection("Friends").Document(addingUser2.ToString());
            Dictionary <string, object> newUser1Friend = new Dictionary <string, object>
            {
                { "TimeOfAdd", Timestamp.GetCurrentTimestamp() }
            };

            await docRef.SetAsync(newUser1Friend);
        }
        // User 2 blocking User 1
        public async Task blockUser()
        {
            FirestoreDb db = FirestoreDb.Create("networking-application");

            Console.WriteLine("Created Cloud Firestore client with project ID: {0}", "networking-application");

            DocumentReference user1Ref = db.Collection("Users").Document("user1");
            DocumentSnapshot  snapshot = await user1Ref.GetSnapshotAsync();

            Dictionary <string, object> user1Info = snapshot.ToDictionary();

            object            userToBlock = user1Info.FirstOrDefault(x => x.Key == "userName").Value;
            DocumentReference user2Ref    = db.Collection("Users").Document("user2").Collection("Blocked").Document(userToBlock.ToString());

            Dictionary <string, object> newBlock = new Dictionary <string, object>
            {
                { "TimeOfBlock", Timestamp.GetCurrentTimestamp() },
                { "UserID", "1234" }
            };

            await user2Ref.SetAsync(newBlock);
        }
Exemple #10
0
        public override void DocumentProcessed(DocumentSnapshot document)
        {
            _projectSnapshotManagerDispatcher.AssertDispatcherThread();

            if (!_projectManager.IsDocumentOpen(document.FilePath))
            {
                return;
            }

            if (document is not DefaultDocumentSnapshot defaultDocument)
            {
                return;
            }

            if (!_documentVersionCache.TryGetDocumentVersion(document, out var nullableSyncVersion))
            {
                // Document is no longer important.
                return;
            }

            var syncVersion = nullableSyncVersion.Value;

            var documentContainer          = defaultDocument.State.GeneratedDocumentContainer;
            var latestSynchronizedDocument = documentContainer.LatestDocument;

            if (latestSynchronizedDocument is null ||
                latestSynchronizedDocument == document)
            {
                // Already up-to-date
                return;
            }

            if (UnchangedHostDocument(document, latestSynchronizedDocument, syncVersion))
            {
                // Documents are identical but we didn't synchronize them because they didn't need to be re-evaluated.
                _generatedDocumentPublisher.PublishCSharp(document.FilePath, documentContainer.CSharpSourceTextContainer.CurrentText, syncVersion);
                _generatedDocumentPublisher.PublishHtml(document.FilePath, documentContainer.HtmlSourceTextContainer.CurrentText, syncVersion);
            }
        }
Exemple #11
0
        public override void DocumentProcessed(DocumentSnapshot document)
        {
            _foregroundDispatcher.AssertForegroundThread();

            if (!_projectManager.IsDocumentOpen(document.FilePath))
            {
                return;
            }

            if (!(document is DefaultDocumentSnapshot defaultDocument))
            {
                return;
            }

            if (!_documentVersionCache.TryGetDocumentVersion(document, out var syncVersion))
            {
                // Document is no longer important.
                return;
            }

            var latestSynchronizedDocument = defaultDocument.State.HostDocument.GeneratedCodeContainer.LatestDocument;

            if (latestSynchronizedDocument == null ||
                latestSynchronizedDocument == document)
            {
                // Already up-to-date
                return;
            }

            if (IdenticalOutputAfterParse(document, latestSynchronizedDocument, syncVersion))
            {
                // Documents are identical but we didn't synchronize them because they didn't need to be re-evaluated.

                var result = document.TryGetText(out var latestText);
                Debug.Assert(result, "We just successfully retrieved the text version, this should always return true.");

                _csharpPublisher.Publish(document.FilePath, latestText, syncVersion);
            }
        }
Exemple #12
0
        private static async Task GetDocAsMap(string project)
        {
            FirestoreDb db = FirestoreDb.Create(project);
            // [START fs_get_doc_as_map]
            DocumentReference docRef   = db.Collection("cities").Document("SF");
            DocumentSnapshot  snapshot = await docRef.GetSnapshotAsync();

            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);
                }
            }
            else
            {
                Console.WriteLine("Document {0} does not exist!", snapshot.Id);
            }
            // [END fs_get_doc_as_map]
        }
        public async Task UpdateByUserCodeAsync(string userCode, DeviceCode data)
        {
            DocumentSnapshot deviceFlowCodes =
                await GetDeviceFlow(nameof(DeviceFlowCodes.UserCode), userCode).ConfigureAwait(false);

            if (!deviceFlowCodes.Exists)
            {
                _logger.LogError("{userCode} not found in database", userCode);
                throw new InvalidOperationException("Could not update device code");
            }

            DeviceFlowCodes existing = deviceFlowCodes.ConvertTo <DeviceFlowCodes>();

            DeviceFlowCodes entity = ToEntity(data, existing.DeviceCode, userCode);

            _logger.LogDebug("{userCode} found in database", userCode);

            existing.SubjectId = data.Subject?.FindFirst(JwtClaimTypes.Subject).Value;
            existing.Data      = entity.Data;

            await deviceFlowCodes.Reference.SetAsync(existing).ConfigureAwait(false);
        }
        private async Task <Range> GetNavigateRangeAsync(DocumentSnapshot documentSnapshot, BoundAttributeDescriptor?attributeDescriptor, CancellationToken cancellationToken)
        {
            if (attributeDescriptor is not null)
            {
                _logger.LogInformation("Attempting to get definition from an attribute directly.");

                var originCodeDocument = await documentSnapshot.GetGeneratedOutputAsync().ConfigureAwait(false);

                var range = await TryGetPropertyRangeAsync(originCodeDocument, attributeDescriptor.GetPropertyName(), _documentMappingService, _logger, cancellationToken).ConfigureAwait(false);

                if (range is not null)
                {
                    return(range);
                }
            }

            // When navigating from a start or end tag, we just take the user to the top of the file.
            // If we were trying to navigate to a property, and we couldn't find it, we can at least take
            // them to the file for the component. If the property was defined in a partial class they can
            // at least then press F7 to go there.
            return(new Range(new Position(0, 0), new Position(0, 0)));
        }
        public static async Task <Dictionary <string, ulong> > GetSelfassignable(ulong guildID)
        {
            DocumentReference guildDocument = Db.Document(Convert.ToString(guildID)).Collection("lite").Document("data");
            DocumentSnapshot  guildSnapshot = await guildDocument.GetSnapshotAsync();

            guildSnapshot.TryGetValue("selfAssignable", out Dictionary <string, object> selfAssignablesUncasted);

            Dictionary <string, ulong> selfAssignablesCasted = new Dictionary <string, ulong>();

            foreach (KeyValuePair <string, object> kvp in selfAssignablesUncasted)
            {
                if (kvp.Value == null)
                {
                    continue;
                }

                ulong roleID = Convert.ToUInt64(kvp.Value);
                selfAssignablesCasted[kvp.Key] = roleID;
            }

            return(selfAssignablesCasted);
        }
        /// <summary>
        /// Extracts the cache value from a Firestore document snapshot.
        /// Checks all the expiration fields so never returns a stale value.
        /// </summary>
        /// <param name="snapshot">The snapshot to pull the cache value from.</param>
        /// <returns>The cache value or null.</returns>
        private byte[] ValueFromSnapshot(DocumentSnapshot snapshot)
        {
            if (!snapshot.Exists)
            {
                return(null);
            }
            CacheDoc doc = snapshot.ConvertTo <CacheDoc>();
            var      now = _clock.GetCurrentDateTimeUtc();

            if (doc.AbsoluteExpiration < now)
            {
                return(null);
            }
            var slidingExpiration = doc.LastRefresh.GetValueOrDefault()
                                    + TimeSpan.FromSeconds(doc.SlidingExpirationSeconds.GetValueOrDefault());

            if (slidingExpiration < now)
            {
                return(null);
            }
            return(doc.Value);
        }
Exemple #17
0
        private async void frmEditInvoice_Load(Object sender, EventArgs e)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"pro-vantagens-firebase-adminsdk-5cf5q-82ec44750b.json";

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);

            FirestoreDb db = FirestoreDb.Create("pro-vantagens");

            documentReference = db.Collection("users").Document(userID).Collection("invoices").Document(invoiceID);
            documentSnapshot  = await documentReference.GetSnapshotAsync();

            invoices = documentSnapshot.ConvertTo <Invoices>();

            txtHolder.Text        = invoices.holder;
            txtPlanName.Text      = invoices.planName;
            cboPaymentMethod.Text = invoices.paymentMethod;
            cboStatus.Text        = invoices.status;
            txtPlanValue.Text     = (double.Parse(invoices.value, CultureInfo.InvariantCulture)).ToString();
            txtAditional.Text     = invoices.aditional.ToString();
            txtTotalValue.Text    = invoices.totalValue.ToString();
            txtDueDate.Text       = invoices.dueDate.ToString();
        }
        public void ExistingDocument()
        {
            var db       = FirestoreDb.Create("proj", "db", new FakeFirestoreClient());
            var readTime = new Timestamp(10, 2);
            var proto    = new Document
            {
                CreateTime = CreateProtoTimestamp(1, 10),
                UpdateTime = CreateProtoTimestamp(2, 20),
                Name       = "projects/proj/databases/db/documents/col1/doc1/col2/doc2"
            };
            var document = DocumentSnapshot.ForDocument(db, proto, readTime);

            Assert.Equal(db.Document("col1/doc1/col2/doc2"), document.Reference);
            Assert.Equal("doc2", document.Id);
            Assert.Same(db, document.Database);
            Assert.Same(proto, document.Document);
            Assert.Equal(new Timestamp(1, 10), document.CreateTime);
            Assert.Equal(new Timestamp(2, 20), document.UpdateTime);
            Assert.Equal(readTime, document.ReadTime);
            Assert.True(document.Exists);
            // Tests for data access are performed separately.
        }
Exemple #19
0
        async void editDb()
        {
            foreach (string id in edit_coll_id)
            {
                DocumentReference docref = db.Collection("stock").Document(id);

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    string temp = Convert.ToString(dataGridView1.Rows[i].Cells[dataGridView1.Columns["id"].Index].Value);

                    if (temp != "")
                    {
                        if (temp == id)
                        {
                            Dictionary <string, object> data = new Dictionary <string, object>()
                            {
                                { "item_name", dataGridView1.Rows[i].Cells[dataGridView1.Columns["item_name"].Index].Value.ToString() },
                                { "vendor_id", dataGridView1.Rows[i].Cells[dataGridView1.Columns["vendor_id"].Index].Value.ToString() },
                                { "unit_price", Convert.ToDouble(dataGridView1.Rows[i].Cells[dataGridView1.Columns["unit_price"].Index].Value.ToString()) },
                                { "quantity", Int32.Parse(dataGridView1.Rows[i].Cells[dataGridView1.Columns["quantity"].Index].Value.ToString()) },
                                { "wholesale_price", Convert.ToDouble(dataGridView1.Rows[i].Cells[dataGridView1.Columns["wholesale_price"].Index].Value.ToString()) },
                                { "item_id", dataGridView1.Rows[i].Cells[dataGridView1.Columns["item_id"].Index].Value.ToString() }
                            };

                            DocumentSnapshot snap = await docref.GetSnapshotAsync();

                            if (snap.Exists)
                            {
                                await docref.SetAsync(data);
                            }

                            break;
                        }
                    }
                }
            }

            edit_coll_id.Clear();
        }
Exemple #20
0
        // Maps a span in the primary buffer to the secondary buffer. This is only valid for C# code
        // that appears in the primary buffer.
        private async Task <TextSpan> GetSecondarySpanAsync(DocumentSnapshot primary, TextSpan primarySpan, Document secondary)
        {
            var output = await primary.GetGeneratedOutputAsync();

            var mappings = output.GetCSharpDocument().SourceMappings;

            for (var i = 0; i < mappings.Count; i++)
            {
                var mapping = mappings[i];
                if (mapping.OriginalSpan.AsTextSpan().Contains(primarySpan))
                {
                    var offset        = mapping.GeneratedSpan.AbsoluteIndex - mapping.OriginalSpan.AbsoluteIndex;
                    var secondarySpan = new TextSpan(primarySpan.Start + offset, primarySpan.Length);
                    Assert.Equal(
                        (await primary.GetTextAsync()).GetSubText(primarySpan).ToString(),
                        (await secondary.GetTextAsync()).GetSubText(secondarySpan).ToString());
                    return(secondarySpan);
                }
            }

            throw new InvalidOperationException("Could not map the primary span to the generated code.");
        }
Exemple #21
0
        public async Task <TodoTask> GetTodoData(string id)
        {
            DocumentReference dr = firestoreDb
                                   .Collection("tasks")
                                   .Document(id);

            DocumentSnapshot snapshot = await
                                        dr.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                TodoTask task = snapshot
                                .ConvertTo <TodoTask>();

                task.Id = snapshot.Id;
                return(task);
            }
            else
            {
                return(new TodoTask());
            }
        }
Exemple #22
0
        public async Task <UserDbModel> GetByIdAsync(string userId)
        {
            if (string.IsNullOrEmpty(userId))
            {
                return(null);
            }

            DocumentReference docRef   = _entities.FirestoreDb?.Collection(_collection)?.Document(userId.ToString());
            DocumentSnapshot  snapshot = await docRef.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                Dictionary <string, object> dictionary = snapshot.ToDictionary();
                return(new UserDbModel()
                {
                    Id = snapshot.Id,
                    Email = dictionary["email"].ToString()
                });
            }

            return(null);
        }
        public async Task <ActionResult> DeleteMedicine(string id, string appointmentid, string patientid, string quantity, string inventoryid)
        {
            try
            {
                string appautoid     = appointmentid;
                string patientautoid = patientid;
                string medicineId    = id;
                string Path          = AppDomain.CurrentDomain.BaseDirectory + @"greenpaperdev-firebase-adminsdk-8k2y5-fb46e63414.json";
                Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Path);
                FirestoreDb db = FirestoreDb.Create("greenpaperdev");

                //CollectionReference col1 = db.Collection("clinics").Document("ly0N6C9cO0crz0s6LMUi").Collection("appointments").Document(appautoid).Collection("medicines");
                DocumentReference docRef = db.Collection("clinics").Document(GlobalSessionVariables.ClinicDocumentAutoId).Collection("appointments").Document(appautoid).Collection("medicines").Document(medicineId);
                await docRef.DeleteAsync();

                DocumentReference docRefInventory  = db.Collection("clinics").Document(GlobalSessionVariables.ClinicDocumentAutoId).Collection("inventory").Document(inventoryid);
                DocumentSnapshot  docSnapInventory = await docRefInventory.GetSnapshotAsync();

                int updatedQuantityBalance = docSnapInventory.GetValue <int>("quantitybalance") + Convert.ToInt32(quantity);

                Dictionary <string, object> data2 = new Dictionary <string, object>
                {
                    { "quantitybalance", updatedQuantityBalance }
                };


                if (docSnapInventory.Exists)
                {
                    await docRefInventory.UpdateAsync(data2);
                }

                return(RedirectToAction("Index", "Image", new { id = appautoid, patient = patientautoid }));
            }
            catch (Exception ex)
            {
                return(View());
            }
        }
        }     //end of method

        public async Task <bool> isAuthorized(string email, int accessPin)
        {
            //reperents the authorization state of the user
            bool isAuthorized = false;

            try
            {
                //connection to the database
                bool connection_Result = connectToFirebase();
                //if the connection is succesfull
                if (connection_Result)
                {
                    //Get the Document reference from the database
                    DocumentReference documentReference = db.Collection("User").Document(email);
                    //Get the snap of the user data form the database
                    DocumentSnapshot documentSnapshot = await documentReference.GetSnapshotAsync();

                    //if the snap exists for the user then check for the validation of the access Pin for the authorization of the user
                    if (documentSnapshot.Exists)
                    {
                        //Conver the snap into the User Object
                        User user_Info = documentSnapshot.ConvertTo <User>();
                        //Bcrypt the Obtianed Pin then verify using the BCRYPT NUGET Package
                        isAuthorized = BC.Verify(accessPin.ToString(), user_Info.accessPIN);
                    } //end if
                }     //end if
                //return the result of the authorization
                return(isAuthorized);
            }//end the try block
            catch (Exception ex)
            {
                //Catch the exception and throw the to the user
                CustomException customException = new CustomException();
                customException.errorTitleName     = ex.Message;
                customException.errorMessageToUser = "******";
                throw new FaultException <CustomException>(customException);
            }
        }
        public void OnSuccess(Java.Lang.Object result)
        {
            DocumentSnapshot snapshot = (DocumentSnapshot)result;

            if (!snapshot.Exists())
            {
                return;
            }

            DocumentReference likesReference = AppDataHelper.GetFirestore().Collection("posts").Document(postID);

            if (Like)
            {
                likesReference.Update("likes." + AppDataHelper.GetFirebaseAuth().CurrentUser.Uid, true);
            }
            else
            {
                if (snapshot.Get("likes") == null)
                {
                    return;
                }

                var data = snapshot.Get("likes") != null?snapshot.Get("likes") : null;

                if (data != null)
                {
                    var dictionaryFromHashMap = new Android.Runtime.JavaDictionary <string, string>(data.Handle, JniHandleOwnership.DoNotRegister);

                    string uid = AppDataHelper.GetFirebaseAuth().CurrentUser.Uid;

                    if (dictionaryFromHashMap.Contains(uid))
                    {
                        dictionaryFromHashMap.Remove(uid);
                        likesReference.Update("likes", dictionaryFromHashMap);
                    }
                }
            }
        }
        public override async Task <TextEdit[]> FormatAsync(DocumentUri uri, DocumentSnapshot documentSnapshot, Range range, FormattingOptions options, CancellationToken cancellationToken)
        {
            if (uri is null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (documentSnapshot is null)
            {
                throw new ArgumentNullException(nameof(documentSnapshot));
            }

            if (range is null)
            {
                throw new ArgumentNullException(nameof(range));
            }

            if (options is null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var codeDocument = await documentSnapshot.GetGeneratedOutputAsync();

            using var context = FormattingContext.Create(uri, documentSnapshot, codeDocument, options, range);

            var result = new FormattingResult(Array.Empty <TextEdit>());

            foreach (var pass in _formattingPasses)
            {
                cancellationToken.ThrowIfCancellationRequested();
                result = await pass.ExecuteAsync(context, result, cancellationToken);
            }

            var filteredEdits = result.Edits.Where(e => range.LineOverlapsWith(e.Range)).ToArray();

            return(filteredEdits);
        }
Exemple #27
0
        private static async Task GetDocAsEntity(string project)
        {
            FirestoreDb db = FirestoreDb.Create(project);
            // [START fs_get_doc_as_entity]
            DocumentReference docRef   = db.Collection("cities").Document("BJ");
            DocumentSnapshot  snapshot = await docRef.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                Console.WriteLine("Document data for {0} document:", snapshot.Id);
                City city = snapshot.ConvertTo <City>();
                Console.WriteLine("Name: {0}", city.Name);
                Console.WriteLine("State: {0}", city.State);
                Console.WriteLine("Country: {0}", city.Country);
                Console.WriteLine("Capital: {0}", city.Capital);
                Console.WriteLine("Population: {0}", city.Population);
            }
            else
            {
                Console.WriteLine("Document {0} does not exist!", snapshot.Id);
            }
            // [END fs_get_doc_as_entity]
        }
        public async Task <Employee> GetEmployeeData(string id)
        {
            try
            {
                DocumentReference docRef   = fireStoreDb.Collection("employees").Document(id);
                DocumentSnapshot  snapshot = await docRef.GetSnapshotAsync();

                if (snapshot.Exists)
                {
                    Employee emp = snapshot.ConvertTo <Employee>();
                    emp.EmployeeId = snapshot.Id;
                    return(emp);
                }
                else
                {
                    return(new Employee());
                }
            }
            catch
            {
                throw;
            }
        }
Exemple #29
0
        public void Enqueue(ProjectSnapshot project, DocumentSnapshot document)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            _foregroundDispatcher.AssertForegroundThread();

            lock (_work)
            {
                // We only want to store the last 'seen' version of any given document. That way when we pick one to process
                // it's always the best version to use.
                _work[new DocumentKey(project.FilePath, document.FilePath)] = document;

                StartWorker();
            }
        }
Exemple #30
0
        /// <inheritdoc/>
        public async Task <Bookmark> GetBookmarkAsync(string id)
        {
            _logger.LogDebug($"Searching for Bookmark with id '{id}'.");

            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException($"Bookmark id with value '{id}' is invalid.");
            }

            DocumentReference bookmarkReference = _bookmarksCollection.Document(id);
            DocumentSnapshot  bookmarkSnapshot  = await bookmarkReference.GetSnapshotAsync();

            if (bookmarkSnapshot.Exists)
            {
                _logger.LogDebug($"Bookmark found with id '{id}'.");
                return(bookmarkSnapshot.ConvertTo <Bookmark>());
            }
            else
            {
                _logger.LogInformation($"No Bookmark found with id '{id}'.");
                return(null);
            }
        }