public void Setup() { _logger.LogDebug($"Creating client for {_options.ProjectId}..."); FirestoreClient = _firestoreClients.GetOrAdd(_options.ProjectId, value => { return(FirestoreDb.Create(_options.ProjectId)); }); }
async void setData(int row) { address.number = dataGridView1.Rows[row].Cells[15].Value.ToString(); string estadoCivil = dataGridView1.Rows[row].Cells[9].Value.ToString(); if (estadoCivil == "VIUVO" || estadoCivil == "VIUVA") { estadoCivil = "Viuvo(a)"; } if (estadoCivil == "SOLTEIRO" || estadoCivil == "SOLTEIRA") { estadoCivil = "Solteiro(a)"; } if (estadoCivil == "CASADO" || estadoCivil == "CASADA") { estadoCivil = "Casado(a)"; } if (estadoCivil == "SEPARADO" || estadoCivil == "SEPARADA") { estadoCivil = "Separado(a)"; } if (estadoCivil == "DIVORCIADO" || estadoCivil == "DIVORCIADA") { estadoCivil = "Divorciado(a)"; } string email = dataGridView1.Rows[row].Cells[21].Value.ToString(); if (email == "") { email = dataGridView1.Rows[row].Cells[19].Value.ToString() + "@provantagens.com"; } ; Dictionary <string, object> data = new Dictionary <string, object>() { { "accessLevel", 0 }, { "name", dataGridView1.Rows[row].Cells[1].Value.ToString() }, { "address", address }, { "cpf", dataGridView1.Rows[row].Cells[2].Value.ToString() }, { "dtn", dataGridView1.Rows[row].Cells[5].Value.ToString() }, { "email", email }, { "estadoCivil", estadoCivil }, { "expedicao", dataGridView1.Rows[row].Cells[8].Value.ToString() }, { "nomeconjuge", dataGridView1.Rows[row].Cells[10].Value.ToString() }, { "nomemae", dataGridView1.Rows[row].Cells[12].Value.ToString() }, { "nomepai", dataGridView1.Rows[row].Cells[12].Value.ToString() }, { "orgaoemissor", dataGridView1.Rows[row].Cells[7].Value.ToString() }, { "rg", dataGridView1.Rows[row].Cells[6].Value.ToString() }, { "tel1", dataGridView1.Rows[row].Cells[19].Value.ToString() }, { "tel2", dataGridView1.Rows[row].Cells[20].Value.ToString() }, }; var authProvider = new FirebaseAuthProvider(new FirebaseConfig("AIzaSyA0hQhaFdSKMTQfpSltAmDdqdMvDDG-aR4")); try { var auth = await authProvider.CreateUserWithEmailAndPasswordAsync(email, "123456"); clientID = auth.User.LocalId; string path = AppDomain.CurrentDomain.BaseDirectory + @"pro-vantagens-firebase-adminsdk-5cf5q-82ec44750b.json"; Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path); FirestoreDb db = FirestoreDb.Create("pro-vantagens"); documentReference = db.Collection("users").Document(clientID); await documentReference.SetAsync(data); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public override void ConfigureServices(WebHostBuilderContext context, IServiceCollection services) => services.AddSingleton(FirestoreDb.Create());
public async Task CommitAsync() { var client = new TransactionTestingClient(); var db = FirestoreDb.Create("proj", "db", client); var transaction = await Transaction.BeginAsync(db, null, default); var doc = db.Document("col/doc"); // A simple write of each kind, just to check they're all passed along as expected. transaction.Create(doc, new { Name = "Test" }); transaction.Update(doc, new Dictionary <FieldPath, object> { { new FieldPath("Name"), "Test2" } }); transaction.Set(doc, new { Name = "Test3" }); transaction.Delete(doc); await transaction.CommitAsync(); var expectedRequest = new CommitRequest { Database = "projects/proj/databases/db", Transaction = ByteString.CopyFromUtf8("transaction 1"), Writes = { // Create new Write { CurrentDocument = new V1Beta1.Precondition{ Exists = false }, Update = new Document { Name = doc.Path, Fields ={ { "Name", CreateValue("Test") } } } }, // Update new Write { CurrentDocument = new V1Beta1.Precondition{ Exists = true }, Update = new Document { Name = doc.Path, Fields ={ { "Name", CreateValue("Test2") } } }, UpdateMask = new DocumentMask{ FieldPaths ={ "Name" } } }, // Set new Write { Update = new Document { Name = doc.Path, Fields ={ { "Name", CreateValue("Test3") } } }, }, // Delete new Write { Delete = doc.Path } } }; Assert.Equal(new[] { expectedRequest }, client.CommitRequests); Assert.Empty(client.RollbackRequests); }
public ResumeRepository() { _db = FirestoreDb.Create("totvs-ats-mvp"); }
private async void frmContractPlan_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"); Query plansQuery = db.Collection("plans"); QuerySnapshot snapshots = await plansQuery.GetSnapshotAsync(); foreach (DocumentSnapshot plansSnapshot in snapshots) { Plans plans = plansSnapshot.ConvertTo <Plans>(); GroupBox box = new GroupBox(); Label lbName = new Label(); Label lbType = new Label(); Label lbDescription = new Label(); Label lbValue = new Label(); Label txtName = new Label(); Label txtType = new Label(); Label txtValue = new Label(); TextBox txtDescription = new TextBox(); Button buttonNext = new Button(); pnPlans.Controls.Add(box); box.Name = "Op" + groupNum.ToString(); box.Text = "Opção " + groupNum.ToString(); box.Width = 579; box.Height = 199; box.Location = new Point(12, i + 12); box.BackColor = Color.Transparent; box.Controls.Add(txtName); txtName.Name = "txtName" + groupNum.ToString(); txtName.Text = plans.name; txtName.Font = new Font("Lucida Sans Unicode", 12, FontStyle.Regular); txtName.Location = new Point(161, 16); txtName.BackColor = Color.Transparent; box.Controls.Add(txtType); txtType.Name = "txtType" + groupNum.ToString(); txtType.Text = plans.type; txtType.Font = new Font("Lucida Sans Unicode", 12, FontStyle.Regular); txtType.Location = new Point(161, 51); txtType.BackColor = Color.Transparent; box.Controls.Add(txtDescription); txtDescription.Name = "txtDescription" + groupNum.ToString(); txtDescription.Text = plans.description; txtDescription.Font = new Font("Lucida Sans Unicode", 12, FontStyle.Regular); txtDescription.Location = new Point(161, 80); txtDescription.ReadOnly = true; txtDescription.Multiline = true; txtDescription.Size = new Size(412, 83); box.Controls.Add(txtValue); txtValue.Name = "txtValue" + groupNum.ToString(); txtValue.Text = plans.value; txtValue.Font = new Font("Lucida Sans Unicode", 12, FontStyle.Regular); txtValue.Location = new Point(494, 16); txtValue.BackColor = Color.Transparent; box.Controls.Add(lbName); lbName.Name = "lbName" + groupNum.ToString(); lbName.Text = "Nome do plano:"; lbName.Font = new Font("Lucida Sans Unicode", 10, FontStyle.Bold); lbName.Location = new Point(6, 16); lbName.BackColor = Color.Transparent; lbName.AutoSize = true; box.Controls.Add(lbType); lbType.Name = "lbType" + groupNum.ToString(); lbType.Text = "Tipo de plano:"; lbType.Font = new Font("Lucida Sans Unicode", 10, FontStyle.Bold); lbType.Location = new Point(6, 51); lbType.BackColor = Color.Transparent; lbType.AutoSize = true; box.Controls.Add(lbDescription); lbDescription.Name = "lbDescription" + groupNum.ToString(); lbDescription.Text = "Descrição:"; lbDescription.Font = new Font("Lucida Sans Unicode", 10, FontStyle.Bold); lbDescription.Location = new Point(54, 80); lbDescription.BackColor = Color.Transparent; lbDescription.AutoSize = true; box.Controls.Add(lbValue); lbValue.Name = "lbValue" + groupNum.ToString(); lbValue.Text = "Valor do plano:"; lbValue.Font = new Font("Lucida Sans Unicode", 10, FontStyle.Bold); lbValue.Location = new Point(344, 16); lbValue.BackColor = Color.Transparent; lbValue.AutoSize = true; box.Controls.Add(buttonNext); buttonNext.Name = plansSnapshot.Id; buttonNext.Text = "Avançar"; buttonNext.Font = new Font("Lucida Sans Unicode", 10, FontStyle.Regular); buttonNext.Location = new Point(498, 166); buttonNext.Size = new Size(75, 30); buttonNext.Click += delegate(object send, EventArgs ex) { callContract(send, ex, plansSnapshot.Id, plans.type, plans.name, plans.value); }; i = i + 208; groupNum = groupNum + 1; } }
public async Task loadInvoicesAsync() { string path = AppDomain.CurrentDomain.BaseDirectory + @"pro-vantagens-firebase-adminsdk-5cf5q-82ec44750b.json"; Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path); FirestoreDb db = FirestoreDb.Create("pro-vantagens"); Query queryUser = db.Collection("users"); QuerySnapshot usersSnapshots = await queryUser.GetSnapshotAsync(); dataGrid.Rows.Clear(); foreach (DocumentSnapshot userDocument in usersSnapshots) { Query Query = db.Collection("users").Document(userDocument.Id).Collection("invoices"); QuerySnapshot snapshots = await Query.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in snapshots) { Invoices invoices = documentSnapshot.ConvertTo <Invoices>(); if (btnPagos.Checked) { if (invoices.status == "Ok") { if (cboSearch.Text == "") { if (documentSnapshot.Exists) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Data da fatura") { if (documentSnapshot.Id.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Nome") { if (invoices.holder.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Plano") { if (invoices.planName.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Vencimento") { if (invoices.dueDate.ToString() == txtSearch.Text) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Método de pagamento") { if (invoices.paymentMethod.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Valor total") { if (invoices.totalValue.ToString().Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } } } if (btnPendentes.Checked) { if (invoices.status == "Pendente") { if (cboSearch.Text == "") { if (documentSnapshot.Exists) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Data da fatura") { if (documentSnapshot.Id.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Nome") { if (invoices.holder.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Plano") { if (invoices.planName.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Vencimento") { if (invoices.dueDate.ToString() == txtSearch.Text) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Método de pagamento") { if (invoices.paymentMethod.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Valor total") { if (invoices.totalValue.ToString().Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } } } if (btnVencidos.Checked) { if (invoices.status == "Vencido") { if (cboSearch.Text == "") { if (documentSnapshot.Exists) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Data da fatura") { if (documentSnapshot.Id.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Nome") { if (invoices.holder.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Plano") { if (invoices.planName.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Vencimento") { if (invoices.dueDate.ToString() == txtSearch.Text) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Método de pagamento") { if (invoices.paymentMethod.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Valor total") { if (invoices.totalValue.ToString().Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } } } if (btnAll.Checked) { if (cboSearch.Text == "") { if (documentSnapshot.Exists) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Data da fatura") { if (documentSnapshot.Id.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Nome") { if (invoices.holder.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Plano") { if (invoices.planName.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Vencimento") { if (invoices.dueDate.ToString() == txtSearch.Text) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Método de pagamento") { if (invoices.paymentMethod.Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } if (cboSearch.Text == "Valor total") { if (invoices.totalValue.ToString().Contains(txtSearch.Text)) { dataGrid.Rows.Add(userDocument.Id, documentSnapshot.Id, invoices.holder, invoices.status, invoices.planName, invoices.paymentMethod, invoices.dueDate, invoices.totalValue); } } } } } ; userID = dataGrid.Rows[0].Cells[0].Value.ToString(); invoiceID = dataGrid.Rows[0].Cells[1].Value.ToString(); }
public void LogWarning_NoLogger() { var db = FirestoreDb.Create("project", "database", new FakeFirestoreClient()); db.LogWarning("Message"); }
public Monitoring3() { InitializeComponent(); { //Konfigurasi Pengambilan data dari Database ke Monitoring untuk menampilkan data sensor Chiller dan Freezer #region string path = AppDomain.CurrentDomain.BaseDirectory + @"percobaanjson-firebase-adminsdk-7qk4t-80ed9d2f19.json"; Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path); database = FirestoreDb.Create("percobaanjson"); async void DocumentCostum() { DocumentReference docref = database.Collection("KTAD-1").Document("SensorAndScaleTime"); DocumentSnapshot snap = await docref.GetSnapshotAsync(); if (snap.Exists) { if (snap.Exists) { FirestoreMonitoring_3 firestore = snap.ConvertTo <FirestoreMonitoring_3>(); txtchillermonitoring3.Text = firestore.Chiller.ToString() + "°C"; txtfreezermonitoring3.Text = firestore.Freezer + "°C"; } } } DocumentCostum(); #endregion } //Program pembuatan Grafik #region graphchart.Series = new SeriesCollection { new LineSeries { Values = new ChartValues <ObservablePoint> { new ObservablePoint(00.01, 14), new ObservablePoint(00.02, 14.2), new ObservablePoint(00.03, 13.8), new ObservablePoint(00.04, 13.5), new ObservablePoint(00.06, 14.2), new ObservablePoint(00.07, 14.5), new ObservablePoint(00.08, 14.8), new ObservablePoint(00.09, 15), new ObservablePoint(00.10, 13), }, PointGeometrySize = 15 }, new LineSeries { Values = new ChartValues <ObservablePoint> { new ObservablePoint(00.01, 3), new ObservablePoint(00.02, 2.5), new ObservablePoint(00.03, 2.8), new ObservablePoint(00.04, 2.3), new ObservablePoint(00.06, 2.5), new ObservablePoint(00.07, 3.2), new ObservablePoint(00.08, 2.8), new ObservablePoint(00.09, 3), new ObservablePoint(00.10, 3.1), }, PointGeometrySize = 15 }, new LineSeries { Values = new ChartValues <ObservablePoint> { new ObservablePoint(00.01, 6), new ObservablePoint(00.02, 5), new ObservablePoint(00.03, 6.5), new ObservablePoint(00.04, 5.5), new ObservablePoint(00.06, 6), new ObservablePoint(00.07, 6.3), new ObservablePoint(00.08, 6.8), new ObservablePoint(00.09, 7), new ObservablePoint(00.10, 5.8), }, PointGeometrySize = 15 } }; #endregion }
public UsuarioRepository() { Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "/home/daniela/Downloads/ajhs.json"); _fireStoreDb = FirestoreDb.Create("ajhs-299719"); }
/// <summary> /// Creates new instance of a repository. /// </summary> /// <param name="projectId">The Firebase project id.</param> /// <param name="collectionName">The working collection name.</param> public DocumentTypeRepository(string projectId, string collectionName) { Database = FirestoreDb.Create(projectId); Collection = Database.Collection(collectionName); }
private static async Task UpdateFirestoreAsync() { Console.WriteLine(); Console.WriteLine(" DOWNLOADING EQUIPMENT LIST FROM FIRESTORE"); FirestoreDb db = FirestoreDb.Create("mws-ams"); // [START fs_get_multiple_docs] Query capitalQuery = db.Collection("assets"); //.WhereEqualTo("Capital", true); QuerySnapshot capitalQuerySnapshot = await capitalQuery.GetSnapshotAsync(); Console.WriteLine(); Console.WriteLine(" DOWNLOAD COMPLETED. NOW PROCESSING"); for (int i = 0; i < Equipments.Count; i++) { Equipment equipment = Equipments[i]; equipment.TimeStamp = long.Parse(DateTime.UtcNow.ToString("yyyyMMddHHmmssffff")); try { DocumentSnapshot eqsnapshot = capitalQuerySnapshot.Documents.FirstOrDefault(e => e.Id == equipment.AssetNumber); if (eqsnapshot == null) { // Dictionary<string, object> user = new Dictionary<string, object> // { // { "AssetNumber", equipment.AssetNumber }, // { "EquipmentNumber", equipment.EquipmentNumber }, // // {"AcquisitionDate" , equipment.AcquisitionDate.ToUniversalTime()}, // {"PendingUpdate" ,equipment.PendingUpdate}, // {"AcquisitionValue" ,equipment.AcquisitionValue}, // {"BookValue",equipment.BookValue}, // {"AssetDescription" ,equipment.AssetDescription}, // {"EquipmentDescription" ,equipment.EquipmentDescription}, // {"OperationId",equipment.OperationId}, // {"SubType",equipment.SubType}, // {"Weight",equipment.Weight}, // {"WeightUnit" ,equipment.WeightUnit}, // {"Dimensions",equipment.Dimensions}, // {"Tag",equipment.Tag}, // {"Type" ,equipment.Type}, // {"Connection" ,equipment.Connection}, // {"Length",equipment.Length}, // {"ModelNumber" ,equipment.ModelNumber}, // {"SerialNumber",equipment.SerialNumber}, // {"AssetLocation" ,equipment.AssetLocation}, // {"AssetLocationText" ,equipment.AssetLocationText}, // {"EquipmentLocation",equipment.EquipmentLocation}, // // }; await db.Collection("assets").Document(equipment.AssetNumber).SetAsync(equipment); } else { Equipment serverEquipment = eqsnapshot.ConvertTo <Equipment>(); if (serverEquipment.EquipmentDescription != equipment.EquipmentDescription) { serverEquipment.EquipmentDescription = equipment.EquipmentDescription; await db.Collection("assets").Document(equipment.AssetNumber).SetAsync(equipment); } } Console.Write("\r UPDATING " + i + " OF " + Equipments.Count); } catch (Exception e) { Console.WriteLine(e.Message); } } }
public FirestoreDbService() { var projectId = Environment.GetEnvironmentVariable("PROJECT_ID"); _db = FirestoreDb.Create(projectId); }
public async Task Listen(SerializableTest wrapper) { ListenTest test = wrapper.Test.Listen; var db = FirestoreDb.Create(ProjectId, DatabaseId, new FakeFirestoreClient()); var query = db.Collection("C").OrderBy("a"); Func <Task> action = async() => { List <QuerySnapshot> snapshots = new List <QuerySnapshot>(); var watchState = new WatchState(query, (snapshot, token) => { snapshots.Add(snapshot); return(Task.FromResult(1)); }); watchState.OnStreamInitialization(StreamInitializationCause.WatchStarting); foreach (var response in test.Responses) { // Fix up the test response to use our watch target ID. ReplaceWatchTargetId(response.TargetChange?.TargetIds); ReplaceWatchTargetId(response.DocumentChange?.TargetIds); ReplaceWatchTargetId(response.DocumentChange?.RemovedTargetIds); ReplaceWatchTargetId(response.DocumentDelete?.RemovedTargetIds); ReplaceWatchTargetId(response.DocumentRemove?.RemovedTargetIds); var result = await watchState.HandleResponseAsync(response, default); if (result == WatchResponseResult.ResetStream) { watchState.OnStreamInitialization(StreamInitializationCause.ResetRequested); } } var expectedSnapshots = test.Snapshots.Select(snapshot => ConvertSnapshot(snapshot)).ToList(); Assert.Equal(expectedSnapshots, snapshots); }; if (test.IsError) { // TODO: Should we actually check that it's only the last response that causes the exception? var exception = await Assert.ThrowsAnyAsync <Exception>(action); Assert.True(exception is ArgumentException || exception is InvalidOperationException, $"Exception type: {exception.GetType()}"); } else { await action(); } // Different clients use different watch target IDs. The test data always uses 1 // to mean "the target ID that the client uses". void ReplaceWatchTargetId(RepeatedField <int> ids) { if (ids == null) { return; } for (int i = 0; i < ids.Count; i++) { if (ids[i] == 1) { ids[i] = WatchStream.WatchTargetId; } } } // Converts from a test proto snapshot to a QuerySnapshot QuerySnapshot ConvertSnapshot(Snapshot snapshot) { var readTime = Timestamp.FromProto(snapshot.ReadTime); var changes = snapshot.Changes.Select(change => ConvertChange(change, readTime)).ToList(); var docs = snapshot.Docs.Select(doc => DocumentSnapshot.ForDocument(db, doc, readTime)).ToList(); return(QuerySnapshot.ForChanges(query, docs, changes, readTime)); } DocumentChange ConvertChange(DocChange change, Timestamp readTime) { var snapshot = DocumentSnapshot.ForDocument(db, change.Doc, readTime); return(new DocumentChange(snapshot, (DocumentChange.Type)change.Kind, change.OldIndex == -1 ? default(int?) : change.OldIndex, change.NewIndex == -1 ? default(int?) : change.NewIndex)); } }
public async Task GetAllSnapshotsAsync() { string docName1 = "projects/proj/databases/db/documents/col1/doc1"; string docName2 = "projects/proj/databases/db/documents/col2/doc2"; ByteString transaction = ByteString.CopyFromUtf8("abc"); var mock = new Mock <FirestoreClient> { CallBase = true }; var request = new BatchGetDocumentsRequest { Database = "projects/proj/databases/db", // Note that we request docName2 twice, as per the caller's request: // the library doesn't perform any elision. Documents = { docName1, docName2, docName2 }, Transaction = transaction }; var responses = new[] { // Deliberately not in the requested order new BatchGetDocumentsResponse { Found = new Document { Name = docName2, CreateTime = CreateProtoTimestamp(0, 1), UpdateTime = CreateProtoTimestamp(0, 2), Fields = { { "Name", CreateValue("Test") } } }, ReadTime = CreateProtoTimestamp(1, 3) }, new BatchGetDocumentsResponse { Missing = docName1, ReadTime = CreateProtoTimestamp(1, 2) }, }; mock.Setup(c => c.BatchGetDocuments(request, It.IsAny <CallSettings>())).Returns(new FakeDocumentStream(responses)); var db = FirestoreDb.Create("proj", "db", mock.Object); var docRef1 = db.Document("col1/doc1"); var docRef2 = db.Document("col2/doc2"); var results = await db.GetAllSnapshotsAsync(new[] { docRef1, docRef2, docRef2 }, transaction, default); Assert.Equal(3, results.Count); // Note that this is the first result from the request, not the first from the response - // the method returns them in request order, not response order. var snapshot1 = results[0]; Assert.False(snapshot1.Exists); Assert.Equal(new Timestamp(1, 2), snapshot1.ReadTime); Assert.Equal(docRef1, snapshot1.Reference); var snapshot2 = results[1]; Assert.True(snapshot2.Exists); Assert.Equal(new Timestamp(0, 1), snapshot2.CreateTime); Assert.Equal(new Timestamp(0, 2), snapshot2.UpdateTime); Assert.Equal(new Timestamp(1, 3), snapshot2.ReadTime); Assert.Equal(docRef2, snapshot2.Reference); Assert.Equal("Test", snapshot2.GetValue <string>("Name")); // The third result element is just a reference to the same snapshot. Assert.Same(results[1], results[2]); mock.VerifyAll(); }
public GoogleCloudFirestoreService() { m_db = FirestoreDb.Create(GoogleComputeEngineHelper.GetCurrentProjectId()); }
public void Document_Invalid(string path) { var db = FirestoreDb.Create("proj", "db", new FakeFirestoreClient()); Assert.Throws <ArgumentException>(() => db.Document(path)); }
// GET: Image public async Task <ActionResult> Index(string id, string patient) { ImageModel _objuserloginmodel = new ImageModel(); ViewBag.SelectedId = 0; TempData["SelectedId"] = 0; TempData["appointmentAutoId"] = id; TempData["patientAutoId"] = patient; List <ImageViewModel> ImageList = new List <ImageViewModel>(); //string ClinicMobileNumber = GlobalSessionVariables.ClinicMobileNumber; //string ClinicMobileNumber = "9811035028"; string Path = AppDomain.CurrentDomain.BaseDirectory + @"greenpaperdev-firebase-adminsdk-8k2y5-fb46e63414.json"; Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Path); FirestoreDb db = FirestoreDb.Create("greenpaperdev"); int i = 1; Query QrefPrescriptions = db.Collection("clinics").Document(GlobalSessionVariables.ClinicDocumentAutoId).Collection("patientList").Document(patient).Collection("prescriptions").OrderByDescending("timeStamp"); QuerySnapshot snapPres = await QrefPrescriptions.GetSnapshotAsync(); if (snapPres.Count > 0) { foreach (DocumentSnapshot docsnapPres in snapPres) { if (docsnapPres.Exists) { ImageViewModel img = new ImageViewModel(); img.Id = i; img.ImageUrl = "data:image/png;base64," + docsnapPres.GetValue <string>("file"); ImageList.Add(img); i++; } } _objuserloginmodel.SelectedImage = ImageList[0]; } //_objuserloginmodel.SelectedImage = _objuserloginmodel.GetList()[0]; TempData["CurrentSelectedId"] = snapPres.Count; TempData["TotalPrescriptions"] = snapPres.Count; decimal totalprice = 0; List <Medicine> medicineList = new List <Medicine>(); Query QrefMedicines = db.Collection("clinics").Document(GlobalSessionVariables.ClinicDocumentAutoId).Collection("appointments").Document(id).Collection("medicines"); QuerySnapshot snapMedicines = await QrefMedicines.GetSnapshotAsync(); if (snapMedicines.Count > 0) { foreach (DocumentSnapshot docsnapMedicines in snapMedicines) { if (docsnapMedicines.Exists) { Medicine med = new Medicine(); med.id = docsnapMedicines.Id; med.medicinename = docsnapMedicines.GetValue <string>("medicinename"); med.quantity = docsnapMedicines.GetValue <string>("quantity"); med.Price = (Convert.ToDecimal(docsnapMedicines.GetValue <string>("quantity")) * Convert.ToDecimal(docsnapMedicines.GetValue <string>("unitmrp"))).ToString(); med.inventoryid = docsnapMedicines.GetValue <string>("inventoryid"); medicineList.Add(med); totalprice = totalprice + Convert.ToDecimal(docsnapMedicines.GetValue <string>("quantity")) * Convert.ToDecimal(docsnapMedicines.GetValue <string>("unitmrp")); } } } TempData["medicine"] = medicineList; QuerySnapshot snapSettings = await db.Collection("clinics").Document(GlobalSessionVariables.ClinicDocumentAutoId).Collection("settings").Limit(1).GetSnapshotAsync(); if (snapSettings.Count > 0) { DocumentSnapshot docSnapSettings = snapSettings.Documents[0]; if (docSnapSettings.Exists) { try { if (docSnapSettings.GetValue <Boolean>("inventoryon")) { TempData["inventoryon"] = "true"; } else { TempData["inventoryon"] = "false"; } } catch { TempData["inventoryon"] = "false"; } } else { TempData["inventoryon"] = "false"; } } DocumentReference docRef = db.Collection("clinics").Document(GlobalSessionVariables.ClinicDocumentAutoId).Collection("appointments").Document(id); DocumentSnapshot docSnap = await docRef.GetSnapshotAsync(); totalprice = totalprice + Convert.ToInt32(docSnap.GetValue <string>("fee")); if (totalprice == 0) { TempData["TotalPrice"] = 0; } else { TempData["TotalPrice"] = totalprice; } TempData["days"] = docSnap.GetValue <string>("days"); TempData["fee"] = docSnap.GetValue <string>("fee"); if (docSnap.GetValue <Timestamp>("raisedDate").ToDateTime().Date < DateTime.Now.Date) { ViewData["DateType"] = "OldDate"; } else { ViewData["DateType"] = "CurrentDate"; } try { if (docSnap.GetValue <string>("statusChemist") == "Completed") { ViewData["FromPage"] = "Completed"; } else { ViewData["FromPage"] = "Waiting"; } } catch { ViewData["FromPage"] = "Waiting"; } TempData.Keep(); return(View(_objuserloginmodel)); }
public FireStoreData() { Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", AppDomain.CurrentDomain.BaseDirectory + Utils.Constants.sdCovid + ".json"); _dataBase = FirestoreDb.Create(Utils.Constants.sdCovid); }
public FirebaseHandler() { this.db = FirestoreDb.Create("catsopinion-backend"); }
public EventsRepository() { Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", Path.Combine(AppContext.BaseDirectory + Global.Database_Key_File)); _db = FirestoreDb.Create(PROJECT_ID); Log.Logger.Information("Created Firestore connection"); }
private async Task <ActionResult> LoadChatAsync(int?key) { //ChatMain Page if (key.HasValue) { ChatKey chat = ent.ChatKeys.FirstOrDefault(x => x.ChatKeyID == key); if (chat != null) { FirestoreDb firestore = FirestoreDb.Create("photogw2"); string docID; var collection = firestore.Collection("Quotation"); var snapshot = await collection.WhereEqualTo("ChatKey", chat.ChatKeyID).GetSnapshotAsync(); if (snapshot.Count() != 0) { docID = snapshot.Documents.FirstOrDefault().Id; } else { var arr = new Dictionary <string, object>().ToArray(); Dictionary <string, object> data = new Dictionary <string, object> { { "ChatKey", chat.ChatKeyID } }; var submitData = collection.Document(); await submitData.SetAsync(data); docID = submitData.Id; } if (ViewBag.StudioID != null) { int studioID = (int)ViewBag.StudioID; ViewBag.PackageList = ent.Packages.Where(x => x.studioid == studioID && x.status.ToLower() != "disabled").ToList(); } ViewBag.QuotationID = docID; if (TempData["Package"] != null) { ViewBag.SelectedPackageID = TempData["Package"]; } return(View("ChatMain", chat)); } } //Chat List Page List <ChatKey> chatlist; if (ViewBag.StudioID != null) { long studioID = (long)ViewBag.StudioID; chatlist = ent.ChatKeys.Where(x => x.StudioID == studioID).ToList(); } else { User whichuser = (User)UserAuthentication.Identity(); chatlist = ent.ChatKeys.Where(x => x.UserID == whichuser.id).ToList(); } return(View("ChatList", chatlist)); }
private FirestoreDb CreateFirestoreDbExpectingNoCommits() => FirestoreDb.Create("proj", "db", new TransactionTestingClient(int.MaxValue, new NotSupportedException()));
private static DocumentReference GetDocumentReference(string resourceName) => FirestoreDb.Create(ProjectId, DatabaseId, new FakeFirestoreClient()).GetDocumentReferenceFromResourceName(resourceName);
private static FirestoreDb InitializeDataBase() { FirestoreDb db = FirestoreDb.Create("sudoku-87c4a"); return(db); }
static int Main(string[] args) { if (args.Length != 4) { PrintUsage(); return(ErrorExitStatus); } stopwatch.Restart(); // Avoid missing component errors because no components are directly used in this project // and the GeneratedCode assembly is not loaded but it should be Assembly.Load("GeneratedCode"); using (var connection = ConnectWithReceptionist(args[1], Convert.ToUInt16(args[2]), args[3])) { var connected = true; var channel = new Channel(FirestoreClient.DefaultEndpoint.Host, GoogleCredential.FromFile(Path.Combine(Directory.GetCurrentDirectory(), GoogleCredentialFile)).ToChannelCredentials()); var database = FirestoreDb.Create(FirebaseProjectId, FirestoreClient.Create(channel)); FirebaseJWT.PeriodicKeyUpdate(); SpatialOSConnectionSystem.connection = connection; ShipsBasicSystem.Firestore = database; ShipsAdditionSystem.Firestore = database; var dispatcher = new Dispatcher(); dispatcher.OnDisconnect(op => { Console.Error.WriteLine("[disconnect] " + op.Reason); connected = false; }); dispatcher.OnCommandRequest(PlayerSpawner.Commands.CreatePlayer.Metaclass, RequestsVerifierSystem.OnCreatePlayerRequest); dispatcher.OnCommandRequest(AsteroidSpawner.Commands.PopulateGridCell.Metaclass, AsteroidProcGenSystem.OnPopulateGridCell); stopwatch.Stop(); connection.SendLogMessage(LogLevel.Info, "Initialization", string.Format("Init Time {0}ms", stopwatch.Elapsed.TotalMilliseconds.ToString("N0"))); var maxWait = TimeSpan.FromMilliseconds(100); while (connected) { stopwatch.Restart(); using (var opList = connection.GetOpList(0)) { dispatcher.Process(opList); } Parallel.Invoke( RequestsVerifierSystem.Update, ShipsBasicSystem.Update, ShipsAdditionSystem.Update, ShipsConstructorSystem.Update, AsteroidProcGenSystem.Update, SpatialOSConnectionSystem.Update ); stopwatch.Stop(); var frameTime = stopwatch.Elapsed; if (frameTime > maxWait) { connection.SendLogMessage(LogLevel.Warn, "Game Loop", string.Format("Frame Time {0}ms", frameTime.TotalMilliseconds.ToString("N0"))); } else { Thread.Sleep(maxWait - frameTime); } } SpatialOSConnectionSystem.connection = null; channel.ShutdownAsync().Wait(); } // This means we forcefully disconnected return(ErrorExitStatus); }
public async Task StreamAsync_WithDocuments() { var mock = new Mock <FirestoreClient> { CallBase = true }; var request = new RunQueryRequest { Parent = "projects/proj/databases/db/documents", StructuredQuery = new StructuredQuery { Select = new Projection { Fields = { Field("Name") } }, From = { new CollectionSelector { CollectionId = "col" } }, Offset = 3 }, Transaction = ByteString.CopyFrom(1, 2, 3, 4) }; var responses = new[] { new RunQueryResponse { SkippedResults = 3 }, new RunQueryResponse { ReadTime = CreateProtoTimestamp(1, 2), Document = new Document { CreateTime = CreateProtoTimestamp(0, 1), UpdateTime = CreateProtoTimestamp(0, 2), Name = "projects/proj/databases/db/documents/col/doc1", Fields = { { "Name", CreateValue("x") } } } }, new RunQueryResponse { ReadTime = CreateProtoTimestamp(1, 3), Document = new Document { CreateTime = CreateProtoTimestamp(0, 3), UpdateTime = CreateProtoTimestamp(0, 4), Name = "projects/proj/databases/db/documents/col/doc2", Fields = { { "Name", CreateValue("y") } } } } }; mock.Setup(c => c.RunQuery(request, It.IsAny <CallSettings>())).Returns(new FakeQueryStream(responses)); var db = FirestoreDb.Create("proj", "db", mock.Object); var query = db.Collection("col").Select("Name").Offset(3); // Just for variety, we'll provide a transaction ID this time... var documents = await query.StreamAsync(ByteString.CopyFrom(1, 2, 3, 4), CancellationToken.None).ToList(); Assert.Equal(2, documents.Count); var doc1 = documents[0]; Assert.Equal(db.Document("col/doc1"), doc1.Reference); Assert.Equal(new Timestamp(1, 2), doc1.ReadTime); Assert.Equal(new Timestamp(0, 1), doc1.CreateTime); Assert.Equal(new Timestamp(0, 2), doc1.UpdateTime); Assert.Equal("x", doc1.GetField <string>("Name")); var doc2 = documents[1]; Assert.Equal(db.Document("col/doc2"), doc2.Reference); Assert.Equal(new Timestamp(1, 3), doc2.ReadTime); Assert.Equal(new Timestamp(0, 3), doc2.CreateTime); Assert.Equal(new Timestamp(0, 4), doc2.UpdateTime); Assert.Equal("x", doc1.GetField <string>("Name")); mock.VerifyAll(); }
public void GetDocumentReferenceFromResourcePath_Invalid(string path) { var db = FirestoreDb.Create("proj", "db", new FakeFirestoreClient()); Assert.Throws <ArgumentException>(() => db.GetDocumentReferenceFromResourceName(path)); }
public async Task GetSnapshotAsync_WithDocuments() { var mock = new Mock <FirestoreClient> { CallBase = true }; var request = new RunQueryRequest { Parent = "projects/proj/databases/db/documents", StructuredQuery = new StructuredQuery { Select = new Projection { Fields = { Field("Name") } }, From = { new CollectionSelector { CollectionId = "col" } }, Offset = 3 } }; var responses = new[] { new RunQueryResponse { SkippedResults = 3 }, new RunQueryResponse { ReadTime = CreateProtoTimestamp(1, 2), Document = new Document { CreateTime = CreateProtoTimestamp(0, 1), UpdateTime = CreateProtoTimestamp(0, 2), Name = "projects/proj/databases/db/documents/col/doc1", Fields = { { "Name", CreateValue("x") } } } }, new RunQueryResponse { ReadTime = CreateProtoTimestamp(1, 3), Document = new Document { CreateTime = CreateProtoTimestamp(0, 3), UpdateTime = CreateProtoTimestamp(0, 4), Name = "projects/proj/databases/db/documents/col/doc2", Fields = { { "Name", CreateValue("y") } } } } }; mock.Setup(c => c.RunQuery(request, It.IsAny <CallSettings>())).Returns(new FakeQueryStream(responses)); var db = FirestoreDb.Create("proj", "db", mock.Object); var query = db.Collection("col").Select("Name").Offset(3); var snapshot = await query.GetSnapshotAsync(); Assert.Equal(2, snapshot.Documents.Count); Assert.Same(query, snapshot.Query); Assert.Equal(new Timestamp(1, 2), snapshot.ReadTime); // From first document var doc1 = snapshot.Documents[0]; Assert.Equal(db.Document("col/doc1"), doc1.Reference); Assert.Equal(new Timestamp(1, 2), doc1.ReadTime); Assert.Equal(new Timestamp(0, 1), doc1.CreateTime); Assert.Equal(new Timestamp(0, 2), doc1.UpdateTime); Assert.Equal("x", doc1.GetValue <string>("Name")); var doc2 = snapshot.Documents[1]; Assert.Equal(db.Document("col/doc2"), doc2.Reference); Assert.Equal(new Timestamp(1, 3), doc2.ReadTime); Assert.Equal(new Timestamp(0, 3), doc2.CreateTime); Assert.Equal(new Timestamp(0, 4), doc2.UpdateTime); Assert.Equal("x", doc1.GetValue <string>("Name")); mock.VerifyAll(); }
public async Task <List <Event> > getAllEvents() { SetEnvironmentVariable.setFirestoreEnvironmentVariable(); List <Event> allEvents = new List <Event>(); FirestoreDb db = FirestoreDb.Create(GetConstant.FIRESTORE_ID); Query allEventsQuery = db.Collection("Event"); QuerySnapshot allEventsQuerySnapshot = await allEventsQuery.GetSnapshotAsync(); foreach (DocumentSnapshot documentSnapshot in allEventsQuerySnapshot.Documents) { Console.WriteLine("Document data for {0} document:", documentSnapshot.Id); Dictionary <string, object> eventValue = documentSnapshot.ToDictionary(); foreach (KeyValuePair <string, object> pair in eventValue) { Console.WriteLine("{0}: {1}", pair.Key, pair.Value); } object webPage = null; try { eventValue.TryGetValue("WebPage", out webPage).ToString(); } catch (ArgumentNullException) { Console.WriteLine("Web page got unsuccesfully"); }; string webPageString = ""; if (webPage != null) { webPageString = webPage.ToString(); } Event eventEntity = new Event( eventValue["Id"].ToString(), eventValue["EventName"].ToString(), DateTime.Parse(eventValue["DateFrom"].ToString()), Int32.Parse(eventValue["EventLengthDays"].ToString()), DateTime.Parse(eventValue["DateDay1"].ToString()), DateTime.Parse(eventValue["DateDay2"].ToString()), DateTime.Parse(eventValue["DateDay3"].ToString()), DateTime.Parse(eventValue["DateDay4"].ToString()), eventValue["Day1TimeFrom"].ToString(), eventValue["Day1TimeTo"].ToString(), eventValue["Day2TimeFrom"].ToString(), eventValue["Day2TimeTo"].ToString(), eventValue["Day3TimeFrom"].ToString(), eventValue["Day3TimeTo"].ToString(), eventValue["Day4TimeFrom"].ToString(), eventValue["Day4TimeTo"].ToString(), webPageString, eventValue["VenueName"].ToString(), eventValue["VenueAdress"].ToString(), eventValue["EventStatus"].ToString(), eventValue["Comment"].ToString(), Boolean.Parse(eventValue["UseTemplate"].ToString()), eventValue["Current_Mail_Template"].ToString(), eventValue["EmailBody"].ToString(), eventValue["EmailSubject"].ToString() ); allEvents.Add(eventEntity); Console.WriteLine(""); } if (allEvents.Count > 0) { allEvents = allEvents.OrderByDescending(ev => ev.date_From).ToList(); } return(allEvents); }