/// <summary> /// Saves to CSV. /// </summary> /// <param name="weatherDataCollection">The weather data collection.</param> public static async void SaveToCsv(WeatherDataCollection weatherDataCollection) { var fileSaver = new FileSavePicker { SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; fileSaver.FileTypeChoices.Add("CSV", new List <string> { ".csv" }); var saveFile = await fileSaver.PickSaveFileAsync(); if (saveFile != null) { CachedFileManager.DeferUpdates(saveFile); var dataForFile = new StringBuilder(); foreach (var day in weatherDataCollection) { dataForFile.Append($"{day.Date.ToShortDateString()},{day.High},{day.Low}{Environment.NewLine}"); } await FileIO.WriteTextAsync(saveFile, dataForFile.ToString()); } }
private void createHistogram(StringBuilder report, WeatherDataCollection tempWeatherCollection, int lowerBound, int upperBound, int bucketSize, HighLow highOrLow) { var initialTierLowerBound = lowerBound - (lowerBound % bucketSize); int initialOffset = 1; var initialTierUpperBound = initialTierLowerBound + bucketSize - initialOffset; var highestTierOffset = bucketSize - 1; var finalTierUpperBound = upperBound - upperBound % bucketSize + highestTierOffset; while (initialTierLowerBound <= finalTierUpperBound) { int countOfDays; if (highOrLow.Equals(HighLow.High)) { countOfDays = tempWeatherCollection.CountDaysWithHighBetween(initialTierLowerBound, initialTierUpperBound); } else { countOfDays = tempWeatherCollection.CountDaysWithLowBetween(initialTierLowerBound, initialTierUpperBound); } report.Append( $"{initialTierLowerBound}-{initialTierUpperBound}: {countOfDays} {Environment.NewLine}"); initialTierLowerBound = initialTierLowerBound + bucketSize; initialTierUpperBound = initialTierUpperBound + bucketSize; } }
private async Task handleNewFileWithExistingFile(WeatherDataCollection newWeatherCollection) { var existingFileDialog = new ContentDialog { Title = "File Already Loaded", Content = "A file has already been loaded, how would you like to handle this?", PrimaryButtonText = "Replace Current File", SecondaryButtonText = "Merge the Files" }; var result = await existingFileDialog.ShowAsync(); switch (result) { case ContentDialogResult.Primary: this.currentWeatherCollection = newWeatherCollection; break; case ContentDialogResult.Secondary: { var fileMerger = new FileMerger(); newWeatherCollection = await fileMerger.MergeWeatherDataCollections(this.currentWeatherCollection, newWeatherCollection); this.currentWeatherCollection = newWeatherCollection; break; } } }
private void createMonthlyBreakdown(WeatherDataCollection daysForReport, StringBuilder report) { var highestTemp = daysForReport.GetDaysWithHighestTempForEachMonth(); var lowestTemp = daysForReport.GetDaysWithLowestTempForEachMonth(); var averageHigh = daysForReport.GetAverageHighTempForEachMonth(); var averageLow = daysForReport.GetAverageLowTempForEachMonth(); var monthCount = 1; for (var i = 0; i < daysForReport.GroupByMonth().Count; i++) { while (highestTemp[i][0].Date.Month != monthCount && monthCount < 12) { var prevMonthName = DateTimeFormatInfo.CurrentInfo.GetMonthName(monthCount); var prevMonthYear = highestTemp[i][0].Date.Year; var prevMonthsDaysOfData = " (0 days of data)"; report.Append(prevMonthName + $" {prevMonthYear}" + prevMonthsDaysOfData + Environment.NewLine); report.Append(Environment.NewLine); monthCount++; } var monthName = highestTemp[i][0].Date.ToString("MMMM", CultureInfo.InvariantCulture); var year = highestTemp[i][0].Date.Year; var daysOfData = $" ({daysForReport.GroupByMonth()[i].Count} days of data)"; report.Append(monthName + $" {year}" + daysOfData + Environment.NewLine); this.formatHighestTempForMonths(highestTemp, i, report); this.formatLowestTempForMonths(lowestTemp, i, report); report.Append($"Average High: {averageHigh[i]:F}" + Environment.NewLine); report.Append($"Average Low: {averageLow[i]:F}" + Environment.NewLine); report.Append(Environment.NewLine); monthCount++; } }
private void createOverview(WeatherDataCollection daysForReport, StringBuilder report) { var dates = new List <string>(); foreach (var current in daysForReport.GetDaysWithHighestLowTempByYear()) { dates.Add(current.Date.ToShortDateString()); } var daysWithHighestLow = string.Join(", ", dates); report.Append( $"Highest temp occurred on {this.formatDaysWithHighestTempForYear(daysForReport)}: {daysForReport.GetDaysWithHighestTempForAYear()[0].High}" + Environment.NewLine); report.Append( $"Lowest temp occurred on {this.formatDaysWithLowestTempForYear(daysForReport)}: {daysForReport.GetDaysWithLowestTempByYear()[0].Low}" + Environment.NewLine); report.Append( $"Lowest high temp occurred on {this.formatDaysWithLowestHighTempForYear(daysForReport)}: {daysForReport.GetDaysWithLowestHighTempByYear()[0].High}" + Environment.NewLine); report.Append( $"Highest low temp occurred on {daysWithHighestLow}: {daysForReport.GetDaysWithHighestLowTempByYear()[0].Low}" + Environment.NewLine); report.Append($"The average high: {daysForReport.GetAverageHighTempForYear():F}" + Environment.NewLine); report.Append($"The average low: {daysForReport.GetAverageLowTempForYear():F}" + Environment.NewLine); report.Append( $"Number of days with temp {this.upperBound} or greater: {daysForReport.GetDaysWithTempGreaterThanEqualTo(this.upperBound)}" + Environment.NewLine); report.Append( $"Number of days with temp {this.lowerBound} or less: {daysForReport.GetDaysWithTempLessThanEqualTo(this.lowerBound)}" + Environment.NewLine); }
/// <summary> /// Adds the new day. /// </summary> /// <param name="weatherDataCollection">The weather data collection.</param> public static async Task <WeatherDataCollection> AddNewDay(WeatherDataCollection weatherDataCollection) { var addNewDayDialog = new AddDayContentDialog(); await addNewDayDialog.ShowAsync(); var newDay = addNewDayDialog.NewDay; if (newDay != null) { if (weatherDataCollection == null) { weatherDataCollection = new WeatherDataCollection { newDay }; } else if (weatherDataCollection.Count == 0) { weatherDataCollection.Add(newDay); } else { var tempWeatherCollection = new WeatherDataCollection { newDay }; var fileMerger = new FileMerger(); weatherDataCollection = await fileMerger.MergeWeatherDataCollections(weatherDataCollection, tempWeatherCollection); } } return(weatherDataCollection); }
/// <summary> /// Parses the temperature file asynchronous. /// </summary> /// <param name="tempFile">The temporary file.</param> /// <returns>A collection of weather data</returns> public async Task <WeatherDataCollection> ParseTemperatureFileAsync(StorageFile tempFile) { var days = new WeatherDataCollection(); var fileText = await FileIO.ReadTextAsync(tempFile); var lines = fileText.Split(Environment.NewLine); var lineNumber = 0; foreach (var day in lines) { lineNumber++; try { var fields = day.Split(","); var date = DateTime.Parse(fields[(int)WeatherDataFields.Date]); var high = Convert.ToInt16(fields[(int)WeatherDataFields.High]); var low = Convert.ToInt16(fields[(int)WeatherDataFields.Low]); days.Add(new WeatherData(date, high, low)); } catch (Exception) { this.ErrorMessages.Append($"Corrupt Data on line {lineNumber} {Environment.NewLine}"); } } return(days); }
private async void addDayButton_Click(object sender, RoutedEventArgs e) { this.currentWeatherCollection = await DayAdder.AddNewDay(this.currentWeatherCollection); var reportBuilder = new WeatherReportBuilder(this.lowerBound, this.upperBound); var report = reportBuilder.CreateReport(this.currentWeatherCollection, this.getBucketSize()); this.summaryTextBox.Text = report + this.errors; }
/// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { WeatherDataCollection clone = new WeatherDataCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((WeatherData)Utils.Clone(this[ii])); } return(clone); }
private string formatDaysWithHighestTempForYear(WeatherDataCollection daysForReport) { var dates = new List <string>(); foreach (var current in daysForReport.GetDaysWithHighestTempForAYear()) { dates.Add(current.Date.ToShortDateString()); } var daysWithHighest = string.Join(",", dates); return(daysWithHighest); }
/// <summary> /// Initializes a new instance of the <see cref="MainPage" /> class. /// </summary> public MainPage() { this.InitializeComponent(); ApplicationView.PreferredLaunchViewSize = new Size { Width = ApplicationWidth, Height = ApplicationHeight }; ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize; ApplicationView.GetForCurrentView().SetPreferredMinSize(new Size(ApplicationWidth, ApplicationHeight)); this.currentWeatherCollection = null; this.errors = null; }
private void addNonConflictingData(WeatherDataCollection updatedWeatherDataCollection) { var oldNonConflictingData = this.oldWeatherDataCollection.Where(oldDay => !this.newWeatherDataCollection.Any(newDay => newDay.Date.Equals(oldDay.Date))).ToList(); var newNonConflictingData = this.newWeatherDataCollection.Where(newDay => !this.oldWeatherDataCollection.Any(oldDay => oldDay.Date.Equals(newDay.Date))).ToList(); foreach (var day in oldNonConflictingData) { updatedWeatherDataCollection.Add(day); this.oldWeatherDataCollection.Remove(day); } foreach (var day in newNonConflictingData) { updatedWeatherDataCollection.Add(day); this.newWeatherDataCollection.Remove(day); } }
/// <summary> /// Creates the report. /// </summary> /// <param name="daysForReport">The days for report.</param> /// <param name="bucketSize">Size of the bucket.</param> /// <returns> /// A full report outlining specific information based the supplied weather data /// </returns> public string CreateReport(WeatherDataCollection daysForReport, int bucketSize) { var report = new StringBuilder(); this.bucketSize = bucketSize; var years = daysForReport.GroupByYear(); foreach (var year in years) { var tempWeatherCollection = new WeatherDataCollection(); foreach (var day in year) { tempWeatherCollection.Add(day); } } report.Append(Environment.NewLine); this.createYearlyBreakdown(daysForReport, report); return(report.ToString()); }
/// <summary> /// Handles the ClickAsync event of the loadFile control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RoutedEventArgs" /> instance containing the event data.</param> private async void loadFile_ClickAsync(object sender, RoutedEventArgs e) { var filePicker = new FileOpenPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.DocumentsLibrary }; filePicker.FileTypeFilter.Add(".csv"); filePicker.FileTypeFilter.Add(".txt"); var chosenFile = await filePicker.PickSingleFileAsync(); if (chosenFile == null) { this.summaryTextBox.Text = "No file was chosen."; } else { var fileParser = new WeatherFileParser(); int.TryParse(this.lowerBoundTextBox.Text, out this.lowerBound); int.TryParse(this.upperBoundTextBox.Text, out this.upperBound); var reportBuilder = new WeatherReportBuilder(this.lowerBound, this.upperBound); var newWeatherCollection = await fileParser.ParseTemperatureFileAsync(chosenFile); if (this.currentWeatherCollection == null) { this.currentWeatherCollection = newWeatherCollection; } else { await this.handleNewFileWithExistingFile(newWeatherCollection); } this.errors = fileParser.ErrorMessages; var report = reportBuilder.CreateReport(this.currentWeatherCollection, this.getBucketSize()); this.summaryTextBox.Text = report + this.errors; } }
/// <summary> /// Merges the weather data collections. /// </summary> /// <param name="currentDataCollection">The old weather data collection.</param> /// <param name="newWeatherData">The new weather data collection.</param> /// <returns> the collection with the data</returns> public async Task <WeatherDataCollection> MergeWeatherDataCollections( WeatherDataCollection currentDataCollection, WeatherDataCollection newWeatherData) { this.oldWeatherDataCollection = currentDataCollection ?? throw new ArgumentNullException(nameof(this.oldWeatherDataCollection), "Current collection cannot be null."); this.newWeatherDataCollection = newWeatherData ?? throw new ArgumentNullException(nameof(newWeatherData), "New collection cannot be null."); var updatedWeatherDataCollection = new WeatherDataCollection(); this.addNonConflictingData(updatedWeatherDataCollection); foreach (var conflictingDay in this.newWeatherDataCollection) { if (this.oldWeatherDataCollection.Any(oldDay => oldDay.Date.Equals(conflictingDay.Date)) && !this.isDoForAllChecked) { var keepOrReplace = new ReplaceOrKeepDialog(conflictingDay, newWeatherData.Count); this.chosenResult = await keepOrReplace.ShowAsync(); this.isDoForAllChecked = keepOrReplace.IsDoForAllChecked; } this.addConflictingDayToUpdatedCollection(conflictingDay, updatedWeatherDataCollection); } var tempWeatherDataCollection = updatedWeatherDataCollection.ToList(); tempWeatherDataCollection.Sort(); updatedWeatherDataCollection.Clear(); foreach (var day in tempWeatherDataCollection) { updatedWeatherDataCollection.Add(day); } return(updatedWeatherDataCollection); }
private void addConflictingDayToUpdatedCollection(WeatherData currentDay, WeatherDataCollection updatedWeatherDataCollection) { switch (this.chosenResult) { case ContentDialogResult.Primary: try { var oldDay = this.oldWeatherDataCollection.Single(x => x.Date.Equals(currentDay.Date)); updatedWeatherDataCollection.Add(oldDay); } catch (Exception e) { Console.WriteLine(e.Message); } break; case ContentDialogResult.Secondary: updatedWeatherDataCollection.Add(currentDay); break; } }
private void createYearlyBreakdown(WeatherDataCollection daysForReport, StringBuilder report) { var years = daysForReport.GroupByYear(); foreach (var year in years) { var tempWeatherCollection = new WeatherDataCollection(); foreach (var day in year) { tempWeatherCollection.Add(day); } this.createOverview(tempWeatherCollection, report); report.Append(Environment.NewLine); var upperBound = tempWeatherCollection.GetDaysWithHighestTempForAYear()[0].High; var lowerBound = tempWeatherCollection.GetDaysWithLowestHighTempByYear()[0].High; report.Append("Highest Temp Histogram" + Environment.NewLine); this.createHistogram(report, tempWeatherCollection, lowerBound, upperBound, this.bucketSize, HighLow.High); report.Append(Environment.NewLine); upperBound = tempWeatherCollection.GetDaysWithHighestLowTempByYear()[0].Low; lowerBound = tempWeatherCollection.GetDaysWithLowestTempByYear()[0].Low; report.Append("Lowest Temp Histogram" + Environment.NewLine); this.createHistogram(report, tempWeatherCollection, lowerBound, upperBound, this.bucketSize, HighLow.Low); report.Append(Environment.NewLine); this.createMonthlyBreakdown(tempWeatherCollection, report); } }
private void clearDataButton_Click(object sender, RoutedEventArgs e) { this.currentWeatherCollection = null; this.summaryTextBox.Text = string.Empty; }