From 8bfb61a37463f28eac7e44cf377ff0ec84221732 Mon Sep 17 00:00:00 2001 From: Ajay Nair Date: Thu, 16 Jan 2025 02:21:28 -0400 Subject: [PATCH] Added export history feature Signed-off-by: Ajay Nair --- src/Calculator/Views/HistoryList.xaml | 8 +++ src/Calculator/Views/HistoryList.xaml.cs | 72 +++++++++++++++++++++++- 2 files changed, 79 insertions(+), 1 deletion(-) diff --git a/src/Calculator/Views/HistoryList.xaml b/src/Calculator/Views/HistoryList.xaml index 8988c336..c7230aa1 100644 --- a/src/Calculator/Views/HistoryList.xaml +++ b/src/Calculator/Views/HistoryList.xaml @@ -176,6 +176,14 @@ Content="" ToolTipService.ToolTip="{utils:ResourceString Name=ClearHistory/[using:Windows.UI.Xaml.Controls]ToolTipService/ToolTip}" Visibility="{x:Bind Model.ItemsCount, Mode=OneWay, Converter={StaticResource ItemSizeToVisibilityNegationConverter}}"/> + + diff --git a/src/Calculator/Views/HistoryList.xaml.cs b/src/Calculator/Views/HistoryList.xaml.cs index 639c6dee..cab6d7c8 100644 --- a/src/Calculator/Views/HistoryList.xaml.cs +++ b/src/Calculator/Views/HistoryList.xaml.cs @@ -1,6 +1,11 @@ using CalculatorApp.ViewModel; using CalculatorApp.ViewModel.Common; - +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using Windows.Storage; +using Windows.Storage.Pickers; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; @@ -77,6 +82,71 @@ namespace CalculatorApp Model.DeleteItem(swipedItem); } } + + private async void ExportButton_Click(object sender, RoutedEventArgs e) + { + var history = (CalculatorApp.ViewModel.HistoryViewModel)this.DataContext; + + + if (history.ItemsCount == 0) + { + return; // No history to export + } + + Debug.WriteLine("Opening save picker"); + + var savePicker = new FileSavePicker + { + SuggestedStartLocation = PickerLocationId.DocumentsLibrary, + SuggestedFileName = "CalculatorHistory" + }; + + Debug.WriteLine("Adding choice"); + + savePicker.FileTypeChoices.Add("Plain Text", new List { ".txt" }); + savePicker.FileTypeChoices.Add("CSV File", new List { ".csv" }); + + StorageFile file = await savePicker.PickSaveFileAsync(); + + if (file == null) + { + return; // User cancelled + } + + try + { + var content = new StringBuilder(); + bool isCsv = file.FileType.Equals(".csv", System.StringComparison.OrdinalIgnoreCase); + + if (isCsv) + { + content.AppendLine("Expression,Result"); + } + + foreach (var item in history.Items) + { + if (isCsv) + { + // Escape quotes and commas for CSV + var expression = item.Expression.Replace("\"", "\"\""); + var result = item.Result.Replace("\"", "\"\""); + content.AppendLine($"\"{expression}\",\"{result}\""); + } + else + { + content.AppendLine($"{item.Expression} = {item.Result}"); + } + } + + await FileIO.WriteTextAsync(file, content.ToString()); + } + catch (Exception ex) + { + // Log error and show user-friendly message + Debug.WriteLine($"Error exporting history: {ex.Message}"); + // You might want to show a dialog here to inform the user + } + } } }