public static async Task <Solicitud> GetSolicitudFromFireStore(string _ID)
        {
            Solicitud solicitud = new Solicitud();

            try {
                FirestoreDb         db         = conexionDB();
                CollectionReference collection = db.Collection("Solicitudes");
                DocumentReference   docRef     = collection.Document(_ID);
                DocumentSnapshot    document   = await docRef.GetSnapshotAsync();

                if (!document.Exists)
                {
                    collection = db.Collection("Renovaciones");
                    docRef     = collection.Document(_ID);
                    document   = await docRef.GetSnapshotAsync();
                }
                if (document.Exists)
                {
                    solicitud             = document.ConvertTo <Solicitud>();
                    solicitud.solicitudID = _ID;

                    List <Documento> documentosAux = new List <Documento>();
                    foreach (Documento doc in solicitud.documentos)
                    {
                        var aux_doc = documentosAux.Find(x => x.tipo == doc.tipo);
                        if (aux_doc == null)
                        {
                            documentosAux.Add(doc);
                        }
                        else
                        {
                            if (aux_doc.version < doc.version)
                            {
                                documentosAux.Remove(aux_doc);
                                documentosAux.Add(doc);
                            }
                        }
                    }
                    solicitud.documentos = documentosAux;
                }
                else
                {
                    solicitud.grupoNombre = "La solicitud con el id " + _ID + " no existe en la FSDB.\r\nVuelva a cargar la página desde la bandeja, si no se muestra información de la solicitud vuelva a cargar los datos de la bandeja";//Auxiliar para mostrar un mensaje de error
                }
            } catch (Exception ex) {
                solicitud.grupoNombre = ex.Message;//Auxiliar para mostrar un mensaje de error
                Log.Information("*****Error Exception GetSolicitudFromFireStore: {0}", ex.Message);
            }
            return(solicitud);
        }
        public IActionResult Details(string id)
        {
            if (HttpContext.Session.GetString("bt_userToken") != null)
            {
                if (id == null)
                {
                    return(BadRequest());
                }

                DocumentReference docRef   = firestoreDb.Collection("fthTest-users").Document(id);
                DocumentSnapshot  snapshot = docRef.GetSnapshotAsync().GetAwaiter().GetResult();
                if (snapshot.Exists)
                {
                    UserModel usr = snapshot.ConvertTo <UserModel>();
                    usr.Id   = snapshot.Id;
                    usr.date = snapshot.CreateTime.Value.ToDateTime();
                    return(View(usr));
                }
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }
            return(View());
        }
        private static async Task <bool> ValidateConnectionToFirestore(ServerProperties properties)
        {
            string         collectionName = "Test_firestore_collection";
            string         docName        = "Test_firestore_document";
            CredentialList credentialList = FindCredentialsAsset();

            FirestoreDb db = FirestoreDb.Create(GetProjectId(properties, credentialList));

            // Create a document with a random ID in the "Test_firestore_collection" collection.
            CollectionReference collection = db.Collection(collectionName);

            DocumentReference document =
                await collection.AddAsync(new { Name = docName });

            // A DocumentReference doesn't contain the data - it's just a path.
            // Let's fetch the current document.
            DocumentSnapshot snapshot = await document.GetSnapshotAsync();

            string receivedDocName = snapshot.GetValue <string>("Name");

            if (receivedDocName != docName)
            {
                await document.DeleteAsync();

                Debug.LogError($"Could not write a test document to firebase");
                return(false);
            }

            await document.DeleteAsync();

            return(true);
        }
예제 #4
0
    public void GetUserName()
    {
        FirebaseFirestore db = FirebaseFirestore.DefaultInstance;

        DocumentReference docRef = db.Collection("users").Document(userUID);

        docRef.GetSnapshotAsync().ContinueWithOnMainThread(task1 =>
        {
            DocumentSnapshot snapshot = task1.Result;
            if (snapshot.Exists)
            {
                Debug.Log(string.Format("Document data for {0} document:", snapshot.Id));
                Dictionary <string, object> user1 = snapshot.ToDictionary();


                userName   = user1["FirstName"].ToString();
                totalCoins = int.Parse(user1["TotalCoins"].ToString());

                Debug.Log("userName is " + userName);

                Debug.Log("remeberMe.isOn value is " + remeberMe.isOn);
                if (remeberMe.isOn)
                {
                    Debug.Log("in remember me if condition");
                    RememberMe();
                }
                signin = true;
            }
        });
    }
예제 #5
0
        public async Task OnPostAsync()
        {
            FirestoreDb db = FirestoreDb.Create("networking-application");

            DocumentReference userRef  = db.Collection("Post").Document("UserPosts");
            DocumentSnapshot  snapshot = await userRef.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                Dictionary <string, object> userInfo = snapshot.ToDictionary();

                userLabel = userInfo.FirstOrDefault(x => x.Key == "userLabel").Value;
                aboutUser = userInfo.FirstOrDefault(x => x.Key == "aboutUser").Value;

                //for(int i = 1; i <= 6; i++)
                int index = 0;
                while (userInfo.ContainsKey("title" + index))
                {
                    forumTitles.Add(userInfo.FirstOrDefault(x => x.Key == "title" + index).Value.ToString());
                    forumTexts.Add(userInfo.FirstOrDefault(x => x.Key == "forumtext" + index).Value.ToString());
                    numPosts = index + 1;
                    index++;
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Document {0} does not exist!", snapshot.Id);
            }
        }
예제 #6
0
        private async void openPage(String page, String password, String username)
        {
            var driverService = ChromeDriverService.CreateDefaultService();

            driverService.HideCommandPromptWindow = true;
            DocumentReference docRef   = db.Collection("page").Document(page);
            DocumentSnapshot  snapshot = await docRef.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                Dictionary <string, Object> snap = snapshot.ToDictionary();
                ChromeOptions options            = new ChromeOptions();
                options.AddArguments("start-maximized");
                try
                {
                    var driver = new ChromeDriver(driverService, options);
                    driver.Navigate().GoToUrl(snap["domain"].ToString());
                    driver.FindElement(By.Name(snap["userNameFieldID"].ToString())).SendKeys(username);
                    driver.FindElement(By.Name(snap["passwordFieldID"].ToString())).SendKeys(password);
                    driver.FindElement(By.Name(snap["submitButtonID"].ToString())).Click();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        }
예제 #7
0
        /// <summary>
        /// Creates or Inserts (upserts) a Subscriber based on their email
        /// </summary>
        /// <param name="sub"></param>
        /// <returns></returns>
        public async Task UpsertSubscriber(PostedSubscribeObject sub)
        {
            await FirestoreSetup();

            Subscriber s = Subscriber.FromPostedSubscriber(sub);

            try {
                DocumentReference doc = DBHandle.Collection(SUBSCRIBERS).Document(s.DocumentId);
                if (doc != null)
                {
                    DocumentSnapshot ds = await doc.GetSnapshotAsync();

                    if (ds.Exists)
                    {
                        // UPDATE
                        await DBHandle.RunTransactionAsync(async transaction => {
                            transaction.Update(doc, "matches", s.Matches);
                        });

                        return;
                    }
                }
                // CREATE
                await DBHandle.RunTransactionAsync(async transaction => {
                    transaction.Create(doc, s);
                });

                return;
            }
            catch (Exception e) {
                Logger.Log($"Some error ocurred while Upserting a subscriber: {e.Message}");
                // some error ocurred while trying to create or update a subscriber
            }
        }
        public static async Task <bool> SetDefaultRole(ulong guildID, SocketRole role)
        {
            try
            {
                DocumentReference guildDocument = Db.Document(Convert.ToString(guildID)).Collection("lite").Document("data");
                DocumentSnapshot  guildSnapshot = await guildDocument.GetSnapshotAsync();

                guildSnapshot.TryGetValue("defaultRoles", out List <ulong> defaultRoles);

                if (defaultRoles == null)
                {
                    defaultRoles = new List <ulong>();
                }
                if (!defaultRoles.Contains(role.Id))
                {
                    defaultRoles.Add(role.Id);
                }
                else
                {
                    defaultRoles.Remove(role.Id);
                }

                Dictionary <string, List <ulong> > update = new Dictionary <string, List <ulong> > {
                    ["defaultRoles"] = defaultRoles
                };
                WriteResult wrire = await guildDocument.SetAsync(update, SetOptions.MergeAll);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #9
0
        public async Task <Dictionary <string, object> > FindClient(string strIdNumber)
        {
            if (strIdNumber.Equals(""))
            {
                throw new Exception("Por favor ingrese un número de identificación.");
            }
            else
            {
                int identificationNumber;
                try
                {
                    identificationNumber = Int32.Parse(strIdNumber);
                }
                catch (Exception)
                {
                    throw new Exception("Número de identificación invalido.\nPor favor introducir un valor numérico");
                }

                DocumentReference docRef   = db.Collection("clients").Document(strIdNumber);
                DocumentSnapshot  snapshot = await docRef.GetSnapshotAsync();

                if (snapshot.Exists)
                {
                    Dictionary <string, object> client = snapshot.ToDictionary();
                    return(client);
                }
                else
                {
                    throw new Exception("El cliente con el número de identificación " + identificationNumber +
                                        " no ha sido encontrado");
                }
            }
        }
예제 #10
0
        public async Task <IActionResult> PutRecipe(String id, Recipe recipe)
        {
            string path = @"RWPfirebase.json";

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
            // Create a connection to the Firestore Database
            FirestoreDb db = FirestoreDb.Create("recipe-web-app-64a48");
            // Push the recipe data into the existing one to update the recipe
            DocumentReference           docuRef       = db.Collection("RecipeWebApp").Document(id);
            Dictionary <string, object> updatedRecipe = new Dictionary <string, object>
            {
                { "Title", recipe.Title },
                { "Description", recipe.Description },
                { "Image", recipe.Image },
                { "Ingredients", recipe.Ingredients },
                { "Method", recipe.Method }
            };
            // Sanity check to make sure the recipe exists
            DocumentSnapshot snap = await docuRef.GetSnapshotAsync();

            if (snap.Exists)
            {
                await docuRef.SetAsync(updatedRecipe);
            }

            return(NoContent());
        }
예제 #11
0
        public async Task <Shared.Models.Client> GetClientData(string id)
        {
            try
            {
                DocumentReference docRef   = firestoreDb.Collection("Clients").Document(id);
                DocumentSnapshot  snapshot = await docRef.GetSnapshotAsync();

                if (snapshot.Exists)
                {
                    Dictionary <string, object> client = snapshot.ToDictionary();
                    string json = JsonConvert.SerializeObject(client);
                    Shared.Models.Client clientById =
                        JsonConvert.DeserializeObject <Shared.Models.Client>(json);
                    clientById.Id   = snapshot.Id;
                    clientById.Date = snapshot.CreateTime.Value.ToDateTimeOffset();
                    return(clientById);
                }
                else
                {
                    return(new Shared.Models.Client());
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        //public static async Task<List<Solicitud>> GetGrupoFromFireStore(string grupoID){
        public static async Task <GrupoDetalle> GetGrupoFromFireStore(string grupoID)
        {
            GrupoDetalle     grupoDetalle = new GrupoDetalle();
            List <Solicitud> solicitudes  = new List <Solicitud>();

            try{
                FirestoreDb db = conexionDB();

                CollectionReference collection  = db.Collection("Grupos");
                DocumentReference   docRef      = collection.Document(grupoID);
                DocumentSnapshot    documentGpo = await docRef.GetSnapshotAsync();

                if (documentGpo.Exists)
                {
                    grupoDetalle.grupo = documentGpo.ConvertTo <Grupo>();
                }

                Query         capitalQuery         = db.Collection("Solicitudes").WhereEqualTo("grupoID", grupoID);
                QuerySnapshot capitalQuerySnapshot = await capitalQuery.GetSnapshotAsync();

                foreach (DocumentSnapshot document in capitalQuerySnapshot.Documents)
                {
                    Solicitud solicitud = document.ConvertTo <Solicitud>();
                    solicitud.solicitudID = document.Id;
                    solicitudes.Add(solicitud);
                }
            }
            catch (Exception ex) {
                Log.Information("*****Error Exception GetGrupoFromFireStore: {0}", ex.Message);
            }
            grupoDetalle.solicitudes = solicitudes;
            return(grupoDetalle);
        }
        public static async Task <Renovacion> GetRenovacionFromFireStore(string _ID)
        {
            Renovacion solicitud = new Renovacion();

            try
            {
                FirestoreDb         db         = conexionDB();
                CollectionReference collection = db.Collection("Renovaciones");
                DocumentReference   docRef     = collection.Document(_ID);
                DocumentSnapshot    document   = await docRef.GetSnapshotAsync();

                if (document.Exists)
                {
                    solicitud             = document.ConvertTo <Renovacion>();
                    solicitud.solicitudID = _ID;
                }
                else
                {
                    solicitud.grupoNombre = "La solicitud con el id " + _ID + " no existe en la FSDB.\r\nVuelva a cargar la página desde la bandeja, si no se muestra información de la solicitud vuelva a cargar los datos de la bandeja";
                }
            }
            catch (Exception ex)
            {
                solicitud.grupoNombre = ex.Message;//Auxiliar para mostrar un mensaje de error
                Log.Information("*****Error Exception GetRenovacionFromFireStore: {0}", ex.Message);
            }
            return(solicitud);
        }
예제 #14
0
        private async Task <bool> GetEnoughTimePassedAsync(ulong userId, DateTimeOffset msgTimestamp)
        {
            List <DocumentReference> recentMsgs = await _database.Collection($"players/{userId}/recent-messages").ListDocumentsAsync().ToListAsync();

            DocumentReference mostRecentMsg = recentMsgs.Count > 0 ? recentMsgs.ElementAt(0) : null;

            if (mostRecentMsg is null)
            {
                return(true);
            }

            else
            {
                foreach (var msg in recentMsgs)
                {
                    if ((await msg.GetSnapshotAsync()).GetValue <DateTimeOffset>("create-time") < (await mostRecentMsg.GetSnapshotAsync()).GetValue <DateTimeOffset>("create-time"))
                    {
                        mostRecentMsg = msg;
                    }
                }
            }

            var createTime = (await mostRecentMsg.GetSnapshotAsync()).GetValue <DateTimeOffset>("create-time");

            return(msgTimestamp - createTime > TimeSpan.FromSeconds(1.0));
        }
        public static async Task <bool> GetAuthStatusFor(ulong guildID)
        {
            // if successful auth cached, do not recheck database
            if (_guildAuthorized.GetValueOrDefault(guildID))
            {
                return(true);
            }

            // if it's been less than X seconds and failed auth cached, do not recheck database
            if (_guildLastChecked.ContainsKey(guildID) &&
                (DateTime.UtcNow - _guildLastChecked[guildID]).Duration() < TimeSpan.FromSeconds(_checkintInterval))
            {
                return(false);
            }

            DocumentReference guildDocument         = Db.Document(Convert.ToString(guildID)).Collection("lite").Document("data");
            DocumentSnapshot  guildDocumentSnapshot = await guildDocument.GetSnapshotAsync();

            if (guildDocumentSnapshot.Exists)
            {
                bool authorizeFetched;
                bool isAuthorized = guildDocumentSnapshot.TryGetValue("authorized", out authorizeFetched);

                _guildAuthorized[guildID]  = authorizeFetched && isAuthorized;
                _guildLastChecked[guildID] = DateTime.UtcNow;
                return(authorizeFetched && isAuthorized);
            }

            return(false);
        }
        public async Task <IActionResult> Get()
        {
            // Create a document with a random ID in the "cities" collection.
            //CollectionReference collection = fireStoreDb.Collection("prevent-fraud");
            //var response = new Response() { Ok = true };
            //await collection.Document("456").CreateAsync(response);

            // Update
            //DocumentReference empRef = fireStoreDb.Collection("prevent-fraud").Document("12345");
            //await empRef.SetAsync(response, SetOptions.Overwrite);


            //DocumentReference document = await collection.AddAsync(city);

            //CollectionReference colRef = fireStoreDb.Collection("prevent-fraud");
            //DocumentReference londonFromDb = fireStoreDb.Document("cities/london");

            //await collection.Document("los-angeles").CreateAsync(city);
            //await colRef.AddAsync(city);

            // Read
            DocumentReference docRef   = fireStoreDb.Collection("prevent-fraud").Document("12345");
            DocumentSnapshot  snapshot = await docRef.GetSnapshotAsync();

            var resp = snapshot.ConvertTo <Response>();

            return(Ok(resp));
        }
        public static async Task <List <ulong> > GetChannelmodsFor(ulong guildID, ISocketMessageChannel channel)
        {
            CollectionReference channelCollection = Db.Document(Convert.ToString(guildID)).Collection("channels");

            DocumentReference channelDoc = channelCollection.Document(Convert.ToString(channel.Id));
            DocumentSnapshot  channelSettingsSnapshot = await channelDoc.GetSnapshotAsync();

            if (channelSettingsSnapshot.Exists)
            {
                Dictionary <string, object> dict = channelSettingsSnapshot.ToDictionary();

                if (dict.ContainsKey("mods"))
                {
                    List <object> mods = dict["mods"] as List <object>;

                    List <ulong> casted = new List <ulong>();
                    foreach (object id in mods)
                    {
                        casted.Add(Convert.ToUInt64(id));
                    }

                    return(casted);
                }
            }

            return(new List <ulong>());
        }
예제 #18
0
        public static async Task AssertExpectedDocument(DocumentReference doc,
                                                        Dictionary <string, object> expected)
        {
            var snap = await doc.GetSnapshotAsync();

            Assert.That(snap.ToDictionary(), Is.EquivalentTo(expected));
        }
        public static async Task <bool> SetSelfassignable(ulong guildID, string code, SocketRole role)
        {
            try
            {
                DocumentReference guildDocument = Db.Document(Convert.ToString(guildID)).Collection("lite").Document("data");
                DocumentSnapshot  guildSnapshot = await guildDocument.GetSnapshotAsync();

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

                if (selfAssignables == null)
                {
                    selfAssignables = new Dictionary <string, object>();
                }

                if (selfAssignables.ContainsKey(code) && role == null)
                {
                    selfAssignables[code] = null;
                }
                else
                {
                    selfAssignables[code] = role.Id;
                }

                Dictionary <string, Dictionary <string, object> > update = new Dictionary <string, Dictionary <string, object> > {
                    ["selfAssignable"] = selfAssignables
                };
                WriteResult wrire = await guildDocument.SetAsync(update, SetOptions.MergeAll);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #20
0
        public async Task <ActionResult> Submit()
        {
            try
            {
                string patientAutoId     = TempData["patientAutoId"].ToString();
                string appointmentAutoId = TempData["appointmentAutoId"].ToString();

                string Path = AppDomain.CurrentDomain.BaseDirectory + @"greenpaperdev-firebase-adminsdk-8k2y5-fb46e63414.json";
                Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Path);
                FirestoreDb db = FirestoreDb.Create("greenpaperdev");

                DocumentReference docRef  = db.Collection("clinics").Document(GlobalSessionVariables.ClinicDocumentAutoId).Collection("appointments").Document(appointmentAutoId);
                DocumentSnapshot  docSnap = await docRef.GetSnapshotAsync();

                if (docSnap.Exists)
                {
                    Dictionary <string, object> data1 = new Dictionary <string, object>
                    {
                        { "completiondateChemist", DateTime.UtcNow },
                        { "statusChemist", "Completed" }
                    };

                    //await docRef.UpdateAsync( "completionMedicine",DateTime.UtcNow);
                    await docRef.UpdateAsync(data1);
                }
                // TODO: Add delete logic here

                return(RedirectToAction("Index", "Appointment"));
            }
            catch
            {
                return(View());
            }
        }
예제 #21
0
        /// <summary>
        /// Gets the last known Scan Data object
        /// </summary>
        /// <returns></returns>
        public async Task <ScanData> GetScanData()
        {
            await FirestoreSetup();

            ScanData sd = null;

            try {
                ScanDataReference = DBHandle.Document(SCANDATA);
                if (ScanDataReference == null)
                {
                    // ScanData vanished - create a new one.
                    return(await CreateScanData());
                }
                DocumentSnapshot scanDataSnapshot = await ScanDataReference.GetSnapshotAsync();

                if (scanDataSnapshot.Exists)
                {
                    sd = scanDataSnapshot.ConvertTo <ScanData>();
                }
                else
                {
                    Logger.Log("No Scan Data was found, creating a new one and will pick up next invocation");
                    return(await CreateScanData());
                }
            }
            catch (Exception e) {
                Logger.Log("An unknown error ocurred while fetching Scan Data. Aborting.");
                // Some error occurred.
            }
            return(sd);
        }
예제 #22
0
    // See b/174676322 for why this test is added.
    public IEnumerator TestMultipleDeletesInOneUpdate() {
      DocumentReference doc = TestDocument();
      var setTask = doc.SetAsync(new Dictionary<string, object> {
        { "key1", "value1" },
        { "key2", "value2" },
        { "key3", "value3" },
        { "key4", "value4" },
        { "key5", "value5" },
      });
      yield return AwaitSuccess(setTask);

      var updateTask = doc.UpdateAsync(new Dictionary<string, object> {
        { "key1", FieldValue.Delete },
        { "key3", FieldValue.Delete },
        { "key5", FieldValue.Delete },
      });
      yield return AwaitSuccess(updateTask);

      var getTask = doc.GetSnapshotAsync(Source.Cache);
      yield return AwaitSuccess(getTask);
      DocumentSnapshot snapshot = getTask.Result;
      var expected = new Dictionary<string, object> {
        { "key2", "value2" },
        { "key4", "value4" },
      };
      Assert.That(snapshot.ToDictionary(), Is.EquivalentTo(expected));
    }
예제 #23
0
        async void Add_Document_with_orden()
        {
            DocumentReference docRef   = database.Collection("Revisiones").Document(txtorden.Text);
            DocumentSnapshot  snapshot = await docRef.GetSnapshotAsync();

            if (snapshot.Exists)
            {
                MessageBox.Show("Repetido");
            }
            else
            {
                DocumentReference           DOC   = database.Collection("Revisiones").Document(txtorden.Text);
                Dictionary <String, Object> data1 = new Dictionary <string, object>()
                {
                    { "Nombre", txtnombre.Text },

                    { "Numero", txtnumero.Text },

                    { "Modelo", txtmarca.Text + " " + txtmodelo.Text },

                    { "Descripcion", txtdescripcion.Text },

                    { "Accesorios", Accesorios },

                    { "Tiempo de espera", tiemporespuesta },

                    { "Fecha y Hora", txthorayfecha.Text }
                };
                await DOC.SetAsync(data1, SetOptions.MergeAll);

                MessageBox.Show("guardado");
            }
        }
        //This method retruns the user selected question at the time of the registration
        public async Task <string> getUserQuestion(string email)
        {
            string security_question = "";

            try
            {
                Boolean connectionResult = connectToFirebase();
                if (connectionResult)
                {
                    DocumentReference docRef1  = db.Collection("User").Document(email);
                    DocumentSnapshot  docSnap1 = await docRef1.GetSnapshotAsync();

                    User userObj = docSnap1.ConvertTo <User>();
                    DocumentReference docRef2  = db.Collection("Questions").Document(userObj.questionSelected.ToString());
                    DocumentSnapshot  docSnap2 = await docRef2.GetSnapshotAsync();

                    DBQuestions question = docSnap2.ConvertTo <DBQuestions>();
                    security_question = question.question;
                }
                return(security_question);
            }
            catch (Exception ex)
            {
                //catch the exception and throw the error on the client
                CustomException customException = new CustomException();
                customException.errorTitleName     = ex.Message;
                customException.errorMessageToUser = "******";
                throw new FaultException <CustomException>(customException);
            }
        }
예제 #25
0
        public async Task <WashDbModel> GetRecentByWashIdAsync(string washId)
        {
            if (string.IsNullOrEmpty(washId))
            {
                return(null);
            }

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

            if (snapshot.Exists)
            {
                Dictionary <string, object> dictionary = snapshot.ToDictionary();

                return(new WashDbModel()
                {
                    Id = snapshot.Id,
                    UserId = _crypto.Decrypt(dictionary["UserId"].ToString(), "J2uEDdYPYG4h996V"),
                    StartTime = Convert.ToDateTime(dictionary["StartTime"].ToString().Replace("Timestamp: ", "")),
                    Type = int.Parse(dictionary["Type"].ToString()),
                    Duration = int.Parse(dictionary["Duration"].ToString()),
                    Done = bool.Parse(dictionary["Done"].ToString())
                });
            }

            return(null);
        }
        public async Task <bool> verifyAnswer(string email, string userAnswer)
        {
            Boolean connectionResult = connectToFirebase();

            try
            {
                DocumentReference docRef1  = db.Collection("User").Document(email);
                DocumentSnapshot  docSnap1 = await docRef1.GetSnapshotAsync();

                User userObj = docSnap1.ConvertTo <User>();
                if (userAnswer.Equals(userObj.questionAnswered))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                CustomException customException = new CustomException();
                customException.errorTitleName     = "Cannot Verify Your Answer,Please Try Again later!!";
                customException.errorMessageToUser = ex.Message;
                throw new FaultException <CustomException>(customException);
            }
        }
예제 #27
0
        public async Task modificarAsync()
        {
            String documentoBuscar = txtDocumentoBuscar.Text;



            //Query dato1 = db.Collection("Paciente").WhereEqualTo("documento", documentoBuscar);
            DocumentReference           reference = db.Collection("Paciente").Document(documentoBuscar);
            Dictionary <string, object> data1     = new Dictionary <string, object>()
            {
                { "documento", txtDocumento.Text },
                { "nombre", txtNombre.Text },
                { "correo", txtCorreo.Text },
                { "telefono", txtTelefono.Text },
                { "genero", txtGenero.Text },
            };

            DocumentSnapshot snap = await reference.GetSnapshotAsync();

            MessageBox.Show("Paciente modificado");

            if (snap.Exists)
            {
                await reference.SetAsync(data1);
            }
        }
        public async Task <bool> isUnique(string email)
        {
            bool isUnique = false;

            try
            {
                Boolean connection_result = connectToFirebase();
                if (connection_result)
                {
                    //Query to check whether the account with same acoount name exists or not
                    DocumentReference documentReference = db.Collection("User").Document(email);
                    DocumentSnapshot  snapshot          = await documentReference.GetSnapshotAsync();

                    if (snapshot.Exists)
                    {
                        isUnique = false;
                    }
                    else
                    {
                        isUnique = true;
                    }
                }
                return(isUnique);
            }
            catch (Exception ex)
            {
                CustomException customException = new CustomException();
                customException.errorTitleName     = "Cannot Check whether you are unique or not ,Please Try Again later!!";
                customException.errorMessageToUser = ex.Message;
                throw new FaultException <CustomException>(customException);
            }
        }
예제 #29
0
        public async void getSnapshot()
        {
            DocumentReference docRef   = db.Collection("users").Document("userID");
            DocumentSnapshot  snapshot = await docRef.GetSnapshotAsync();

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

                Dictionary <string, object> movie = snapshot.ToDictionary();
                foreach (KeyValuePair <string, object> pair in movie)
                {
                    Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
                    switch (pair.Key)
                    {
                    case "profilePic":
                        BitmapImage profileImg = new BitmapImage();
                        profileImg.BeginInit();
                        profileImg.UriSource = new Uri(pair.Value.ToString());
                        profileImg.EndInit();
                        profileImage.Source = profileImg;
                        break;

                    case "bio":
                        profileBio.Text = "Bio: " + pair.Value.ToString();
                        break;
                    }
                }
            }
            else
            {
                Console.WriteLine("Document {0} does not exist!", snapshot.Id);
            }
        }
예제 #30
0
        async private void ctrlHome_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("home").Document("drlmPXCpRvfPmsEx2r0p");
            documentSnapshot  = await documentReference.GetSnapshotAsync();

            try
            {
                loadImage();
            }
            catch
            {
                imgHome.Image = null;
                MessageBox.Show("Nenhuma imagem encontrada");
            }

            lbRight.Parent    = imgHome;
            lbRight.BackColor = Color.Transparent;
            lbLeft.Parent     = imgHome;
            lbLeft.BackColor  = Color.Transparent;
        }