-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBooksWindow.xaml.cs
More file actions
605 lines (531 loc) · 20.6 KB
/
BooksWindow.xaml.cs
File metadata and controls
605 lines (531 loc) · 20.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using DatabaseExampleWPF.Database;
using DatabaseExampleWPF.Models;
namespace DatabaseExampleWPF
{
/// <summary>
/// Interaction logic for BooksWindow.xaml
///
/// This window demonstrates:
/// - Displaying data in a DataGrid
/// - INSERT operations (adding new books)
/// - UPDATE operations (editing existing books)
/// - DELETE operations (removing books)
/// - Managing many-to-many relationships (Books-Authors via BookAuthors table)
/// - Form validation
/// - Data binding between UI controls and objects
/// </summary>
public partial class BooksWindow : Window
{
#region Fields
/// <summary>
/// Stores the currently selected book for editing
/// null if we're adding a new book
/// This is a common pattern - reusing the same form for add and edit
/// </summary>
private Book selectedBook = null;
#endregion
#region Constructor and Initialization
/// <summary>
/// Constructor - initializes the window
/// </summary>
public BooksWindow()
{
InitializeComponent();
// Load data when window opens
LoadBooks();
LoadAuthors();
// Hide author management until a book is selected
UpdateAuthorManagementVisibility(false);
}
#endregion
#region Data Loading Methods
/// <summary>
/// Loads all books from database and displays them in the DataGrid
/// This demonstrates reading data and binding it to UI controls
/// </summary>
private void LoadBooks()
{
try
{
// Get all books from database using DatabaseHelper
List<Book> books = DatabaseHelper.GetAllBooks();
// Set the DataGrid's ItemsSource to the list of books
// This is DATA BINDING - connecting data to UI
// The DataGrid will automatically display all books
dgBooks.ItemsSource = books;
// If there are no books, show a message
if (books.Count == 0)
{
MessageBox.Show(
"No books found in the database.\n\n" +
"Add your first book using the form on the right!",
"Information",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(
$"Error loading books:\n\n{ex.Message}",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
/// <summary>
/// Loads all authors into the ComboBox for adding to books
/// </summary>
private void LoadAuthors()
{
try
{
List<Author> authors = DatabaseHelper.GetAllAuthors();
// Set ItemsSource for the ComboBox
cboAvailableAuthors.ItemsSource = authors;
}
catch (Exception ex)
{
MessageBox.Show(
$"Error loading authors:\n\n{ex.Message}",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
/// <summary>
/// Loads authors assigned to the currently selected book
/// Demonstrates querying the many-to-many relationship
/// </summary>
private void LoadAssignedAuthors()
{
try
{
if (selectedBook == null || selectedBook.BookID <= 0)
{
lstAssignedAuthors.ItemsSource = null;
return;
}
// Get authors for this book from the BookAuthors junction table
List<Author> authors = DatabaseHelper.GetAuthorsForBook(selectedBook.BookID);
// Display in the ListBox
lstAssignedAuthors.ItemsSource = authors;
}
catch (Exception ex)
{
MessageBox.Show(
$"Error loading assigned authors:\n\n{ex.Message}",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
#endregion
#region Form Management Methods
/// <summary>
/// Clears all input fields in the form
/// Used when adding a new book or after saving
/// </summary>
private void ClearForm()
{
txtTitle.Text = string.Empty;
txtISBN.Text = string.Empty;
txtYear.Text = string.Empty;
selectedBook = null;
// Update form title to show we're adding a new book
txtFormTitle.Text = "Add New Book";
// Clear selection in DataGrid
dgBooks.SelectedItem = null;
// Hide author management (no book selected)
UpdateAuthorManagementVisibility(false);
}
/// <summary>
/// Populates the form with data from a selected book for editing
/// This demonstrates the EDIT part of CRUD
/// </summary>
/// <param name="book">The book to edit</param>
private void PopulateForm(Book book)
{
if (book == null) return;
// Store the selected book
selectedBook = book;
// Populate the form fields
txtTitle.Text = book.Title;
txtISBN.Text = book.ISBN;
txtYear.Text = book.YearPublished.ToString();
// Update form title to show we're editing
txtFormTitle.Text = $"Edit Book (ID: {book.BookID})";
// Show author management for this book
UpdateAuthorManagementVisibility(true);
LoadAssignedAuthors();
}
/// <summary>
/// Shows or hides the author management section
/// </summary>
/// <param name="show">True to show, false to hide</param>
private void UpdateAuthorManagementVisibility(bool show)
{
// Show/hide the controls
lstAssignedAuthors.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
cboAvailableAuthors.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
btnAddAuthor.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
btnRemoveAuthor.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
// Show/hide the "no book selected" message
txtNoBookSelected.Visibility = show ? Visibility.Collapsed : Visibility.Visible;
}
/// <summary>
/// Validates the form input before saving
/// Returns a Book object if valid, null if invalid
/// This demonstrates INPUT VALIDATION
/// </summary>
/// <returns>Valid Book object or null</returns>
private Book ValidateAndCreateBook()
{
// Create a new book object (or use existing for updates)
Book book = selectedBook ?? new Book();
// Validate Title
if (string.IsNullOrWhiteSpace(txtTitle.Text))
{
MessageBox.Show(
"Please enter a book title.",
"Validation Error",
MessageBoxButton.OK,
MessageBoxImage.Warning);
txtTitle.Focus(); // Put cursor in the title field
return null;
}
book.Title = txtTitle.Text.Trim();
// ISBN is optional, so just set it
book.ISBN = txtISBN.Text.Trim();
// Validate Year
if (string.IsNullOrWhiteSpace(txtYear.Text))
{
MessageBox.Show(
"Please enter the year published.",
"Validation Error",
MessageBoxButton.OK,
MessageBoxImage.Warning);
txtYear.Focus();
return null;
}
// Try to parse the year as an integer
if (!int.TryParse(txtYear.Text, out int year))
{
MessageBox.Show(
"Year must be a valid number.",
"Validation Error",
MessageBoxButton.OK,
MessageBoxImage.Warning);
txtYear.Focus();
return null;
}
book.YearPublished = year;
// Use the Book class's validation method
if (!book.IsValid())
{
MessageBox.Show(
$"Validation failed:\n\n{book.GetValidationErrors()}",
"Validation Error",
MessageBoxButton.OK,
MessageBoxImage.Warning);
return null;
}
return book;
}
#endregion
#region Button Event Handlers
/// <summary>
/// Saves a book (either INSERT for new or UPDATE for existing)
/// Demonstrates both CREATE and UPDATE operations
/// </summary>
private void BtnSave_Click(object sender, RoutedEventArgs e)
{
try
{
// Validate the form and get a Book object
Book book = ValidateAndCreateBook();
if (book == null) return; // Validation failed
bool success;
string action;
if (book.BookID == 0)
{
// INSERT - adding a new book
action = "added";
int newId = DatabaseHelper.InsertBook(book);
success = newId > 0;
if (success)
{
book.BookID = newId; // Store the new ID
}
}
else
{
// UPDATE - editing existing book
action = "updated";
success = DatabaseHelper.UpdateBook(book);
}
if (success)
{
MessageBox.Show(
$"Book '{book.Title}' {action} successfully!",
"Success",
MessageBoxButton.OK,
MessageBoxImage.Information);
// Refresh the list to show changes
LoadBooks();
// Clear the form for next entry
ClearForm();
}
else
{
MessageBox.Show(
$"Failed to {action.TrimEnd('d')} book.\n\n" +
"Check the debug output for details.",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(
$"Error saving book:\n\n{ex.Message}",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
/// <summary>
/// Clears the form
/// </summary>
private void BtnClear_Click(object sender, RoutedEventArgs e)
{
ClearForm();
}
/// <summary>
/// Refreshes the books list from the database
/// </summary>
private void BtnRefresh_Click(object sender, RoutedEventArgs e)
{
LoadBooks();
LoadAuthors(); // Also refresh authors in case they were added in another window
}
/// <summary>
/// Deletes the selected book
/// Demonstrates DELETE operation with user confirmation
/// </summary>
private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
try
{
// Check if a book is selected in the DataGrid
if (dgBooks.SelectedItem == null)
{
MessageBox.Show(
"Please select a book to delete.",
"No Selection",
MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
Book bookToDelete = (Book)dgBooks.SelectedItem;
// Ask for confirmation before deleting
// MessageBoxResult stores which button the user clicked
MessageBoxResult result = MessageBox.Show(
$"Are you sure you want to delete the book:\n\n" +
$"'{bookToDelete.Title}' ({bookToDelete.YearPublished})?\n\n" +
"This action cannot be undone!",
"Confirm Delete",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
// Only delete if user clicked Yes
if (result == MessageBoxResult.Yes)
{
bool success = DatabaseHelper.DeleteBook(bookToDelete.BookID);
if (success)
{
MessageBox.Show(
$"Book '{bookToDelete.Title}' deleted successfully!",
"Success",
MessageBoxButton.OK,
MessageBoxImage.Information);
// Refresh the list
LoadBooks();
// Clear the form if we were editing this book
if (selectedBook?.BookID == bookToDelete.BookID)
{
ClearForm();
}
}
else
{
MessageBox.Show(
"Failed to delete book.\n\n" +
"The book may have active loans or other dependencies.",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
}
catch (Exception ex)
{
MessageBox.Show(
$"Error deleting book:\n\n{ex.Message}",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
/// <summary>
/// Adds an author to the selected book
/// Demonstrates INSERT into the BookAuthors junction table (many-to-many)
/// </summary>
private void BtnAddAuthor_Click(object sender, RoutedEventArgs e)
{
try
{
// Validate that a book is selected
if (selectedBook == null || selectedBook.BookID <= 0)
{
MessageBox.Show(
"Please select or save a book first.",
"No Book Selected",
MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
// Validate that an author is selected in the ComboBox
if (cboAvailableAuthors.SelectedItem == null)
{
MessageBox.Show(
"Please select an author to add.",
"No Author Selected",
MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
Author authorToAdd = (Author)cboAvailableAuthors.SelectedItem;
// Add the relationship to the BookAuthors table
bool success = DatabaseHelper.AddBookAuthor(selectedBook.BookID, authorToAdd.AuthorID);
if (success)
{
MessageBox.Show(
$"Author '{authorToAdd.FullName}' added to book '{selectedBook.Title}'!",
"Success",
MessageBoxButton.OK,
MessageBoxImage.Information);
// Refresh the assigned authors list
LoadAssignedAuthors();
}
else
{
MessageBox.Show(
"Failed to add author to book.\n\n" +
"This author may already be assigned to this book.",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
catch (Exception ex)
{
MessageBox.Show(
$"Error adding author to book:\n\n{ex.Message}",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
/// <summary>
/// Removes an author from the selected book
/// Demonstrates DELETE from the BookAuthors junction table (many-to-many)
/// </summary>
private void BtnRemoveAuthor_Click(object sender, RoutedEventArgs e)
{
try
{
// Validate that a book is selected
if (selectedBook == null || selectedBook.BookID <= 0)
{
MessageBox.Show(
"Please select a book first.",
"No Book Selected",
MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
// Validate that an author is selected in the ListBox
if (lstAssignedAuthors.SelectedItem == null)
{
MessageBox.Show(
"Please select an author to remove from the list.",
"No Author Selected",
MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
Author authorToRemove = (Author)lstAssignedAuthors.SelectedItem;
// Ask for confirmation
MessageBoxResult result = MessageBox.Show(
$"Remove '{authorToRemove.FullName}' from '{selectedBook.Title}'?",
"Confirm Remove",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
// Remove the relationship from BookAuthors table
bool success = DatabaseHelper.RemoveBookAuthor(selectedBook.BookID, authorToRemove.AuthorID);
if (success)
{
MessageBox.Show(
$"Author '{authorToRemove.FullName}' removed from book '{selectedBook.Title}'!",
"Success",
MessageBoxButton.OK,
MessageBoxImage.Information);
// Refresh the assigned authors list
LoadAssignedAuthors();
}
else
{
MessageBox.Show(
"Failed to remove author from book.",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
}
catch (Exception ex)
{
MessageBox.Show(
$"Error removing author from book:\n\n{ex.Message}",
"Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
#endregion
#region DataGrid Event Handlers
/// <summary>
/// Handles when a user selects a different row in the DataGrid
/// Populates the form with the selected book's data for editing
/// </summary>
private void DgBooks_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Check if a row is selected
if (dgBooks.SelectedItem != null)
{
// Get the selected book
Book book = (Book)dgBooks.SelectedItem;
// Populate the form for editing
PopulateForm(book);
}
}
#endregion
}
}