예제 #1
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);
            });
        }
예제 #2
0
        public async Task <SharedDocumentData[]> getSharedDocument(string email)
        {
            int     sharedDocumentCount = 0;
            Boolean connectionResult    = connectToFirebase();

            DocumentReference documentReference = db.Collection("SharedDocuments").Document(email);
            IAsyncEnumerable <CollectionReference> collectionRefrences = documentReference.ListCollectionsAsync();
            IAsyncEnumerator <CollectionReference> enumerator          = collectionRefrences.GetAsyncEnumerator();

            while (await enumerator.MoveNextAsync())
            {
                CollectionReference collectionReference = enumerator.Current;
                Query         allDocumentsQuery         = documentReference.Collection(collectionReference.Id);
                QuerySnapshot snaps = await allDocumentsQuery.GetSnapshotAsync();


                foreach (DocumentSnapshot snap in snaps)
                {
                    sharedDocumentCount++;
                }
            }


            SharedDocumentData[] sharedDocuments = new SharedDocumentData[sharedDocumentCount];

            IAsyncEnumerator <CollectionReference> enumerator1 = collectionRefrences.GetAsyncEnumerator();
            int i = 0;

            while (await enumerator1.MoveNextAsync())
            {
                CollectionReference collectionReference = enumerator1.Current;
                Query         allDocumentsQuery         = documentReference.Collection(collectionReference.Id);
                QuerySnapshot snaps = await allDocumentsQuery.GetSnapshotAsync();


                foreach (DocumentSnapshot snap in snaps)
                {
                    DBSharedDocumentData dBSharedDocumentData = snap.ConvertTo <DBSharedDocumentData>();
                    sharedDocuments[i]          = new SharedDocumentData();
                    sharedDocuments[i].fileName = dBSharedDocumentData.fileName;
                    sharedDocuments[i].fileLink = dBSharedDocumentData.fileLink;
                    sharedDocuments[i].sharedBy = dBSharedDocumentData.sharedBy;
                    i++;
                }
            }
            return(sharedDocuments);
        }
예제 #3
0
        public async Task Save(CalendarViewModel calendarViewModel, string userId, string userName)
        {
            var filePath = Path.GetTempFileName();
            // ReSharper disable once RedundantAssignment
            string downloadUrl = "";
            var    file        = calendarViewModel.Image;

            if (file != null)
            {
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    file.CopyTo(stream);
                }
                var str  = File.Open(filePath, FileMode.Open);
                var task = new FirebaseStorage("timetracker-5c762.appspot.com", new FirebaseStorageOptions())
                           .Child(file.FileName)
                           .PutAsync(str);
                downloadUrl = await task;
                str.Dispose();
                File.Delete(filePath);
            }
            else if (calendarViewModel.DownloadUrl != null)
            {
                downloadUrl = calendarViewModel.DownloadUrl;
            }

            DocumentReference tasksRef;
            var usersRef = db.Collection("users").Document(userId);
            await usersRef.SetAsync(new
            {
                Name = userName
            });

            if (calendarViewModel.Id != null)
            {
                tasksRef = usersRef.Collection(DateTime.Parse(calendarViewModel.Date.ToString(CultureInfo.CurrentCulture))
                                               .ToString("MM.yyyy")).Document("tasks").Collection("tasks").Document(calendarViewModel.Id);
            }
            else
            {
                tasksRef = usersRef.Collection(DateTime.Parse(calendarViewModel.Date.ToString(CultureInfo.CurrentCulture))
                                               .ToString("MM.yyyy")).Document("tasks").Collection("tasks").Document();
            }

            tasksRef?.SetAsync(new { title = calendarViewModel.Name, description = calendarViewModel.Description, downloadUrl }, SetOptions.MergeAll);

            DocumentReference dateRef = db.Collection("users").Document(userId)
                                        .Collection(DateTime.Parse(calendarViewModel.Date.ToString(CultureInfo.CurrentCulture))
                                                    .ToString("MM.yyyy")).Document(calendarViewModel.Date.ToString("dd"));
            await dateRef.SetAsync(new
            {
                month = calendarViewModel.Date.ToString("MM.yyyy")
            });

            var taskRef = dateRef.Collection("tasks").Document(calendarViewModel.Id ?? tasksRef?.Id);

            taskRef?.SetAsync(new { reference = tasksRef, hours = calendarViewModel.Hours }, SetOptions.MergeAll);
        }
        /// <summary>
        /// Increment a randomly picked shard by 1.
        /// </summary>
        /// <param name="docRef">The document reference <see cref="DocumentReference"/></param>
        /// <returns>The <see cref="Task"/></returns>
        private static async Task IncrementCounterAsync(DocumentReference docRef, int numOfShards)
        {
            int documentId;

            lock (s_randLock)
            {
                documentId = s_rand.Next(numOfShards);
            }
            var shardRef = docRef.Collection("shards").Document(documentId.ToString());
            await shardRef.UpdateAsync("count", FieldValue.Increment(1));
        }
예제 #5
0
        private static async Task AddSubcollection(string project)
        {
            FirestoreDb db = FirestoreDb.Create(project);
            // [START fs_add_subcollection]
            DocumentReference           cityRef          = db.Collection("cities").Document("SF");
            CollectionReference         subcollectionRef = cityRef.Collection("neighborhoods");
            Dictionary <string, object> data             = new Dictionary <string, object>
            {
                { "name", "Marina" },
            };
            await subcollectionRef.Document("Marina").SetAsync(data);

            // [END fs_add_subcollection]
            Console.WriteLine("Added data to the Marina document in the neighborhoods subcollection in the SF document in the cities collection.");
        }
        // [END fs_counter_classes]

        // [START fs_create_counter]
        /// <summary>
        /// Create a given number of shards as a
        /// subcollection of specified document.
        /// </summary>
        /// <param name="docRef">The document reference <see cref="DocumentReference"/></param>
        private static async Task CreateCounterAsync(DocumentReference docRef, int numOfShards)
        {
            CollectionReference colRef = docRef.Collection("shards");
            var tasks = new List <Task>();

            // Initialize each shard with Count=0
            for (var i = 0; i < numOfShards; i++)
            {
                tasks.Add(colRef.Document(i.ToString()).SetAsync(new Shard()
                {
                    Count = 0
                }));
            }
            await Task.WhenAll(tasks);
        }
        static async Task <ModuleResources> GetModuleResources(DocumentReference moduleRef)
        {
            var resourceQuery = await moduleRef.Collection(ResourceCollection).GetSnapshotAsync();

            var resourceSnapshots = resourceQuery.Documents;

            var list = new Improbable.Collections.List <ResourceInfo>(resourceQuery.Count);

            for (int i = 0; i < resourceQuery.Count; i++)
            {
                var resourceSnapshot = resourceSnapshots[i];
                var resource         = resourceSnapshot.ConvertTo <Resource>();

                list.Add(new ResourceInfo(resourceSnapshot.Id, resource.Type, resource.Quantity));
            }

            return(new ModuleResources(list));
        }
        static async Task <ResourceInventoryData> GetResourceInventory(DocumentReference shipRef)
        {
            var resourceQuery = await shipRef.Collection(ResourceCollection).GetSnapshotAsync();

            var resourceSnapshots = (DocumentSnapshot[])resourceQuery.Documents;

            var resources = new Improbable.Collections.Map <int, ResourceInfo>(resourceQuery.Count);

            for (int i = 0; i < resourceQuery.Count; i++)
            {
                var snapshot = resourceSnapshots[i];

                var resource = snapshot.ConvertTo <Resource>();

                resources[i] = new ResourceInfo(snapshot.Id, resource.Type, resource.Quantity);
            }

            return(new ResourceInventoryData(resources));
        }
예제 #9
0
        public async Task <Dictionary <string, int> > GetAll(string userId, DateTime date)
        {
            DocumentReference   usersRef      = db.Collection("users").Document(userId);
            CollectionReference colRef        = usersRef.Collection(date.ToString("MM.yyyy"));
            QuerySnapshot       querySnapshot = await colRef.GetSnapshotAsync();

            Dictionary <string, int> dictionary = new Dictionary <string, int>();

            foreach (var temp in querySnapshot)
            {
                var day   = temp.Id;
                var tasks = await temp.Reference.Collection("tasks").GetSnapshotAsync();

                int hours = 0;
                foreach (var temp2 in tasks)
                {
                    hours += int.Parse(temp2.ToDictionary()["hours"].ToString());
                }

                dictionary.Add(day, hours);
            }

            return(dictionary);
        }
        /// <summary>
        /// Get total count across all shards.
        /// </summary>
        /// <param name="docRef">The document reference <see cref="DocumentReference"/></param>
        /// <returns>The <see cref="int"/></returns>
        private static async Task <int> GetCountAsync(DocumentReference docRef)
        {
            var snapshotList = await docRef.Collection("shards").GetSnapshotAsync();

            return(snapshotList.Sum(shard => shard.GetValue <int>("count")));
        }
예제 #11
0
        private async void simulateData()
        {
            CollectionReference orderColl   = db.Collection("order");
            CollectionReference invoiceColl = db.Collection("invoice");
            CollectionReference stockColl   = db.Collection("stock");

            QuerySnapshot stockSnap = await stockColl.GetSnapshotAsync();

            List <Stock> stockList = new List <Stock>();

            foreach (DocumentSnapshot stockDocsnap in stockSnap.Documents)
            {
                Stock stock = stockDocsnap.ConvertTo <Stock>();

                stockList.Add(stock);
            }

            Order order = new Order();

            order.order_id     = "";
            order.order_status = "";
            Invoice invoice = new Invoice();

            invoice.invoice_id  = -1;
            invoice.invoice_num = "dummyinvoicenumber";

            Random random = new Random();

            for (int year = 2020; year <= 2020; year++)
            {
                if (year == 2019)
                {
                    for (int month = 1; month <= 12; month++)
                    {
                        //simulate new invoices at start of every month
                        foreach (Stock stock in stockList)
                        {
                            Dictionary <string, object> data = new Dictionary <string, object>()
                            {
                                { "invoice_date", new DateTime(year, month, 1, 0, 0, 0, DateTimeKind.Utc) },
                                { "invoice_id", invoice.invoice_id },
                                { "invoice_num", invoice.invoice_num },
                                { "vendor_id", stock.vendor_id }
                            };

                            DocumentReference invoiceDocref = await invoiceColl.AddAsync(data);

                            Dictionary <string, object> data2 = new Dictionary <string, object>()
                            {
                                { "item_id", stock.item_id },
                                { "item_name", stock.item_name },
                                { "quantity", 100 },
                                { "wholesale_price", stock.wholesale_price }
                            };

                            await invoiceDocref.Collection("invoice_items").AddAsync(data2);
                        }

                        //simulate sales order everyday
                        for (int day = 1; day <= DateTime.DaysInMonth(year, month); day++)
                        {
                            //loop through stock
                            for (int i = 0; i < 10; i++)
                            {
                                int orderRand = random.Next(0, 10);
                                //if 0 means the item has no sales, else sell according to the number for quantity
                                if (orderRand > 0)
                                {
                                    Dictionary <string, object> data = new Dictionary <string, object>()
                                    {
                                        { "order_date", new DateTime(year, month, day, 0, 0, 0, DateTimeKind.Utc) },
                                        { "order_id", "dummyorderid" },
                                        { "order_status", "dummy" },
                                    };

                                    DocumentReference orderDocref = await orderColl.AddAsync(data);

                                    Dictionary <string, object> data2 = new Dictionary <string, object>()
                                    {
                                        { "item_id", stockList[i].item_id },
                                        { "quantity", orderRand },
                                    };

                                    await orderDocref.Collection("order_items").AddAsync(data2);
                                }
                            }
                        }
                    }
                }
                else
                {
                    for (int month = 12; month <= 12; month++)
                    {
                        foreach (Stock stock in stockList)
                        {
                            Dictionary <string, object> data = new Dictionary <string, object>()
                            {
                                { "invoice_date", new DateTime(year, month, 1, 0, 0, 0, DateTimeKind.Utc) },
                                { "invoice_id", invoice.invoice_id },
                                { "invoice_num", invoice.invoice_num },
                                { "vendor_id", stock.vendor_id }
                            };

                            DocumentReference invoiceDocref = await invoiceColl.AddAsync(data);

                            Dictionary <string, object> data2 = new Dictionary <string, object>()
                            {
                                { "item_id", stock.item_id },
                                { "item_name", stock.item_name },
                                { "quantity", 100 },
                                { "wholesale_price", stock.wholesale_price }
                            };

                            await invoiceDocref.Collection("invoice_items").AddAsync(data2);
                        }

                        for (int day = 1; day <= DateTime.DaysInMonth(year, month); day++)
                        {
                            //loop through stock
                            for (int i = 0; i < 3; i++)
                            {
                                int orderRand = random.Next(0, 10);
                                //if 0 means the item has no sales, else sell according to the number for quantity
                                if (orderRand > 0)
                                {
                                    Dictionary <string, object> data = new Dictionary <string, object>()
                                    {
                                        { "order_date", new DateTime(year, month, day, 0, 0, 0, DateTimeKind.Utc) },
                                        { "order_id", "dummyorderid" },
                                        { "order_status", "dummy" },
                                    };

                                    DocumentReference orderDocref = await orderColl.AddAsync(data);

                                    Dictionary <string, object> data2 = new Dictionary <string, object>()
                                    {
                                        { "item_id", stockList[i].item_id },
                                        { "quantity", orderRand },
                                    };

                                    await orderDocref.Collection("order_items").AddAsync(data2);
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #12
0
        private async void uploadInvoice(String file)
        {
            Excel.Application xlApp      = new Excel.Application();
            Excel.Workbook    xlWorkBook = xlApp.Workbooks.Open(file);
            object            misValue   = System.Reflection.Missing.Value;

            foreach (Excel.Worksheet xlWorkSheet in xlWorkBook.Worksheets)
            {
                try
                {
                    string temp;
                    temp = xlWorkSheet.Range["Vendor_Name"].Value2.ToString();
                    temp = xlWorkSheet.Range["Invoice_Number"].Value2.ToString();
                    temp = xlWorkSheet.Range["Invoice_Date"].Value2.ToString();
                    temp = xlWorkSheet.Range["Item_Number"].Value2.ToString();
                    temp = xlWorkSheet.Range["Item_Desc"].Value2.ToString();
                    temp = xlWorkSheet.Range["Item_Quantity"].Value2.ToString();
                    temp = xlWorkSheet.Range["Item_Price"].Value2.ToString();
                    temp = xlWorkSheet.Range["Item_Total_Price"].Value2.ToString();
                    temp = xlWorkSheet.Range["Total_Balance"].Value2.ToString();

                    CollectionReference icoll = db.Collection("invoice");
                    Query         iquery      = icoll.WhereEqualTo("invoice_num", xlWorkSheet.Range["Invoice_Number"].Value2.ToString());
                    QuerySnapshot isnap       = await iquery.GetSnapshotAsync();

                    Query         iquery2 = icoll.OrderByDescending("invoice_id").Limit(1);
                    QuerySnapshot isnap2  = await iquery2.GetSnapshotAsync();

                    int invoiceid = isnap2.Documents[0].ConvertTo <Invoice>().invoice_id;

                    if (isnap.Count == 0)
                    {
                        try
                        {
                            for (int count = 0; ; count++)
                            {
                                newInvoiceStock.Add(xlWorkSheet.Cells[xlWorkSheet.Range["Item_Desc"].Row + count, xlWorkSheet.Range["Item_Desc"].Column].Value2.ToString());
                            }
                        }
                        catch
                        {
                            CollectionReference coll = db.Collection("stock");

                            Query         query2    = coll.OrderByDescending("item_id").Limit(1);
                            QuerySnapshot stocksnap = await query2.GetSnapshotAsync();

                            int stockid = stocksnap.Documents[0].ConvertTo <Stock>().item_id;

                            int vendor_id = await updateVendorDb(xlWorkSheet.Range["Vendor_Name"].Value2.ToString());

                            DateTime date = DateTime.FromOADate(Convert.ToDouble(xlWorkSheet.Range["Invoice_Date"].Value2.ToString()));
                            DateTime.SpecifyKind(date, DateTimeKind.Utc);

                            invoiceid = invoiceid + 1;

                            Dictionary <string, object> idata = new Dictionary <string, object>()
                            {
                                //auto generate invoice id
                                { "invoice_date", Timestamp.FromDateTimeOffset(date) },
                                { "invoice_id", invoiceid },
                                { "invoice_num", xlWorkSheet.Range["Invoice_Number"].Value2.ToString() },
                                { "vendor_id", vendor_id }
                            };
                            DocumentReference idoc = await icoll.AddAsync(idata);

                            for (int i = 0; i < newInvoiceStock.Count; i++)
                            {
                                //query need to repeat to verify existence of item
                                Query query = coll
                                              .WhereEqualTo("item_name", newInvoiceStock[i].ToString())
                                              .WhereEqualTo("vendor_id", vendor_id);

                                QuerySnapshot snap = await query.GetSnapshotAsync();

                                if (snap.Documents.Count <= 0)
                                {
                                    //add new item
                                    Stock stock = new Stock();

                                    stockid = stockid + 1;

                                    stock.item_id         = stockid;
                                    stock.item_name       = xlWorkSheet.Cells[xlWorkSheet.Range["Item_Desc"].Row + i, xlWorkSheet.Range["Item_Desc"].Column].Value2.ToString();
                                    stock.vendor_id       = vendor_id;
                                    stock.wholesale_price = Double.Parse(xlWorkSheet.Cells[xlWorkSheet.Range["Item_Price"].Row + i, xlWorkSheet.Range["Item_Price"].Column].Value2.ToString());
                                    stock.quantity        = Int32.Parse(xlWorkSheet.Cells[xlWorkSheet.Range["Item_Quantity"].Row + i, xlWorkSheet.Range["Item_Quantity"].Column].Value2.ToString());

                                    add_coll.Add(stock);

                                    Dictionary <string, object> idata2 = new Dictionary <string, object>()
                                    {
                                        { "item_id", stock.item_id },
                                        { "item_name", stock.item_name },
                                        { "quantity", stock.quantity },
                                        { "wholesale_price", stock.wholesale_price }
                                    };

                                    await idoc.Collection("invoice_items").AddAsync(idata2);
                                }
                                else
                                {
                                    //edit existing item
                                    string id = snap.Documents[0].Id;

                                    Stock stock = snap.Documents[0].ConvertTo <Stock>();

                                    DocumentReference docref = coll.Document(id);

                                    Dictionary <string, object> data = new Dictionary <string, object>()
                                    {
                                        { "quantity", stock.quantity + Convert.ToInt32(xlWorkSheet.Cells[xlWorkSheet.Range["Item_Quantity"].Row + i, xlWorkSheet.Range["Item_Quantity"].Column].Value2) }
                                    };

                                    await docref.UpdateAsync(data);

                                    Dictionary <string, object> idata2 = new Dictionary <string, object>()
                                    {
                                        { "item_id", stock.item_id },
                                        { "item_name", stock.item_name },
                                        { "quantity", Convert.ToInt32(xlWorkSheet.Cells[xlWorkSheet.Range["Item_Quantity"].Row + i, xlWorkSheet.Range["Item_Quantity"].Column].Value2) },
                                        { "wholesale_price", stock.wholesale_price }
                                    };

                                    await idoc.Collection("invoice_items").AddAsync(idata2);
                                }
                            }

                            if (add_coll.Count > 0)
                            {
                                PriceEntryForm form = new PriceEntryForm(add_coll);

                                form.Show();

                                form.FormClosed += new FormClosedEventHandler(Form_Closed);
                            }
                            else
                            {
                                refreshDGV();
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Invoice duplicate detected!");
                    }
                }
                catch
                {
                    failedUpload.Add(Path.GetFileName(file));
                }
            }

            xlWorkBook.Close(false, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkBook);
            releaseObject(xlApp);

            finishLoad();
        }
예제 #13
0
        public ICollectionReference GetCollection(string collectionPath)
        {
            var collectionReference = _documentReference.Collection(collectionPath);

            return(new CollectionReferenceWrapper(collectionReference));
        }
예제 #14
0
        private async Task InitializeAsync(ulong id, CollectionReference playerCollection)
        {
            PlayerCollection = playerCollection;
            PlayerDoc        = PlayerCollection.Document(id.ToString());

            var playerDocSnap = await PlayerDoc.GetSnapshotAsync();

            if (!playerDocSnap.Exists)
            {
                await PlayerDoc.CreateAsync(new Dictionary <string, object>()
                {
                    { "boost", 0 },
                    { "demo-count", 0 },
                    { "death-count", 0 },
                    { "demo-rate", (DemoData.MinDemoChance + DemoData.MaxDemoChance) / 2 },
                    { "avoid-rate", (DemoData.MinAvoidChance + DemoData.MaxAvoidChance) / 2 },
                    { "avoid-count", 0 },
                    { "miss-count", 0 }
                });

                playerDocSnap = await PlayerDoc.GetSnapshotAsync();
            }

            if (!playerDocSnap.ContainsField("avoid-count"))
            {
                await PlayerDoc.UpdateAsync("avoid-count", 0);

                await PlayerDoc.UpdateAsync("miss-count", 0);
            }

            if (!playerDocSnap.TryGetValue("avoid-count", out int avoidCount))
            {
                avoidCount = 0;
            }

            if (!playerDocSnap.TryGetValue("miss-count", out int missCount))
            {
                missCount = 0;
            }

            if (!playerDocSnap.TryGetValue("boost-used", out int boostUsed))
            {
                boostUsed = 0;
            }

            Data = new DemoData(
                playerDocSnap.GetValue <int>("boost"),
                playerDocSnap.GetValue <int>("demo-count"),
                playerDocSnap.GetValue <int>("death-count"),
                playerDocSnap.GetValue <double>("demo-rate"),
                playerDocSnap.GetValue <double>("avoid-rate"),
                avoidCount,
                missCount);

            RecentMessages = new List <DbMessage>();

            var recentMsgSnap = await PlayerDoc.Collection("recent-messages").GetSnapshotAsync();

            if (recentMsgSnap.Count > 0)
            {
                foreach (var message in recentMsgSnap)
                {
                    //content, createTime
                    if (!message.TryGetValue("content", out string content))
                    {
                        content = "";
                    }
                    if (!message.TryGetValue("create-time", out DateTime createTime))
                    {
                        createTime = new DateTime(0);
                    }
                    if (!message.TryGetValue("is-successful-command", out bool isSuccessfulCommand))
                    {
                        isSuccessfulCommand = false;
                    }

                    RecentMessages.Add(await DbMessage.CreateAsync(content, createTime, isSuccessfulCommand, id, PlayerCollection, message.Id));
                }
            }
        }