0.6 First Day Assignment [1 hour 30 minutes]

Overview
Acceptance Criteria
  • Your CSV has the headings Course Number, Course Name, and Credits, with one course per row.
  • Clicking Load courses CSV reads Courses.csv from the application's working directory and displays three columns.
  • Each column can be sorted in ascending or descending order.
  • Credits sort as numbers, and course numbers remain text.
  • An invalid CSV displays a message without replacing the previously loaded courses.
  • The student, breakfast, backpack, clothing, shopping-list, and weather features still work.
Instructions
1.Open Your Existing Solution [10 minutes]

Continue your completed 0.5 First Day application. Create a CSV file containing course numbers, course names, and credits. Add a button that opens the file and displays its contents in a table, then sort the table by clicking its column headings.

Goal: Create structured data in a file, load it into an application, and organize it in different ways.

A Back up 0.5 and open your working solution

Close Visual Studio. Copy the entire completed solution folder and name the backup First Day 0.5 Backup LastName. Open LastName.sln from your original working folder. Keep the working folder and solution names unchanged.

B Run your application and check the existing features

Check the shopping-list save and load buttons and the weather feature from 0.5. Close the running application before editing.

2.Create a Course CSV File [15 minutes]

CSV means comma-separated values. Each row represents one course, and commas separate its three values. The first row names the columns.

A Open Notepad and paste this example

Use Notepad to create a plain-text file. Paste the complete example, including its first row. These sample courses let you check text sorting, decimal credits, and numeric sorting.

Courses.csv — paste into a new Notepad document
Course Number,Course Name,Credits
CS 102,Object-Oriented Programming,4
ENG 101,College Writing,3
CS 001,Introduction to Computing,2
ART 110,"Art, Design and Technology",1.5
CAP 200,Capstone Studio,10
B Save the file as Courses.csv in your solution folder

Choose File > Save As. Browse to the working LastName folder containing LastName.sln. Set Save as type to All files, enter Courses.csv, choose UTF-8 encoding, and save. Confirm the filename is Courses.csv, not Courses.csv.txt.

C Check the three columns

Keep the header exactly as shown and in the same order. Each course must have a number, name, and nonnegative numeric credit value. Use a period for decimal credits. A course name containing a comma must be enclosed in double quotes, as shown for Art, Design and Technology.

Course numbers are text identifiers: CS 001 should keep its leading zeros. Credits are numbers: 10 should sort after 4 in ascending order. You will add a course of your own after testing the example.

3.Add the Course Controls [15 minutes]
A Add the Courses panel in Grid row 4

In Solution Explorer, open FirstDayScenario/MainWindow.xaml and switch to XAML source view. Find the shopping-list StackPanel in Grid row 3 and locate its matching closing tag, after both shopping-list buttons. Insert this entire block immediately after that closing tag and before the existing output TextBox in Grid row 5. The new panel must be a direct child of the existing Grid. Row 4 already exists in the Grid row definitions.

MainWindow.xaml — add the Courses panel
<StackPanel Grid.Row="4">
    <TextBlock Text="Courses" FontWeight="Bold" VerticalAlignment="Center" Margin="5,10,0,0" />
    <Button x:Name="loadCoursesButton" HorizontalAlignment="Left" Content="Load courses CSV" Width="125" Margin="5" Click="loadCoursesButton_Click" />
    <DataGrid x:Name="coursesDataGrid" AutoGenerateColumns="True" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserSortColumns="True" ColumnWidth="Auto" Margin="5" />
</StackPanel>
Shows the Courses heading, Load courses CSV button, and course table between the shopping list and output area.
Add the Courses panel

The DataGrid generates its columns from the loaded table and allows column sorting. Save the file. The loadCoursesButton_Click method has not been added yet; complete the next task before building.

4.Add the Supplied Course-Loading Code [30 minutes]
A Check the System.Data framework reference

In Solution Explorer, expand References under the FirstDayScenario project and confirm System.Data is present. If it is missing, right-click References, choose Add Reference, and select System.Data under Assemblies > Framework. The supplied CSV reader uses framework classes and requires no Microsoft.VisualBasic reference.

B Create CourseCsv.cs in the FirstDayScenario project

Right-click the Business Classes folder in the FirstDayScenario project, choose Add > Class, name the file CourseCsv.cs, and click Add. Open that file, select all generated contents, and replace them with the complete code below. Include the using statements, namespace, class, and all braces. This code goes in the new CourseCsv.cs file, not MainWindow.xaml.cs.

CourseCsv.cs — replace the entire file
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Text.RegularExpressions;

namespace FirstDayScenario
{
    /// <summary>
    /// Represents a CSV file containing course information.
    /// </summary>
    public static class CourseCsv
    {
        private static readonly Regex FieldPattern = new Regex("\\G[ \\t]*(?:\"(?<quoted>(?:[^\"]|\"\")*)\"[ \\t]*|(?<plain>[^\",\\r\\n]*))(?<end>,|\\r\\n|\\r|\\n|\\z)");

        /// <summary>
        /// Loads a CSV file containing course information into a DataTable.
        /// </summary>
        /// <param name="fileName">The name of the course CSV file.</param>
        /// <returns>An in-memory DataTable containing course information.</returns>
        public static DataTable Load(string fileName)
        {
            DataTable courses = new DataTable();

            courses.Columns.Add("CourseNumber", typeof(string));
            courses.Columns.Add("CourseName", typeof(string));
            courses.Columns.Add("Credits", typeof(decimal));

            bool headerFound = false;

            foreach (string[] fields in ReadRows(File.ReadAllText(fileName)))
            {
                if (!headerFound)
                {
                    if (fields.Length != 3 ||
                        !string.Equals(fields[0], "Course Number", StringComparison.OrdinalIgnoreCase) ||
                        !string.Equals(fields[1], "Course Name", StringComparison.OrdinalIgnoreCase) ||
                        !string.Equals(fields[2], "Credits", StringComparison.OrdinalIgnoreCase))
                    {
                        throw new FormatException("The first row must be: Course Number,Course Name,Credits");
                    }

                    headerFound = true;

                    continue;
                }

                decimal credits;

                if (fields.Length != 3 ||
                    string.IsNullOrWhiteSpace(fields[0]) ||
                    string.IsNullOrWhiteSpace(fields[1]) ||
                    !decimal.TryParse(fields[2], NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out credits) ||
                    credits < 0)
                {
                    throw new FormatException(
                        "Each row needs a course number, course name, " +
                        "and nonnegative numeric credits.");
                }

                courses.Rows.Add(fields[0], fields[1], credits);
            }

            if (!headerFound)
            {
                throw new FormatException("The CSV file is empty.");
            }

            if (courses.Rows.Count == 0)
            {
                throw new FormatException("Add at least one course beneath the CSV header.");
            }

            return courses;
        }

        private static IEnumerable<string[]> ReadRows(string text)
        {
            int position = 0;

            while (position < text.Length)
            {
                int rowStart = position;
                string delimiter;

                List<string> fields = new List<string>();

                do
                {
                    Match match = FieldPattern.Match(text, position);

                    if (!match.Success)
                    {
                        throw new FormatException("Invalid CSV formatting near character " + (position + 1) + ".");
                    }

                    string value = match.Groups["quoted"].Success
                        ? match.Groups["quoted"].Value.Replace("\"\"", "\"")
                        : match.Groups["plain"].Value;

                    fields.Add(value.Trim());
                    position += match.Length;
                    delimiter = match.Groups["end"].Value;
                }
                while (delimiter == ",");

                if (!string.IsNullOrWhiteSpace(text.Substring(rowStart, position - rowStart)))
                {
                    yield return fields.ToArray();
                }
            }
        }
    }
}

The supplied reader uses a regular expression to read CSV fields and checks the header and each row before returning the table. It handles quoted course names and stores credits as numbers so they sort correctly.

C Check the using statements in MainWindow.xaml.cs

Expand MainWindow.xaml in Solution Explorer and open MainWindow.xaml.cs. At the very top of the file, with its existing using statements and above the namespace line, add any of these lines that are missing. Keep the other using statements. Do not duplicate lines already present.

MainWindow.xaml.cs — required using statements
using System;
using System.IO;
using System.Windows;
D Paste this new method immediately after loadWeatherButton_Click

In MainWindow.xaml.cs, find the declaration of the existing loadWeatherButton_Click method. Place the cursor on a blank line after its closing brace and paste the complete method below. It belongs inside the MainWindow class, outside every other method.

Keep loadWeatherButton_Click and its entire body. Keep the constructor, GetForecastAsync, and every existing event handler. If you already created an empty loadCoursesButton_Click method, replace that empty method with this one instead of adding a second copy.

MainWindow.xaml.cs — add loadCoursesButton_Click
private void loadCoursesButton_Click(object sender, RoutedEventArgs e)
{
    string coursesPath = "Courses.csv";

    if (File.Exists(coursesPath))
    {
        try
        {
            // Only replace the current table after the entire file is valid.
            System.Data.DataTable courses = CourseCsv.Load(coursesPath);
            this.coursesDataGrid.ItemsSource = courses.DefaultView;
            this.textOutput.Text = courses.Rows.Count + " courses loaded. Click a column heading to sort.";
        }
        catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException || ex is FormatException)
        {
            MessageBox.Show(this, ex.Message, "Unable to load courses", MessageBoxButton.OK, MessageBoxImage.Warning);
        }
    }
}

The button reads Courses.csv from the application's working directory. After a valid file is read, ItemsSource connects its table to the DataGrid. If the file is invalid, a message explains the problem and the previous table stays in place. If the file is missing, this handler does nothing.

E Copy Courses.csv into the application's run folder

Keep your original CSV in the solution folder. For the supplied project's default Debug run settings, copy it into FirstDayScenario\bin\Debug beside FirstDayScenario.exe. Build once first if this folder does not exist. The relative filename in the handler is resolved from the application's working directory; if you configured a different working directory, put the copy there instead. Whenever you edit the original CSV, replace this run-folder copy before loading again.

F Save all files and build the solution

Choose Build > Build Solution. If System.Data cannot be found, check its framework reference. If CourseCsv cannot be found, check that CourseCsv.cs was added to the project and contains the complete supplied code. The new button's Click value and C# method must both be spelled loadCoursesButton_Click.

5.Load, Sort, and Check Your Courses [10 minutes]
A Run the application and click Load courses CSV

The button loads the run-folder copy of Courses.csv directly; there is no file picker. Confirm that five courses appear. The course name Art, Design and Technology should occupy one cell even though it contains a comma. The course number CS 001 should retain its zeros.

B Sort the table using each column heading

Click CourseNumber to sort by course number, then click it again to reverse the order. Repeat with CourseName. Click Credits: ascending order should be 1.5, 2, 3, 4, 10. Click it again to reverse the order.

Sorting rearranges the displayed rows. It does not change the CSV file. You do not need to write a separate sorting method; the supplied DataGrid provides column sorting.

C Add one course to the CSV and load it again

Open Courses.csv in Notepad, add a new row with a course number, course name, and numeric credits, and save. Replace the run-folder copy with this updated file. Return to the application, click Load courses CSV, to read the updated file. Confirm that six courses appear. Loading again replaces the table rather than adding duplicate rows. Edit courses in the CSV file; the displayed table is read-only.

D Check an invalid credit value

In Notepad, temporarily change one credit value to three and save. Replace the run-folder copy, then try loading the file. Confirm that an error message appears and the six previously loaded courses remain visible. Change the value back to a number, save, replace the run-folder copy, and load successfully again.

E Check the earlier First Day features

Click New student before Have breakfast or Fill backpack. Check both clothing choices and the shopping-list save and load buttons. Load weather using Chicago's coordinates from 0.5: -87.6298 for Longitude and 41.8781 for Latitude. Confirm the JSON still appears in the browser area.

Submission
6.Final Check and Submit [5 minutes]
A Complete the final check

Confirm the solution builds, your six-course CSV loads, all three columns sort, and the earlier features still work. Restore valid data in Courses.csv before submitting.

B Zip the entire solution folder

Close Visual Studio. Create a ZIP of the working LastName folder. Open the ZIP and confirm it includes LastName.sln, the FirstDayScenario project folder, the new CourseCsv.cs file inside its Business Classes folder, and Courses.csv in the solution folder.

C Submit through the Feedback System and Canvas

Upload the ZIP to First Day 0.6 in the Feedback System. Review the results and correct any required issues. Submit the Feedback System submission URL to the 0.6 First Day Assignment in Canvas.