//**************************************************** // Method: BCS426Homework5DLL.CourseWork ReadFromFile(string filename) // // Purpose: read from the file using serialization // //**************************************************** private BCS426Homework5DLL.CourseWork ReadFromFile(string filename) { //creates a course work instance BCS426Homework5DLL.CourseWork cw = new BCS426Homework5DLL.CourseWork(); FileStream reader = new FileStream(filename, FileMode.Open, FileAccess.Read); //opens the FileStream to read the JSON from DataContractJsonSerializer serializer; //creates an instance of DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(BCS426Homework5DLL.CourseWork)); cw = (BCS426Homework5DLL.CourseWork)serializer.ReadObject(reader); //reads from the file reader.Close(); //closes the file return(cw); //returns the coursework instance }
//**************************************************** // Method: void MenuItemImport_Click(object sender, RoutedEventArgs e) // // Purpose: imports the data from the file into the cleared database // //**************************************************** private void MenuItemImport_Click(object sender, RoutedEventArgs e) { //creates a course work instance BCS426Homework5DLL.CourseWork cw = new BCS426Homework5DLL.CourseWork(); //opens the file dialog box OpenFileDialog openFileDialog = new OpenFileDialog(); //filters the files to only show json files openFileDialog.Filter = "JSON files (*.json)|*.json"; //openFileDialog.InitialDirectory = @"C:\Users\Samantha\Documents\Fall 2019\BCS426\BCS426Homework4WPF\BCS426Homework4WPF\bin\Debug"; //sets the intital directory to the current working directory openFileDialog.InitialDirectory = @System.IO.Directory.GetCurrentDirectory(); //changes the title of the dialog box openFileDialog.Title = "Open Course Work From JSON"; if (openFileDialog.ShowDialog() == true) { //clears the text boxes textBoxAssignmentName.Clear(); textBoxCategoryName.Clear(); textBoxGrade.Clear(); //clears the database ClearDB(); listBoxSubmission.Items.Clear(); //gets the filename wanted string filename = openFileDialog.FileName; //reads from the file selected into the coursework instance cw = ReadFromFile(filename); //loops through all the submissions and adds to the database table foreach (BCS426Homework5DLL.Submission sub in cw.Submissions) { //adds the submission to the database AddSubToDB(sub); } //loads the data to the listbox LoadDataFromDB(); } }