Firebase'deki veritabanımdaki flashcard yapısına hashtags ve updatedAt gibi iki alan…
- User
Firebase'deki veritabanımdaki flashcard yapısına hashtags ve updatedAt gibi iki alan ekledim. Senden istediğim ana kodun fonksiyonelliğini kesinlikle, kesinlikle ama kesinlikle etkilemeden bu verileri de okuyup yazması için ilgili kod güncellemerini yap. Hashtags için metin giriş alanı de uygun bir yere ekle aynı şekilde pc uygulamam hashtag verisini boş okuduğunda herhangi bir hataya sebep olmasın. Tüm kodu tek parça yaz.
"flashcards": { "-O9I0kTmATzuYG6v9pBj": { "backgroundColor": "#FF6F00", "category": "CATEGORY", "content": "hello this is texthello this is texthello this is texthello this is texthello this is texthello this is hello this is texthello this is texthello this is texthello this is texthello this is texthello this is text", "favorite": true, "id": "-O9I0kTmATzuYG6v9pBj", "pinned": true, "timestamp": 1729043564773, "title": "Title", "updatedAt": 1729112499190, "hashtags": ["#example", "#firebase", "#flashcards"] }
/// <summary> /// Initializes Firebase connection using the provided JSON credentials. /// </summary> private void InitializeFirebase() { var path = "flashcard-e7f47-firebase-adminsdk-om656-e70a5506c2.json"; var credential = GoogleCredential.FromFile(path); // Check if FirebaseApp is already created to prevent duplicate initialization if (FirebaseApp.DefaultInstance == null) { FirebaseApp.Create(new AppOptions { Credential = credential }); } firebaseClient = new FirebaseClient("https://flashcard-e7f47-default-rtdb.europe-west1.firebasedatabase.app/"); } private async Task SyncLocalDataWithFirebase() { try { // Firebase'den verileri al var firebaseFlashcards = await firebaseClient .Child("flashcards") // "flashcards" yolunu kendi veritabanınıza göre düzenleyin .OnceAsync<FlashcardItem>(); // Firebase'deki flashcard ID'lerini topla var firebaseFlashcardIds = firebaseFlashcards.Select(f => f.Key).ToHashSet(); // Yerel dosyadan verileri oku List<FlashcardItem> localFlashcards = new List<FlashcardItem>(); if (File.Exists(localDataFilePath)) { var json = File.ReadAllText(localDataFilePath); localFlashcards = JsonConvert.DeserializeObject<List<FlashcardItem>>(json); } // Yerel verilerden silinmiş olanları temizle var updatedLocalFlashcards = localFlashcards .Where(f => firebaseFlashcardIds.Contains(f.id)) .ToList(); // Güncellenmiş verileri yerel dosyaya yaz File.WriteAllText(localDataFilePath, JsonConvert.SerializeObject(updatedLocalFlashcards)); // UI güncellemelerini Invoke ile gerçekleştir this.Invoke((MethodInvoker)delegate { // DataGridView'i güncelle allFlashcards = updatedLocalFlashcards; // Güncellenmiş verileri kullan dataGridView.DataSource = null; dataGridView.DataSource = allFlashcards; // Durum çubuğunu güncelle statusLabel.Text = "Local data synchronized with Firebase."; // Update Filter Categories menu PopulateFilterCategoriesMenu(); }); } catch (Exception ex) { MessageBox.Show( "Bulut senkronizasyonu başarısız oldu. İnternet bağlantınızı kontrol edin ve tekrar deneyin.\nYerel veri eklemelerinize devam edebilirsiniz.", "Senkronizasyon Hatası", MessageBoxButtons.OK, MessageBoxIcon.Warning ); } } private void ExportSettingsMenuItem_Click(object sender, EventArgs e) { // Get distinct categories for export options List<string> categories = allFlashcards.Select(f => f.category).Distinct().ToList(); categories = categories.Where(c => !string.IsNullOrWhiteSpace(c)).ToList(); using (ExportSettingsForm exportForm = new ExportSettingsForm(categories)) { if (exportForm.ShowDialog() == DialogResult.OK) { // You can handle any additional settings here if needed // Currently, export settings are handled during Save As } } } /// <summary> /// Handles button click events by identifying the button text. /// </summary> private void ButtonClick(string buttonText) { switch (buttonText) { case "Add": AddData(); break; case "Update": UpdateData(); break; case "Delete": DeleteData(); break; case "Search": SearchData(); break; case "Clear": ClearSearch(); break; } } /// <summary> /// Handles the "Save As" menu item click to save data in selected format. /// </summary> private void SaveAsMenuItem_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog = new SaveFileDialog { Filter = "Firebase files (*.json)|*.json|Standard JSON files (*.json)|*.json|CSV files (*.csv)|*.csv|TSV files (*.tsv)|*.tsv|Text files (*.txt)|*.txt|PDF files (*.pdf)|*.pdf", Title = "Save As" }; if (saveFileDialog.ShowDialog() == DialogResult.OK) { try { string extension = Path.GetExtension(saveFileDialog.FileName).ToLower(); // Filtre indexini kaldırdım çünkü şimdi yöntemde uzmanlaşmadık // İlk olarak seçilen formatın türünü belirleyin // DataGridView'den verileri al var data = isOnline ? allFlashcards : (List<FlashcardItem>)dataGridView.DataSource; // Show Export Settings dialog with yeni seçenek using (ExportSettingsForm exportForm = new ExportSettingsForm(allFlashcards.Select(f => f.category).Distinct().Where(c => !string.IsNullOrWhiteSpace(c)).ToList())) { exportForm.SelectAllFields(); // Select all fields by default if (exportForm.ShowDialog() == DialogResult.OK) { var selectedFields = exportForm.GetSelectedFields(); var exportByCategory = exportForm.ExportByCategory; List<string> selectedCategories = exportForm.GetSelectedCategories(); if (selectedFields.Count == 0) { MessageBox.Show("Please select at least one field to export.", "No Fields Selected", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // Kullanıcının seçimine göre veri setini belirleyin List<FlashcardItem> dataToExport; if (exportForm.ExportAll) { dataToExport = allFlashcards; } else if (exportByCategory && selectedCategories.Any()) { dataToExport = allFlashcards.Where(f => selectedCategories.Contains(f.category)).ToList(); } else { dataToExport = (List<FlashcardItem>)dataGridView.DataSource; } // Farklı formatlarda kaydetmek için mevcut metodları kullanın if (extension == ".json") { // Determine if it's Firebase JSON or Standard JSON based on filter // Let's assume the first option is Firebase if (saveFileDialog.FilterIndex == 1) { SaveDataAsJSonForFirebase(dataToExport, saveFileDialog.FileName); } else { SaveDataAsJSon2(dataToExport, saveFileDialog.FileName, selectedFields); } } else { // Handle CSV, TSV, TXT, PDF exports with field selection switch (extension) { case ".csv": SaveDataAsCsv(dataToExport, saveFileDialog.FileName, ',', selectedFields); break; case ".tsv": SaveDataAsCsv(dataToExport, saveFileDialog.FileName, '\t', selectedFields); break; case ".txt": SaveDataAsTxt(dataToExport, saveFileDialog.FileName, selectedFields); break; case ".pdf": SaveDataAsPdf(dataToExport, saveFileDialog.FileName, selectedFields); break; default: MessageBox.Show("Unsupported file format.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); break; } MessageBox.Show("Data saved successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } catch (Exception ex) { MessageBox.Show($"Error saving data: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } private void SaveDataAsJSon2(List<FlashcardItem> data, string filePath, List<string> selectedFields) { try { var filteredData = data.Select(item => { var jsonObject = new Dictionary<string, object>(); foreach (var field in selectedFields) { switch (field.ToLower()) { case "id": jsonObject["id"] = item.id; break; case "category": jsonObject["category"] = item.category; break; case "title": jsonObject["title"] = item.title; break; case "content": jsonObject["content"] = item.content; break; case "favorite": jsonObject["favorite"] = item.favorite; break; case "pinned": jsonObject["pinned"] = item.pinned; break; case "timestamp": jsonObject["timestamp"] = item.timestamp; break; case "backgroundcolor": jsonObject["backgroundColor"] = item.backgroundColor; break; default: break; } } return jsonObject; }).ToList(); var options = new JsonSerializerSettings { Formatting = Formatting.Indented // JSON'u okunabilir şekilde biçimlendirir }; string jsonString = JsonConvert.SerializeObject(filteredData, options); File.WriteAllText(filePath, jsonString, Encoding.UTF8); } catch (Exception ex) { MessageBox.Show($"Error saving JSON data: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void SaveDataAsJSonForFirebase(List<FlashcardItem> data, string filePath) { try { // Verileri flashcards düğümü altında olacak şekilde düzenle var flashcards = new Dictionary<string, FlashcardItem>(); foreach (var item in data) { flashcards[item.id] = item; // Mevcut ID'yi kullan } var root = new Dictionary<string, object> { { "flashcards", flashcards } }; var options = new JsonSerializerSettings { Formatting = Formatting.Indented // JSON'u okunabilir şekilde biçimlendirir }; string jsonString = JsonConvert.SerializeObject(root, options); File.WriteAllText(filePath, jsonString, new UTF8Encoding(false)); //For firebase Json new UTF8Encoding(false) is must } catch (Exception ex) { MessageBox.Show($"Error saving JSON data: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// <summary> /// Updates a flashcard in the Firebase database and local storage. /// </summary> private async Task UpdateFlashcardInDatabase(FlashcardItem flashcard) { try { // Update local data var index = allFlashcards.FindIndex(f => f.id == flashcard.id); if (index >= 0) { allFlashcards[index] = flashcard; SaveLocalData(); // Save to local storage } if (isOnline) { await firebaseClient .Child("flashcards") .Child(flashcard.id) .PutAsync(flashcard); } else { // Add to offline changes offlineChanges.Add(new FlashcardChange { ChangeType = ChangeType.Update, Flashcard = flashcard }); SaveOfflineChanges(); // Offline changes'i kaydet // Update local data is already done } ApplyFiltersAndSort(); } catch (Exception ex) { MessageBox.Show($"Error updating flashcard: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private async Task LoadDataAsync() { try { if (isOnline) { // We assume that real-time listener will update the data // So we don't fetch all data here } // After data is loaded, populate the ContextMenuStrip PopulateColumnContextMenu(); } catch (Exception ex) { MessageBox.Show($"Error loading data: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ApplyFiltersAndSort() { // Başlangıç olarak tüm flashcard'ları al IEnumerable<FlashcardItem> filtered = allFlashcards; // Favoriler filtresini uygula if (chkFilterFavorites.Checked) { filtered = filtered.Where(f => f.favorite); } // Sabitlenmiş filtresini uygula if (chkFilterPinned.Checked) { filtered = filtered.Where(f => f.pinned); } // Custom Tag seçili değilse kategori filtresini uygula if (string.IsNullOrEmpty(selectedCustomTag)) { if (!string.IsNullOrEmpty(selectedTag)) { if (selectedTag.Equals("All Categories", StringComparison.OrdinalIgnoreCase)) { // "All Categories" seçildiğinde, kategori filtresi uygulama // Tüm kategoriler gösterilir } else if (selectedTag.Equals("uncategorized", StringComparison.OrdinalIgnoreCase)) { // "uncategorized" seçildiğinde sadece bu kategoriye sahip flashcard'ları göster filtered = filtered.Where(f => f.category.Equals("uncategorized", StringComparison.OrdinalIgnoreCase)); } else { // Diğer kategoriler için normal filtreleme filtered = filtered.Where(f => f.category.Equals(selectedTag, StringComparison.OrdinalIgnoreCase)); } } } // Arama filtresini uygula if (!string.IsNullOrWhiteSpace(currentSearchTerm)) { filtered = filtered.Where(f => f.title.ToLower().Contains(currentSearchTerm) || f.category.ToLower().Contains(currentSearchTerm) || f.content.ToLower().Contains(currentSearchTerm)); } // Listeye dönüştür List<FlashcardItem> filteredList = filtered.ToList(); // Sıralama işlemini uygula if (!string.IsNullOrEmpty(currentSortColumn)) { if (sortAscending) { switch (currentSortColumn) { case "title": filteredList = filteredList.OrderBy(f => f.title).ToList(); break; case "timestamp": filteredList = filteredList.OrderBy(f => f.timestamp).ToList(); break; } } else { switch (currentSortColumn) { case "title": filteredList = filteredList.OrderByDescending(f => f.title).ToList(); break; case "timestamp": filteredList = filteredList.OrderByDescending(f => f.timestamp).ToList(); break; } } } UpdateDataGridView(filteredList); } private void UpdateDataGridView(List<FlashcardItem> flashcards) { // SelectionChanged olayını geçici olarak devre dışı bırak dataGridView.SelectionChanged -= DataGridView_SelectionChanged; // DataGridView'i temizlemeden önce mevcut sütunları ve görünümleri kontrol et var columnSettings = new Dictionary<string, bool>(); foreach (DataGridViewColumn column in dataGridView.Columns) { columnSettings[column.Name] = column.Visible; } dataGridView.DataSource = null; dataGridView.Columns.Clear(); if (flashcards.Any()) { dataGridView.AutoGenerateColumns = false; // Define DataGridView columns // ID Column - Hidden var idColumn = new DataGridViewTextBoxColumn { DataPropertyName = "id", HeaderText = "ID", Name = "id", Visible = false }; dataGridView.Columns.Add(idColumn); // Category Column var categoryColumn = new DataGridViewTextBoxColumn { DataPropertyName = "category", HeaderText = "Category", Name = "category", SortMode = DataGridViewColumnSortMode.NotSortable }; dataGridView.Columns.Add(categoryColumn); // Title Column var titleColumn = new DataGridViewTextBoxColumn { DataPropertyName = "title", HeaderText = "Title", Name = "title", SortMode = DataGridViewColumnSortMode.Programmatic }; dataGridView.Columns.Add(titleColumn); // Content Column var contentColumn = new DataGridViewTextBoxColumn { DataPropertyName = "content", HeaderText = "Content", Name = "content", SortMode = DataGridViewColumnSortMode.NotSortable }; dataGridView.Columns.Add(contentColumn); // Favorite Column (Checkbox) var favoriteColumn = new DataGridViewCheckBoxColumn { DataPropertyName = "favorite", HeaderText = "Favorite", Name = "favorite", SortMode = DataGridViewColumnSortMode.Automatic }; dataGridView.Columns.Add(favoriteColumn); // Pinned Column (Checkbox) var pinnedColumn = new DataGridViewCheckBoxColumn { DataPropertyName = "pinned", HeaderText = "Pinned", Name = "pinned", SortMode = DataGridViewColumnSortMode.Automatic }; dataGridView.Columns.Add(pinnedColumn); // Timestamp Column var timestampColumn = new DataGridViewTextBoxColumn { DataPropertyName = "timestamp", HeaderText = "Timestamp", Name = "timestamp", SortMode = DataGridViewColumnSortMode.Programmatic }; dataGridView.Columns.Add(timestampColumn); // BackgroundColor Column var backgroundColorColumn = new DataGridViewTextBoxColumn { DataPropertyName = "backgroundColor", HeaderText = "Background Color", Name = "backgroundColor", SortMode = DataGridViewColumnSortMode.NotSortable }; dataGridView.Columns.Add(backgroundColorColumn); dataGridView.DataSource = flashcards; dataGridView.ClearSelection(); // Seçimi temizle // Sütun görünürlüklerini geri yükle foreach (DataGridViewColumn column in dataGridView.Columns) { if (columnSettings.ContainsKey(column.Name)) { column.Visible = columnSettings[column.Name]; } } } else { // If no flashcards match the filters, display a message var messageColumn = new DataGridViewTextBoxColumn { HeaderText = "Message", Name = "Message", AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill }; dataGridView.Columns.Add(messageColumn); dataGridView.Rows.Add("No flashcards found."); } // Restore column visibility state RestoreColumnVisibilityState(); // Update the status label with the count statusLabel.Text = $"Total Items: {flashcards.Count}"; // SelectionChanged olayını tekrar etkinleştir dataGridView.SelectionChanged += DataGridView_SelectionChanged; } /// <summary> /// Populates the ContextMenuStrip with the current DataGridView columns. /// Ensures no duplicate menu items are added. /// </summary> private void PopulateColumnContextMenu() { columnContextMenu.Items.Clear(); // Clear existing items to prevent duplication foreach (DataGridViewColumn column in dataGridView.Columns) { // Skip hidden or irrelevant columns if necessary // For example, you might want to skip the "ID" column if (column.Name == "id") continue; // Create a ToolStripMenuItem for the column var menuItem = new ToolStripMenuItem(column.HeaderText) { Checked = column.Visible, CheckOnClick = true, Tag = column // Store the column in Tag for reference }; menuItem.CheckedChanged += ColumnMenuItem_CheckedChanged; // Add the menu item to the ContextMenuStrip columnContextMenu.Items.Add(menuItem); } } /// <summary> /// Handles the CheckedChanged event of ContextMenuStrip items to toggle column visibility. /// </summary> private void ColumnMenuItem_CheckedChanged(object sender, EventArgs e) { if (sender is ToolStripMenuItem menuItem && menuItem.Tag is DataGridViewColumn column) { column.Visible = menuItem.Checked; columnVisibilityState[column.Name] = column.Visible; // Update the visibility state } } /// <summary> /// Shows the ContextMenuStrip when the user right-clicks on a column header. /// </summary> private void DataGridView_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { var hitTestInfo = dataGridView.HitTest(e.X, e.Y); if (hitTestInfo.Type == DataGridViewHitTestType.ColumnHeader) { // Show the ContextMenuStrip at the mouse position columnContextMenu.Show(dataGridView, new Point(e.X, e.Y)); } } } /// <summary> /// Handles the Form Load event to initially load data and start real-time listener. /// </summary> private async void MainForm_Load(object sender, EventArgs e) { LoadCustomTags(); // Eklendi // Load local data first LoadLocalData(); LoadOfflineChanges(); // Yeni eklenen ApplyFiltersAndSort(); // Varsayılan sıralamayı ayarladık currentSortColumn = "timestamp"; sortAscending = false; // Start online status timer onlineStatusTimer.Start(); if (CheckInternetConnection()) { isOnline = true; // Start real-time listener if not already started if (!isListening) { RealTimeListener(); } await ProcessOfflineChanges(); } else { isOnline = false; } // Populate Filter Categories menu after data is loaded PopulateFilterCategoriesMenu(); } /// <summary> /// Adds a new flashcard to the Firebase database and local storage. /// </summary> private async void AddData() { var newFlashcard = CreateFlashcardFromInputs(); if (newFlashcard != null) { try { // Check if the flashcard already exists to prevent duplicate entries if (IsDuplicateFlashcard(newFlashcard)) { MessageBox.Show("This flashcard already exists.", "Duplicate Entry", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } newFlashcard.id = Guid.NewGuid().ToString(); if (isOnline) { await firebaseClient .Child("flashcards") .Child(newFlashcard.id) .PutAsync(newFlashcard); // Do not add to allFlashcards here; real-time listener will handle it } else { // Add to offline changes offlineChanges.Add(new FlashcardChange { ChangeType = ChangeType.Add, Flashcard = newFlashcard }); SaveOfflineChanges(); // Offline changes'i kaydet // Update local data allFlashcards.Add(newFlashcard); SaveLocalData(); ApplyFiltersAndSort(); } ClearInputs(); // Refresh Filter Categories menu as a new category might have been added PopulateFilterCategoriesMenu(); } catch (Exception ex) { MessageBox.Show($"Error adding flashcard: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } /// <summary> /// Checks if a flashcard with the same content already exists. /// </summary> private bool IsDuplicateFlashcard(FlashcardItem newFlashcard) { return allFlashcards.Any(f => f.title == newFlashcard.title && f.category == newFlashcard.category && f.content == newFlashcard.content); } /// <summary> /// Updates the selected flashcard in the Firebase database and local storage. /// </summary> private async void UpdateData() { if (dataGridView.SelectedRows.Count > 0) { var selectedFlashcard = (FlashcardItem)dataGridView.SelectedRows[0].DataBoundItem; var updatedFlashcard = CreateFlashcardFromInputs(); if (updatedFlashcard != null) { updatedFlashcard.id = selectedFlashcard.id; updatedFlashcard.timestamp = selectedFlashcard.timestamp; // Zaman damgasını koru // Check for duplicates excluding the current flashcard if (IsDuplicateFlashcardExcludingCurrent(updatedFlashcard)) { MessageBox.Show("A flashcard with the same content already exists.", "Duplicate Entry", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { if (isOnline) { await firebaseClient .Child("flashcards") .Child(updatedFlashcard.id) .PutAsync(updatedFlashcard); // Do not update allFlashcards here; real-time listener will handle it } else { // Add to offline changes offlineChanges.Add(new FlashcardChange { ChangeType = ChangeType.Update, Flashcard = updatedFlashcard }); SaveOfflineChanges(); // Offline changes'i kaydet // Update local data var index = allFlashcards.FindIndex(f => f.id == updatedFlashcard.id); if (index >= 0) { allFlashcards[index] = updatedFlashcard; SaveLocalData(); ApplyFiltersAndSort(); } } ClearInputs(); // Refresh Filter Categories menu as category might have changed PopulateFilterCategoriesMenu(); } catch (Exception ex) { MessageBox.Show($"Error updating flashcard: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } else { MessageBox.Show("Please select a flashcard to update.", "No Selection", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } /// <summary> /// Checks for duplicates excluding the current flashcard being updated. /// </summary> private bool IsDuplicateFlashcardExcludingCurrent(FlashcardItem updatedFlashcard) { return allFlashcards.Any(f => f.id != updatedFlashcard.id && f.title == updatedFlashcard.title && f.category == updatedFlashcard.category && f.content == updatedFlashcard.content); } /// <summary> /// Deletes selected flashcards from the Firebase database and local storage. /// </summary> private async void DeleteData() { if (dataGridView.SelectedRows.Count > 0) { int selectedCount = dataGridView.SelectedRows.Count; var confirmResult = MessageBox.Show($"Are you sure you want to delete {selectedCount} flashcard(s)?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (confirmResult == DialogResult.Yes) { try { var idsToDelete = dataGridView.SelectedRows .Cast<DataGridViewRow>() .Select(row => ((FlashcardItem)row.DataBoundItem).id) .ToList(); if (isOnline) { // Create a list of delete tasks var deleteTasks = idsToDelete .Select(id => firebaseClient.Child("flashcards").Child(id).DeleteAsync()) .ToList(); // Execute all delete tasks in parallel await Task.WhenAll(deleteTasks); // Do not remove from allFlashcards; real-time listener will handle it } else { // Add to offline changes foreach (var id in idsToDelete) { var flashcard = allFlashcards.FirstOrDefault(f => f.id == id); if (flashcard != null) { offlineChanges.Add(new FlashcardChange { ChangeType = ChangeType.Delete, Flashcard = flashcard }); } } SaveOfflineChanges(); // Offline changes'i kaydet // Remove from local data allFlashcards.RemoveAll(f => idsToDelete.Contains(f.id)); SaveLocalData(); ApplyFiltersAndSort(); } // Clear inputs ClearInputs(); MessageBox.Show($"{selectedCount} flashcard(s) deleted successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); // Refresh Filter Categories menu as categories might have been deleted PopulateFilterCategoriesMenu(); } catch (Exception ex) { MessageBox.Show($"Error deleting flashcards: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } else { MessageBox.Show("Please select one or more flashcards to delete.", "No Selection", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } /// <summary> /// Creates a FlashcardItem object from the input fields. /// </summary> private FlashcardItem CreateFlashcardFromInputs() { string title = txtTitle.Text.Trim(); string content = txtContent.Text.Trim(); string backgroundColor = txtBackgroundColor.Text.Trim(); // Kategori belirleme string category; if (!string.IsNullOrWhiteSpace(selectedCustomTag)) { category = selectedCustomTag; } else if (!string.IsNullOrWhiteSpace(txtCategory.Text)) { category = txtCategory.Text.Trim(); } else { category = "uncategorized"; } return new FlashcardItem { title = title, category = category, content = content, favorite = chkFavorite.Checked, pinned = chkPinned.Checked, timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), backgroundColor = backgroundColor }; } /// <summary> /// Handles the selection change in the DataGridView to populate the input fields. /// </summary> private void DataGridView_SelectionChanged(object sender, EventArgs e) { if (dataGridView.SelectedRows.Count > 0) { var selectedFlashcard = (FlashcardItem)dataGridView.SelectedRows[0].DataBoundItem; txtTitle.Text = selectedFlashcard.title; txtTitle.ForeColor = Color.Black; txtCategory.Text = selectedFlashcard.category; txtCategory.ForeColor = Color.Black; txtContent.Text = selectedFlashcard.content; txtContent.ForeColor = Color.Black; txtBackgroundColor.Text = selectedFlashcard.backgroundColor; txtBackgroundColor.ForeColor = Color.Black; chkFavorite.Checked = selectedFlashcard.favorite; chkPinned.Checked = selectedFlashcard.pinned; } else { // Seçim yoksa metin kutularını temizle ClearInputs(); } } /// <summary> /// Sets up a real-time listener to Firebase to update data upon changes. /// </summary> private void RealTimeListener() { isListening = true; firebaseClient .Child("flashcards") .AsObservable<FlashcardItem>() .Subscribe(d => { if (d.Object != null) { HandleRealTimeUpdate(d.Key, d.EventType, d.Object); } else if (d.EventType == FirebaseEventType.Delete) { HandleRealTimeUpdate(d.Key, d.EventType, null); } }); } /// <summary> /// Handles real-time updates from Firebase. /// </summary> /// <param name="key">Firebase key</param> /// <param name="eventType">Event Type</param> /// <param name="flashcard">The updated flashcard item.</param> private void HandleRealTimeUpdate(string key, FirebaseEventType eventType, FlashcardItem flashcard) { Invoke((Action)(() => { var index = allFlashcards.FindIndex(f => f.id == key); if (eventType == FirebaseEventType.Delete) { if (index >= 0) { allFlashcards.RemoveAt(index); SaveLocalData(); ApplyFiltersAndSort(); // Refresh Filter Categories menu as categories might have been removed PopulateFilterCategoriesMenu(); } } else if (flashcard != null) { // Ensure that the id is set properly flashcard.id = key; if (index >= 0) { // Update existing item allFlashcards[index] = flashcard; } else { // Add new item only if it doesn't exist allFlashcards.Add(flashcard); } SaveLocalData(); ApplyFiltersAndSort(); // Refresh Filter Categories menu as new categories might have been added PopulateFilterCategoriesMenu(); } })); } private void SaveLocalData() { try { string json = JsonConvert.SerializeObject(allFlashcards); File.WriteAllText(localDataFilePath, json); } catch (Exception ex) { MessageBox.Show($"Error saving local data: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void LoadLocalData() { if (File.Exists(localDataFilePath)) { try { string json = File.ReadAllText(localDataFilePath); allFlashcards = JsonConvert.DeserializeObject<List<FlashcardItem>>(json); } catch (Exception ex) { MessageBox.Show($"Error loading local data: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { allFlashcards = new List<FlashcardItem>(); } } /// <summary> /// Checks if there is an active internet connection. /// </summary> /// <returns>True if online, otherwise false.</returns> private bool CheckInternetConnection() { try { using (var client = new System.Net.WebClient()) using (client.OpenRead("http://clients3.google.com/generate_204")) return true; } catch { return false; } } /// <summary> /// Handles the Search button click to apply search criteria. /// </summary> private void SearchData() { string searchText = txtSearch.Text; if (string.IsNullOrWhiteSpace(searchText)) { currentSearchTerm = ""; } else { currentSearchTerm = searchText.ToLower(); } ApplyFiltersAndSort(); } /// <summary> /// Clears the search input and resets search filter. /// </summary> private void ClearSearch() { txtSearch.Text = ""; currentSearchTerm = ""; ApplyFiltersAndSort(); } /// <summary> /// Formats the timestamp column to display human-readable dates. /// </summary> private void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (dataGridView.Columns[e.ColumnIndex].Name == "timestamp") { if (e.Value != null && long.TryParse(e.Value.ToString(), out long timestamp)) { DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(timestamp); DateTime dateTime = dateTimeOffset.ToLocalTime().DateTime; e.Value = dateTime.ToString("yyyy-MM-dd HH:mm:ss"); e.FormattingApplied = true; } } } private string GetSelectedCategory() { if (!string.IsNullOrWhiteSpace(selectedCustomTag)) { return selectedCustomTag; } if (tagCheckedListBox.CheckedItems.Count > 0) { return tagCheckedListBox.CheckedItems[0].ToString(); } return "uncategorized"; } private async Task SaveFlashcardToDatabase(FlashcardItem flashcard) { try { // Check if the flashcard already exists to prevent duplicate entries if (IsDuplicateFlashcard(flashcard)) { // You can choose to notify the user here if desired return; } flashcard.id = Guid.NewGuid().ToString(); if (isOnline) { await firebaseClient .Child("flashcards") .Child(flashcard.id) .PutAsync(flashcard); // Do not add to allFlashcards here; real-time listener will handle it } else { // Add to offline changes offlineChanges.Add(new FlashcardChange { ChangeType = ChangeType.Add, Flashcard = flashcard }); SaveOfflineChanges(); // Offline changes'i kaydet // Add to local data allFlashcards.Add(flashcard); SaveLocalData(); ApplyFiltersAndSort(); } // Refresh Filter Categories menu as a new category might have been added PopulateFilterCategoriesMenu(); } catch (Exception ex) { // Hata yönetimi } } private void LoadTagsMenuItem_Click(object sender, EventArgs e) { using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) { folderBrowserDialog.Description = "Klasör Seçin"; if (folderBrowserDialog.ShowDialog() == DialogResult.OK) { string selectedFolder = folderBrowserDialog.SelectedPath; // Klasördeki ve alt klasörlerdeki PDF dosyalarını al string[] pdfFiles = Directory.GetFiles(selectedFolder, "*.pdf", SearchOption.AllDirectories); // Dosya isimlerini al (uzantısız) List<string> tags = pdfFiles.Select(file => Path.GetFileNameWithoutExtension(file)).ToList(); // CheckedListBox'ı güncelle tagCheckedListBox.Items.Clear(); foreach (var tag in tags) { tagCheckedListBox.Items.Add(tag); } } } } private async void OnlineStatusTimer_Tick(object sender, EventArgs e) { bool currentlyOnline = CheckInternetConnection(); if (currentlyOnline && !isOnline) { // We were offline, now online isOnline = true; await ProcessOfflineChanges(); // Start real-time listener if not already started if (!isListening) { RealTimeListener(); } } else if (!currentlyOnline && isOnline) { // We were online, now offline isOnline = false; } } private async Task ProcessOfflineChanges() { if (offlineChanges == null || !offlineChanges.Any()) return; foreach (var change in offlineChanges.ToList()) // ToList() kullanarak koleksiyonun değişmesini önler { try { switch (change.ChangeType) { case ChangeType.Add: // Assume change.Flashcard.id already set await firebaseClient .Child("flashcards") .Child(change.Flashcard.id) .PutAsync(change.Flashcard); break; case ChangeType.Update: await firebaseClient .Child("flashcards") .Child(change.Flashcard.id) .PutAsync(change.Flashcard); break; case ChangeType.Delete: await firebaseClient .Child("flashcards") .Child(change.Flashcard.id) .DeleteAsync(); break; } } catch (Exception ex) { // Herhangi bir hata durumunda süreci durdurabilir veya devam edebilirsiniz MessageBox.Show($"Error processing offline change: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } // Tüm offline değişiklikler işlendi, listeyi temizle offlineChanges.Clear(); SaveOfflineChanges(); // Optional: Delete the offlineChangesFile if exists try { if (File.Exists(offlineChangesFilePath)) { File.Delete(offlineChangesFilePath); } } catch (Exception ex) { MessageBox.Show($"Error deleting offline changes file: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// <summary> /// Adds a new change to the offlineChanges list and saves it. /// </summary> private void AddOfflineChange(ChangeType changeType, FlashcardItem flashcard) { offlineChanges.Add(new FlashcardChange { ChangeType = changeType, Flashcard = flashcard }); SaveOfflineChanges(); } /// <summary> /// Saves the offlineChanges list to a local file. /// </summary> private void SaveOfflineChanges() { try { string json = JsonConvert.SerializeObject(offlineChanges); File.WriteAllText(offlineChangesFilePath, json); } catch (Exception ex) { MessageBox.Show($"Error saving offline changes: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } /// <summary> /// Loads the offlineChanges list from a local file. /// </summary> private void LoadOfflineChanges() { if (File.Exists(offlineChangesFilePath)) { try { string json = File.ReadAllText(offlineChangesFilePath); offlineChanges = JsonConvert.DeserializeObject<List<FlashcardChange>>(json) ?? new List<FlashcardChange>(); } catch (Exception ex) { MessageBox.Show($"Error loading offline changes: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); offlineChanges = new List<FlashcardChange>(); } } else { offlineChanges = new List<FlashcardChange>(); } } /// Represents a Flashcard item. /// </summary> public class FlashcardItem { public string id { get; set; } public string category { get; set; } public string title { get; set; } public string content { get; set; } public bool favorite { get; set; } public bool pinned { get; set; } public long timestamp { get; set; } public string backgroundColor { get; set; } } public enum ChangeType { Add, Update, Delete } public class FlashcardChange { public ChangeType ChangeType { get; set; } public FlashcardItem Flashcard { get; set; } } - Assistant