Beispiel #1
0
        public async Task <ActionResult> Index(Account acc)
        {
            await initialDB();

            if (acc.password == acc.confirmPassword)
            {
                Query query = db.Collection("users")
                              .WhereEqualTo("username", acc.username);
                QuerySnapshot snapshots = await query.GetSnapshotAsync();

                foreach (DocumentSnapshot doc in snapshots)
                {
                    //User Exists
                    ViewBag.error = "User Exists. Try again!";
                    return(View("Index"));
                }

                CollectionReference         collection = db.Collection("users");
                Dictionary <string, object> data       = new Dictionary <string, object>()
                {
                    { "id", DateTime.Now.ToBinary().ToString() },
                    { "username", acc.username },
                    { "password", acc.password },
                };
                await collection.AddAsync(data);

                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                //Not Compare
                ViewBag.error = "Don't match";
                return(View("Index"));
            }
        }
Beispiel #2
0
        public async Task <Cobranca> Add(Cobranca cobranca)
        {
            CollectionReference colRef = fireStoreDb.Collection(collectionName);
            await colRef.AddAsync(cobranca);

            return(cobranca);
        }
        public async Task <IActionResult> Post([FromBody] PostMessage request)
        {
            // Unpack the message from Pubsub.
            string sourceText;

            try
            {
                byte[] data = Convert.FromBase64String(request.message.data);
                sourceText = Encoding.UTF8.GetString(data);
            }
            catch (Exception e)
            {
                _logger.LogError(1, e, "Bad request");
                return(BadRequest());
            }
            // Translate the source text.
            _logger.LogDebug(2, "Translating {0} to Spanish.", sourceText);
            var result = await _translator.TranslateTextAsync(sourceText, "es");

            // Store the result in Firestore.
            Translation translation = new Translation()
            {
                TimeStamp      = DateTime.UtcNow,
                SourceText     = sourceText,
                TranslatedText = result.TranslatedText
            };

            _logger.LogDebug(3, "Saving translation {0} to {1}.",
                             translation.TranslatedText, _translations.Path);
            await _translations.AddAsync(translation);

            // Return a success code.
            return(NoContent());
        }
Beispiel #4
0
        public async void UploadRepair(
            string serviceName,
            AddRepairBindingModel repair)
        {
            FirestoreDb db = connection.GetFirestoreDb();

            CollectionReference repairsColRef = db
                                                .Collection("service-repairs");

            DateTime endOfWarranty = new DateTime(
                repair.BoughtAt.Year + repair.WarrantyPeriod / 12,
                repair.BoughtAt.Month, repair.BoughtAt.Day);

            repair.InWarranty =
                DateTime.UtcNow >= repair.BoughtAt &&
                DateTime.UtcNow <= endOfWarranty ? true : false;

            Repair repairModel = new Repair(repair);

            await repairsColRef.AddAsync(repairModel);

            //await db.RunTransactionAsync(async transaction => {
            //	UpdateRepairId(serviceName, repair.RepairId);
            //
            //});
        }
Beispiel #5
0
 /*
  * Firestore'a doküman olarak yeni bir oyuncu ekleyen fonksiyonumuz
  */
 public async void NewPlayer(Player player)
 {
     // players koleksiyonuna ait referansı al
     CollectionReference collRef = db.Collection("players");
     // awaitable AddAsync metodu ile ekle
     await collRef.AddAsync(player);
 }
Beispiel #6
0
        public async Task PostRoutesToFirestore([FromBody] RouteViewModel routeData)
        {
            if (routeData != null)
            {
                CollectionReference collectionReference = db.Collection("RouteList");
                string routeDataFromFrontEnd            = routeData.RouteDescription;
                string zone = "N/A";
                client = new FireSharp.FirebaseClient(config);
                StringReader reader = new StringReader(routeDataFromFrontEnd);
                while ((routeDataFromFrontEnd = reader.ReadLine()) != null)
                {
                    string[] cxLine = routeDataFromFrontEnd.Split("\t");
                    zone = cxLine[2] == null || cxLine[2] == "" ? zone : cxLine[2].ToString();
                    RouteModel routeModel = new RouteModel();

                    routeModel.Dsp    = cxLine[0];
                    routeModel.Zone   = zone;
                    routeModel.Status = "waiting".ToUpper();
                    routeModel.Cx     = cxLine[3];
                    routeModel.Name   = NameParser(cxLine[4]);
                    routeModel.Wave   = Int32.Parse(routeData.Wave);
                    try
                    {
                        await collectionReference.AddAsync(routeModel);
                    }
                    catch (Exception e)
                    {
                        string s = e.ToString();
                    }
                }
                ;
            }
        }
        //public async Task<List<string>> GetDatabases()
        //{
        //    var client = new MongoClient(_config.AtlasMongoConnection);
        //    List<string> databases = new List<string>();

        //    using (var cursor = await client.ListDatabasesAsync())
        //    {
        //        await cursor.ForEachAsync(d => databases.Add(d.ToString()));
        //    }
        //    return databases;
        //}
        //public async Task<List<string>> GetCollections(string database)
        //{
        //    var client = new MongoClient(_config.AtlasMongoConnection);
        //    List<string> collections = new List<string>();

        //    using (var cursor = await client.GetDatabase(database).ListCollectionsAsync())
        //    {
        //        await cursor.ForEachAsync(d => collections.Add( new JObject(new JProperty("name",d["name"].ToString())).ToString()));
        //    }
        //    return collections;
        //}
        public async Task <Repository> Create(string repository, string collection, Repository repoObject)
        {
            if (repoObject.validate)
            {
                ValidateInnerDataAgainstSchema(repoObject.schemaUri, repoObject.data);
            }

            GoogleCredential serviceAcct = GoogleCredential.FromJson(GetServiceAccountKey()); //hardcoded

            Channel channel = new Channel(
                FirestoreClient.DefaultEndpoint.Host, FirestoreClient.DefaultEndpoint.Port,
                serviceAcct.ToChannelCredentials());

            FirestoreClient client = FirestoreClient.Create(channel);

            FirestoreDb         db = FirestoreDb.Create("repositorynookproject", client);
            CollectionReference c  = GetCollection(db, collection);


            //convert times to UTC
            repoObject.createdDate  = DateTime.SpecifyKind(repoObject.createdDate, DateTimeKind.Utc);
            repoObject.modifiedDate = DateTime.SpecifyKind(repoObject.modifiedDate, DateTimeKind.Utc);

            DocumentReference document = await c.AddAsync(repoObject);

            return(repoObject);
        }
Beispiel #8
0
        public ActionResult Create(SuperUser superuser)
        {
            string Path = AppDomain.CurrentDomain.BaseDirectory + @"greenpaperdev-firebase-adminsdk-8k2y5-fb46e63414.json";

            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Path);
            FirestoreDb db = FirestoreDb.Create("greenpaperdev");


            try
            {
                CollectionReference         col1  = db.Collection("SuperUsers");
                Dictionary <string, object> data1 = new Dictionary <string, object>
                {
                    { "UserId", superuser.UserId },
                    { "UserName", superuser.UserName },
                    { "Password", superuser.Password }
                };

                col1.AddAsync(data1);


                // TODO: Add insert logic here
                //var result = await fireBaseClient.Child("Students").PostAsync(std);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Beispiel #9
0
        public async Task UploadLog(RepairLog log)
        {
            FirestoreDb db =
                connection.GetFirestoreDb();

            CollectionReference colRef = db
                                         .Collection("activity-log");

            DocumentReference docRef = null;

            Dictionary <string, object> repairIdDoc =
                new Dictionary <string, object>()
            {
                { "RepairId", log.RepairId }
            };

            await db.RunTransactionAsync(async t => {
                docRef = await colRef.AddAsync(repairIdDoc);
            });

            CollectionReference subDocRef =
                docRef.Collection("logs");

            await db.RunTransactionAsync(async t => {
                await subDocRef.AddAsync(log);
            });
        }
        public async Task <Cliente> Add(Cliente cliente)
        {
            CollectionReference colRef = fireStoreDb.Collection(collectionName);
            await colRef.AddAsync(cliente);

            return(cliente);
        }
Beispiel #11
0
        private async Task <int> updateVendorDb(string vendorName)
        {
            CollectionReference coll = db.Collection("vendor");

            Query query  = coll.WhereEqualTo("vendor_name", vendorName);
            Query query2 = coll.OrderByDescending("vendor_id").Limit(1);

            QuerySnapshot snap = await query.GetSnapshotAsync();

            QuerySnapshot snap2 = await query2.GetSnapshotAsync();

            int id = snap2.Documents[0].ConvertTo <Vendor>().vendor_id;

            if (snap.Documents.Count == 0)
            {
                id = id + 1;

                Dictionary <string, object> data = new Dictionary <string, object>()
                {
                    { "vendor_id", id },
                    { "vendor_name", vendorName }
                };

                await coll.AddAsync(data);

                return(id);
            }

            Vendor vendor = snap.Documents[0].ConvertTo <Vendor>();

            return(vendor.vendor_id);
        }
        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);
        }
        public T Add <T>(T record) where T : Base
        {
            CollectionReference colRef = fireStoreDb.Collection(collectionName);
            DocumentReference   doc    = colRef.AddAsync(record).GetAwaiter().GetResult();

            record.Id = doc.Id;
            return(record);
        }
Beispiel #14
0
        public async System.Threading.Tasks.Task EnviarAlaNubeAsync(MessageQueue cola, FirestoreDb db)
        {
            CollectionReference collection = db.Collection("Archivos");
            String            archivo      = Recibir(cola);
            DocumentReference document     = await collection.AddAsync(new { Archivo = archivo });

            DocumentSnapshot snapshot = await document.GetSnapshotAsync();
        }
        public async Task CreateAsync(Book book)
        {
            // Firestore expects all times to be UTC.
            book.PublishedDate = book.PublishedDate?.ToUniversalTime();
            DocumentReference docRef = await _books.AddAsync(book);

            book.Id = docRef.Id;
        }
Beispiel #16
0
        /// <inheritdoc/>
        public async Task <Bookmark> AddBookmarkAsync(Bookmark bookmark)
        {
            DocumentReference bookmarkDocument = await _bookmarksCollection.AddAsync(bookmark);

            bookmark.AddDocumentReference(bookmarkDocument);

            return(bookmark);
        }
Beispiel #17
0
        private async void FirebaseSave()
        {
            //MessageBox.Show(db.ToString());
            // Create a document with a ramdom ID in the "Product" collection
            // A DocumentReference doen't contain the data -it's just a path
            // let fetch the current document
            //DocumentSnapshot snapshot = await document.GetSnapshotAsync();
            //txtName.Text = snapshot.GetValue<string>("Name");
            //txtDetail.Text = snapshot.GetValue<string>("Detail");
            //txtPath.Text = snapshot.GetValue<string>("PathImage");
            //pictureBox1.ImageLocation = txtPath.Text;

            /*
             * new
             *      {
             *              Name = txtName.Text.ToUpper().Trim(),
             *              Detail = txtDetail.Text.Trim(),
             *              PathImage = txtPath.Text.Trim(),
             *              Image = FSBHelper.ConvertImageToBase64(ImageBox.Image)
             *      }
             *
             *      ProductRecord p = new ProductRecord
             *      {
             *              Id = _document,
             *              Name = txtName.Text.Trim(),
             *              Detail = txtDetail.Text.Trim(),
             *              PathImage = txtPath.Text.Trim(),
             *              Image = FSBHelper.ConvertImageToBase64(ImageBox.Image)
             *      };
             */

            // test upload file
            //UploadImageToFireStore();


            CollectionReference collectionReference = db.Collection("Product");

            if (_mode == ActionMode.Add)
            {
                DocumentReference document = await collectionReference.AddAsync(p);
            }
            else if (_mode == ActionMode.Edit)
            {
                Dictionary <FieldPath, object> updates = new Dictionary <FieldPath, object>
                {
                    { new FieldPath("Name"), p.Name },
                    { new FieldPath("Detail"), p.Detail },
                    { new FieldPath("PathImage"), p.PathImage },
                    { new FieldPath("Image"), p.Image }
                };

                await collectionReference.Document(_document).UpdateAsync(updates);

                //DocumentReference docRef =
                //db.Collection("Product").Document(_document);
                //await docRef.SetAsync(p);
            }
        }
Beispiel #18
0
 RunTransaction(
     WarehousePart newPart,
     CollectionReference colRef)
 {
     await colRef.Database
     .RunTransactionAsync(async transaction => {
         await colRef.AddAsync(newPart);
     });
 }
Beispiel #19
0
 async Task addDataToFirestore()
 {
     CollectionReference         collection = db.Collection("cars");
     Dictionary <string, object> data       = new Dictionary <string, object>()
     {
         { "id", "1234" },
     };
     await collection.AddAsync(data);
 }
Beispiel #20
0
        public async void UploadRepair(
            string serviceName,
            AddRepairBindingModel repair)
        {
            FirestoreDb db = connection.GetFirestoreDb();

            CollectionReference repairsColRef = db
                                                .Collection("service-repairs");

            Repair repairModel = new Repair(repair);

            if (repairModel.BoughtAt.Day == 29 &&
                repairModel.BoughtAt.Month == 2)
            {
                int warrantyInYears = repairModel.WarrantyPeriod / 12;

                if (warrantyInYears % 4 == 0)
                {
                    repairModel.WarrantyExpiresOn =
                        repairModel.BoughtAt.AddYears(warrantyInYears);
                }
                else
                {
                    repairModel.WarrantyExpiresOn =
                        repairModel.BoughtAt.AddYears(warrantyInYears)
                        .AddDays(1);
                }
            }
            else
            {
                int warrantyInYears = repairModel.WarrantyPeriod / 12;

                repairModel.WarrantyExpiresOn =
                    repairModel.BoughtAt.AddYears(warrantyInYears);
            }

            await db
            .RunTransactionAsync(async transaction => {
                UpdateRepairId(serviceName,
                               repairModel.RepairId);

                await repairsColRef.AddAsync(repairModel);
            });

            RepairLog log = new RepairLog()
            {
                TimeOfEvent = DateTime.UtcNow,
                RepairId    = repairModel.RepairId,
                TypeOfEvent = "create",
                Status      = repairModel.RepairStatus,
                Description = $"Add repair with id {repairModel.RepairId}"
            };

            UploadLog(log);
        }
Beispiel #21
0
        public async Task <BlogPost> AddBlogPost(BlogPost blogPost)
        {
            // add document to collection to get a ref
            var blogPostRef = await _blogPostsCollection.AddAsync(blogPost);

            // get a snapshot of the ref
            var snapshot = await blogPostRef.GetSnapshotAsync();

            // convert to model
            return(snapshot.ConvertTo <BlogPost>());
        }
Beispiel #22
0
        private async Task Insert()
        {
            FirestoreDb         db          = FirestoreDb.Create(ProjectID);
            CollectionReference policlinics = db.Collection("policlinics");
            var clinics = await Clinics.GetPoliclinicsAsync();

            clinics.ForEach(async clinic =>
            {
                await policlinics.AddAsync(clinic);
            });
        }
Beispiel #23
0
        public async void AddTodoTask(TodoTask task)
        {
            CollectionReference collection =
                firestoreDb.Collection("tasks");

            task.CreatedAt = DateTime.SpecifyKind(
                DateTime.Now,
                DateTimeKind.Utc
                );

            DocumentReference dr = await collection.AddAsync(task);
        }
 public async void AddEmployee(Employee employee)
 {
     try
     {
         CollectionReference colRef = fireStoreDb.Collection("employees");
         await colRef.AddAsync(employee);
     }
     catch
     {
         throw;
     }
 }
 public async void AddContact(ContactUs contact)
 {
     try
     {
         CollectionReference colRef = fireStoreDb.Collection("contact-us");
         await colRef.AddAsync(contact);
     }
     catch
     {
         throw;
     }
 }
 public async void AddMedic(Medic Medic)
 {
     try
     {
         CollectionReference colRef = fireStoreDb.Collection("Medics");
         await colRef.AddAsync(Medic);
     }
     catch
     {
         throw;
     }
 }
 public async void AddUser(Users user)
 {
     try
     {
         CollectionReference colRef = fireStoreDb.Collection("users");
         await colRef.AddAsync(user);
     }
     catch
     {
         throw;
     }
 }
Beispiel #28
0
        public async Task UploadLog(RepairLog log)
        {
            FirestoreDb db =
                connection.GetFirestoreDb();

            CollectionReference colRef = db
                                         .Collection("activity-log");

            await db.RunTransactionAsync(async t => {
                await colRef.AddAsync(log);
            });
        }
Beispiel #29
0
 public async void AddCareer(Career career)
 {
     try
     {
         CollectionReference colRef = fireStoreDb.Collection("career");
         await colRef.AddAsync(career);
     }
     catch
     {
         throw;
     }
 }
 public async void AddRewards(Rewards obj)
 {
     try
     {
         CollectionReference colRef = fireStoreDb.Collection("rewards");
         await colRef.AddAsync(obj);
     }
     catch
     {
         throw;
     }
 }