Ejemplo n.º 1
0
        /// <summary>
        /// Approves a section. Returns true if the section has been approved by everyone.
        /// </summary>
        /// <param name="username">Username approving</param>
        /// <param name="sectionId">Section to approve</param>
        /// <returns>Whether section has been approved by all or not</returns>
        public async Task <Boolean> ApproveSection(string username, string sectionId)
        {
            DocumentReference   docRef   = db.Collection("sections").Document(sectionId);
            CollectionReference userRef  = db.Collection("users");
            DocumentSnapshot    snapshot = await docRef.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                Section section = snapshot.ConvertTo <Section>();
                if (!section.ApprovedBy.Contains(username))
                {
                    section.ApprovedBy.Add(username);
                    await docRef.UpdateAsync("ApprovedBy", FieldValue.ArrayUnion(username));
                }
                QuerySnapshot userSnapshots = await userRef.GetSnapshotAsync();

                if (userSnapshots.Count <= section.ApprovedBy.Count())
                {
                    await docRef.UpdateAsync("ApprovedAt", Timestamp.GetCurrentTimestamp());

                    return(true);
                }
            }
            return(false);
        }
Ejemplo n.º 2
0
 public IEnumerator TestCreateViaArrayUnion() {
   DocumentReference doc = TestDocument();
   var data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(1L, 2L) } };
   yield return AwaitSuccess(doc.SetAsync(data));
   yield return AssertExpectedDocument(
       doc, new Dictionary<string, object> { { "array", new List<object> { 1L, 2L } } });
 }
Ejemplo n.º 3
0
        public void TakeTeacherAttendance(IList <string> teacherIds, DateTime date)
        {
            string d = date.ToString("MM/dd/yyyy");

            foreach (string teacherId in Teachers.Keys)
            {
                DocumentReference dr = db.Collection("teachers").Document(teacherId);

                DocumentSnapshot snapshot = Teachers[teacherId];

                try
                {
                    snapshot.GetValue <string[]>("attended");
                    if (teacherIds.Contains(teacherId))
                    {
                        dr.UpdateAsync("attended", FieldValue.ArrayUnion(d)).Wait();
                    }
                    else
                    {
                        dr.UpdateAsync("attended", FieldValue.ArrayRemove(d)).Wait();
                    }
                }
                catch
                {
                    if (teacherIds.Contains(teacherId))
                    {
                        Dictionary <string, object> update = new Dictionary <string, object>
                        {
                            { "attended", new string[] { d } }
                        };
                        dr.SetAsync(update, SetOptions.MergeAll).Wait();
                    }
                }
            }
        }
Ejemplo n.º 4
0
        public async Task updates_existing_document()
        {
            var sut      = CrossFirebaseFirestore.Current;
            var pokemon  = PokemonFactory.CreateSquirtle();
            var path     = $"testing/{pokemon.Id}";
            var document = sut.GetDocument(path);

            await document.SetDataAsync(pokemon);

            Assert.Equal(pokemon, (await document.GetDocumentSnapshotAsync <Pokemon>()).Data);

            var update = new Dictionary <object, object> {
                { "name", "Cool Squirtle" },
                { "moves", FieldValue.ArrayUnion("Bubble-Blast") },
                { "first_sighting_location.latitude", 13.37 }
            };

            await document.UpdateDataAsync(update);

            var snapshot = await document.GetDocumentSnapshotAsync <Pokemon>();

            Assert.Equal("Cool Squirtle", snapshot.Data.Name);
            Assert.True(snapshot.Data.Moves.Contains("Bubble-Blast"));
            Assert.Equal(13.37, snapshot.Data.FirstSightingLocation.Latitude);
        }
Ejemplo n.º 5
0
        public async void AddFoodRecord(string userId, string item, string money, string bookDate)
        {
            DocumentReference docRef  = _db.Collection(userId).Document(bookDate);
            DocumentSnapshot  docShot = await _db.Collection(userId).Document(bookDate).GetSnapshotAsync();

            Dictionary <string, object> record = new Dictionary <string, object> {
                { "Id", Guid.NewGuid().ToString("N") },
                { "Name", item },
                { "Money", money.Contains(".") ? float.Parse(money) : Convert.ToInt32(money) }
            };

            if (docShot.Exists)
            {
                if (docShot.GetValue <List <Dictionary <string, object> > > ("list").Count > 0)
                {
                    await docRef.UpdateAsync("list", FieldValue.ArrayUnion(record));
                }
                else
                {
                    await docRef.SetAsync(new { list = new List <Dictionary <string, object> > ()
                                                {
                                                    record
                                                } });
                }
            }
            else
            {
                await docRef.SetAsync(new { list = new List <Dictionary <string, object> > ()
                                            {
                                                record
                                            } });
            }
        }
Ejemplo n.º 6
0
 private static void AddAssetRefToEdge(WriteBatch batch, DocumentReference assetRef, DocumentReference edgeRef)
 {
     Console.WriteLine($"Associating asset ({assetRef.Id}) to edge ({edgeRef.Id})");
     batch.Update(edgeRef, new Dictionary <string, object> {
         { nameof(EdgeData.AssetRefs), FieldValue.ArrayUnion(assetRef) },
         { nameof(EdgeData.LastUpdate), Timestamp.GetCurrentTimestamp() }
     });
 }
Ejemplo n.º 7
0
        //----------------------------------------------------

        /**
         * Adds a user request to a team
         */
        public static async Task AddUserRequestToTeamAsync(string userId, Team team)
        {
            await CrossCloudFirestore.Current
            .Instance
            .GetCollection("Team")
            .GetDocument(team.Id)
            .UpdateDataAsync("member_request", FieldValue.ArrayUnion(userId));
        }
 public static async Task AddNotificationToUserAsync(string userId, string notification_id)
 {
     await CrossCloudFirestore.Current
     .Instance
     .GetCollection("User")
     .GetDocument(userId)
     .UpdateDataAsync("notifications", FieldValue.ArrayUnion(notification_id));
 }
 /**
  * Adds a team to a user
  */
 public static async Task AddTeamToUserAsync(string userId, Team team)
 {
     await CrossCloudFirestore.Current
     .Instance
     .GetCollection("User")
     .GetDocument(userId)
     .UpdateDataAsync("team", FieldValue.ArrayUnion(team.Id));
 }
Ejemplo n.º 10
0
    public IEnumerator TestRemoveViaSetMergeArrayRemove() {
      DocumentReference doc = TestDocument();
      var data = new Dictionary<string, object> { { "array", FieldValue.ArrayUnion(1L, 2L, 3L) } };
      yield return AwaitSuccess(doc.SetAsync(data));

      data = new Dictionary<string, object> { { "array", FieldValue.ArrayRemove(1L, 3L) } };
      AwaitSuccess(doc.SetAsync(data, SetOptions.MergeAll));
      yield return AssertExpectedDocument(
          doc, new Dictionary<string, object> { { "array", new List<object> { 2L } } });
    }
Ejemplo n.º 11
0
        async void Update_Array_Elements()
        {
            DocumentReference docref = db.Collection("Add_Aray").Document("myDoc");
            DocumentSnapshot  snap   = await docref.GetSnapshotAsync();

            if (snap.Exists)
            {
                await docref.UpdateAsync("My Array", FieldValue.ArrayUnion(123, "abcd", 456));
            }
        }
Ejemplo n.º 12
0
        public void ArrayUnion()
        {
            var sentinel = FieldValue.ArrayUnion("a", "b");
            var value    = ValueSerializer.Serialize(SerializationContext.Default, sentinel);

            Assert.Equal(SentinelKind.ArrayUnion, SentinelValue.GetKind(value));
            var array    = SentinelValue.GetArrayValue(value);
            var expected = CreateArray(CreateValue("a"), CreateValue("b")).ArrayValue;

            Assert.Equal(expected, array);
        }
Ejemplo n.º 13
0
        private static async Task UpdateDocumentArray(string project)
        {
            FirestoreDb db = FirestoreDb.Create(project);
            // [START fs_update_document_array]
            DocumentReference washingtonRef = db.Collection("cities").Document("DC");

            // Atomically add a new region to the "regions" array field.
            await washingtonRef.UpdateAsync("Regions", FieldValue.ArrayUnion("greater_virginia"));

            // Atomically remove a region from the "regions" array field.
            await washingtonRef.UpdateAsync("Regions", FieldValue.ArrayRemove("east_coast"));

            // [END fs_update_document_array]
            Console.WriteLine("Updated the Regions array of the DC document in the cities collection.");
        }
Ejemplo n.º 14
0
    public IEnumerator TestRemoveObjectsViaUpdateArrayRemove() {
      DocumentReference doc = TestDocument();
      var data = new Dictionary<string, object> {
        { "array",
          FieldValue.ArrayUnion(1L, new Dictionary<string, object> { { "a", "value" } }, 3L) }
      };
      yield return AwaitSuccess(doc.SetAsync(data));

      data = new Dictionary<string, object> {
        { "array", FieldValue.ArrayRemove(new Dictionary<string, object> { { "a", "value" } }) }
      };
      AwaitSuccess(doc.UpdateAsync(data));
      yield return AssertExpectedDocument(
          doc, new Dictionary<string, object> { { "array", new List<object> { 1L, 3L } } });
    }
Ejemplo n.º 15
0
        // GET: Klant/Create
        public async Task <IActionResult> Create(string documentId, Product product)
        {
            db = FirestoreDatabase.LoadDatabase();

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

            if (product.ProductId != null)
            {
                await document.UpdateAsync("products", FieldValue.ArrayUnion(product));

                return(RedirectToAction(documentId, "Klant/Producten"));
            }

            return(View(product));
        }
Ejemplo n.º 16
0
        public void EditStudent(string studentId, string newClassName, string newStudentName, string newStudentPhone, string newGrade,
                                string newParentName, string newParentPhone, DateTime newBirthday)
        {
            DocumentReference dr = db.Collection("students").Document(studentId);

            Dictionary <string, object> update = new Dictionary <string, object>
            {
                { "studentName", newStudentName },
                { "studentPhone", newStudentPhone },
                { "grade", newGrade },
                { "parentName", newParentName },
                { "parentPhone", newParentPhone },
                { "birthday", newBirthday.ToString("MM/dd/yyyy").Substring(0, 5) }
            };

            dr.SetAsync(update, SetOptions.MergeAll).Wait();
            var w = dr.GetSnapshotAsync();

            w.Wait();
            Students[studentId] = w.Result;

            if (CurrentClass != newClassName)
            {
                //Remove student from current class
                DocumentReference curClass = db.Collection("classes").Document(Classes[CurrentClass]);
                curClass.UpdateAsync("students", FieldValue.ArrayRemove(studentId)).Wait();

                //add student to new class
                DocumentReference newClass = db.Collection("classes").Document(Classes[newClassName]);
                try
                {
                    newClass.UpdateAsync("students", FieldValue.ArrayUnion(studentId)).Wait();
                }
                catch
                {
                    Dictionary <string, object> fields = new Dictionary <string, object>
                    {
                        { "students", new string[] { studentId } }
                    };
                    newClass.SetAsync(fields).Wait();
                }
            }
        }
Ejemplo n.º 17
0
        public async Task UpdateSection(string username, Section section)
        {
            DocumentReference docRef = db.Collection("sections").Document(section.Id);

            string[] approvedBy = new string[] { username };
            Dictionary <string, object> updates = new Dictionary <string, object> {
                { "Title", section.Title },
                { "Text", section.Text },
                { "ApprovedBy", approvedBy },
                { "ApprovedAt", null }
            };
            await docRef.UpdateAsync(updates);

            await docRef.UpdateAsync("History", FieldValue.ArrayUnion(new HistoryItem {
                Action   = 1,
                ActionBy = username,
                ActionAt = Timestamp.GetCurrentTimestamp()
            }));
        }
Ejemplo n.º 18
0
        //aggiunge un elemento al carrello
        public async Task <WriteResult> AddProductToCart(Product pProduct, string pUserUId, int pQuantitySelect)
        {
            FirestoreDb db   = CreateInstanceDB();
            FirebaseApp wApp = CreateFirebaseApp();

            //per prima cosa viene recuperato il record User a cui è associato
            //un elemento di tipo Map relativo al carrello
            DocumentReference wDocRef  = db.Collection("user").Document(pUserUId);
            DocumentSnapshot  snapshot = await wDocRef.GetSnapshotAsync();

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

            wMapCart.Add("quantita", pQuantitySelect);
            wMapCart.Add("uidProdotto", pProduct.UId);

            WriteResult wWResult = await wDocRef.UpdateAsync("carrello", FieldValue.ArrayUnion(wMapCart));


            return(wWResult);
        }
Ejemplo n.º 19
0
        public void TakeAttendance(IList <string> studentIds, DateTime date)
        {
            string d = date.ToString("MM/dd/yyyy");

            // Make sure that takeAttendance is the last call that happens!!!!!

            // go through all students in this class
            // if they are in the list, add their attendance
            // if not, remove their attendance
            foreach (string studentId in Students.Keys)
            {
                DocumentReference dr = db.Collection("students").Document(studentId);

                DocumentSnapshot snapshot = Students[studentId];

                try
                {
                    snapshot.GetValue <string[]>("attended");
                    if (studentIds.Contains(studentId))
                    {
                        dr.UpdateAsync("attended", FieldValue.ArrayUnion(d)).Wait();
                    }
                    else
                    {
                        dr.UpdateAsync("attended", FieldValue.ArrayRemove(d)).Wait();
                    }
                }
                catch
                {
                    if (studentIds.Contains(studentId))
                    {
                        Dictionary <string, object> update = new Dictionary <string, object>
                        {
                            { "attended", new string[] { d } }
                        };
                        dr.SetAsync(update, SetOptions.MergeAll).Wait();
                    }
                }
            }
            CurrentClass = "";
        }
Ejemplo n.º 20
0
        public void AddTeacher(string teacherName, string teacherPhone, DateTime birthday)
        {
            teacherName  = teacherName ?? "";
            teacherPhone = teacherPhone ?? "";

            string bday = birthday.ToString("MM/dd/yyyy").Substring(0, 5);
            Dictionary <string, object> teacher = new Dictionary <string, object>
            {
                { "teacherName", teacherName },
                { "phone", teacherPhone },
                { "birthday", bday }
            };

            // check if there is a teacher with this name and birthday?
            var w = db.Collection("teachers").AddAsync(teacher);

            w.Wait();
            DocumentReference dr        = w.Result;
            string            teacherId = dr.Id;
            DocumentReference classDoc  = db.Collection("classes").Document(Classes[CurrentClass]);

            try
            {
                classDoc.UpdateAsync("teachers", FieldValue.ArrayUnion(teacherId)).Wait();
            }
            catch
            {
                Dictionary <string, object> t = new Dictionary <string, object>
                {
                    { "teachers", new string[] { teacherId } }
                };
                classDoc.SetAsync(t, SetOptions.MergeAll).Wait();
            }

            var wa = dr.GetSnapshotAsync();

            wa.Wait();
            Teachers.Add(teacherId, wa.Result);
            teacherList.Add(new KeyValuePair <string, string>(teacherId, teacherName));
            teacherList.Sort((a, b) => a.Value.CompareTo(b.Value));
        }
Ejemplo n.º 21
0
        public void EditTeacher(string teacherId, string newClassName, string newTeacherName, string newTeacherPhone, DateTime newBirthday)
        {
            DocumentReference dr = db.Collection("teachers").Document(teacherId);

            Dictionary <string, object> update = new Dictionary <string, object>
            {
                { "teacherName", newTeacherName },
                { "phone", newTeacherPhone },
                { "birthday", newBirthday.ToString("MM/dd/yyyy").Substring(0, 5) }
            };

            dr.SetAsync(update, SetOptions.MergeAll).Wait();
            var w = dr.GetSnapshotAsync();

            w.Wait();
            Teachers[teacherId] = w.Result;

            if (CurrentClass != newClassName)
            {
                //Remove student from current class
                DocumentReference curClass = db.Collection("classes").Document(Classes[CurrentClass]);
                curClass.UpdateAsync("teachers", FieldValue.ArrayRemove(teacherId)).Wait();

                //add student from current class
                DocumentReference newClass = db.Collection("classes").Document(Classes[newClassName]);
                try
                {
                    newClass.UpdateAsync("teachers", FieldValue.ArrayUnion(teacherId)).Wait();
                }
                catch
                {
                    Dictionary <string, object> t = new Dictionary <string, object>
                    {
                        { "teachers", new string[] { teacherId } }
                    };
                    newClass.SetAsync(t, SetOptions.MergeAll).Wait();
                }
            }
        }
Ejemplo n.º 22
0
 public async void AddRecord(string userId, int questionNumber, string className)
 {
     try {
         DocumentReference           docRef = _db.Collection("records").Document(userId);
         Dictionary <string, object> record = new Dictionary <string, object> {
             { "QuestionNumber", questionNumber },
             { "Answer", "" },
             { "ClassName", className }
         };
         DocumentSnapshot document = docRef.GetSnapshotAsync().Result;
         if (document.Exists)
         {
             if (document.GetValue <List <Dictionary <string, object> > > ("list").Count > 0)
             {
                 await docRef.UpdateAsync("list", FieldValue.ArrayUnion(record));
             }
             else
             {
                 await docRef.SetAsync(new { list = new List <Dictionary <string, object> > ()
                                             {
                                                 record
                                             } });
             }
         }
         else
         {
             await docRef.SetAsync(new { list = new List <Dictionary <string, object> > ()
                                         {
                                             record
                                         } });
         }
     } catch (Exception ex) {
         Bot.PushMessage(ex.StackTrace);
         // Bot.Notify (new Exception (new Error (ErrCode.D001, Bot.UserInfo.userId, ex.Message).Message));
     }
 }
Ejemplo n.º 23
0
        public async Task <TwiMLResult> SmsWebhook(SmsRequest request, int numMedia)
        {
            // Is this number in our database?

            var accountsRef   = _db.Collection("accounts");
            var query         = accountsRef.WhereEqualTo("PhoneNumber", request.From);
            var querySnapshot = await query.GetSnapshotAsync();

            DocumentSnapshot?document;

            if (querySnapshot.Count == 0)
            {
                await accountsRef.Document(Guid.NewGuid().ToString())
                .SetAsync(new Dictionary <string, object>()
                {
                    { "PhoneNumber", request.From }
                });

                var snapshot = await query.GetSnapshotAsync();

                document = snapshot.Documents[0];
            }
            else
            {
                document = querySnapshot.Documents[0];
            }

            // Save the message body if there is one
            if (request.Body != null)
            {
                await document.Reference.UpdateAsync("Messages", FieldValue.ArrayUnion(new Dictionary <string, object>()
                {
                    { "Text", request.Body },
                    { "Timestamp", Timestamp.GetCurrentTimestamp() }
                }));
            }


            var filenames = await SaveMedia(numMedia);


            var phone = _context.Phones.FirstOrDefault(x => x.PhoneNumber == request.From);

            if (phone == null)
            {
                phone = new Phone
                {
                    PhoneNumber = request.From,
                    Images      = new List <Models.Image>()
                };
                _context.Phones.Add(phone);
            }

            foreach (var(image, thumbnail) in filenames)
            {
                if (phone.Images == null)
                {
                    phone.Images = new List <Models.Image>();
                }
                phone.Images.Add(new Models.Image
                {
                    Name          = image,
                    ThumbnailName = thumbnail
                });
            }

            _context.SaveChanges();

            var response    = new MessagingResponse();
            var messageBody = numMedia == 0 ? "Send us an image!" :
                              $"Thanks for sending us {numMedia} file(s)!";

            response.Message(messageBody);
            return(TwiML(response));
        }
Ejemplo n.º 24
0
        public async Task <WriteResult> AddMenuCategory(String RestaurantID, String MenuCategory)
        {
            WriteResult writeResult = await Root.Collection("restaurants").Document(RestaurantID).UpdateAsync("MenuCategories", FieldValue.ArrayUnion(MenuCategory));

            return(writeResult);
        }
Ejemplo n.º 25
0
        public async Task <WriteResult> AddFoods(String RestaurantID, Food food)
        {
            WriteResult writeResult = await Root.Collection("restaurants").Document(RestaurantID).UpdateAsync("Foods", FieldValue.ArrayUnion(food));

            return(writeResult);
        }
Ejemplo n.º 26
0
        public void AddStudent(string studentName, string studentPhone, string grade, string parentName, string parentPhone, DateTime birthday)
        {
            // make sure that no fields are null
            studentName  = studentName ?? "";
            studentPhone = studentPhone ?? "";
            grade        = grade ?? "";
            parentName   = parentName ?? "";
            parentPhone  = parentPhone ?? "";

            string bday = birthday.ToString("MM/dd/yyyy").Substring(0, 5);

            Dictionary <string, object> student = new Dictionary <string, object>
            {
                { "studentName", studentName },
                { "studentPhone", studentPhone },
                { "grade", grade },
                { "parentName", parentName },
                { "parentPhone", parentPhone },
                { "birthday", bday }
            };

            // check if there is a student with this name and birthday
            var q = db.Collection("students")
                    .WhereEqualTo("studentName", studentName)
                    .WhereEqualTo("birthday", bday)
                    .GetSnapshotAsync();

            q.Wait();
            if (q.Result.Count != 0)
            {
                return;
            }

            // add the student
            var w = db.Collection("students").AddAsync(student);

            w.Wait();
            DocumentReference dr        = w.Result;
            string            studentId = dr.Id;

            // add them to their class
            DocumentReference classDoc = db.Collection("classes").Document(Classes[CurrentClass]);

            try
            {
                classDoc.UpdateAsync("students", FieldValue.ArrayUnion(studentId)).Wait();
            }
            catch
            {
                Dictionary <string, object> fields = new Dictionary <string, object>
                {
                    { "students", new string[] { studentId } }
                };
                classDoc.SetAsync(fields).Wait();
            }


            var wa = dr.GetSnapshotAsync();

            wa.Wait();

            // Update students lists
            Students.Add(studentId, wa.Result);
            studentList.Add(new KeyValuePair <string, string>(studentId, studentName));
            studentList.Sort((a, b) => a.Value.CompareTo(b.Value));
        }