private void btAdd_Click(object sender, RoutedEventArgs e) { try { if (string.IsNullOrEmpty(tbName.Text) || string.IsNullOrEmpty(tbAge.Text)) { MessageBox.Show("Please input Name and Age"); return; } int age = 0; int.TryParse(tbAge.Text, out age); if (age < 0 || age > 150) { MessageBox.Show("Age must be 0-150"); return; } Person newPerson = new Person { Name = tbName.Text, Age = age }; using (var ctx = new PersonDbContext()) { ctx.People.Add(newPerson); ctx.SaveChanges(); MessageBox.Show("Person Added"); ResetInput(); } } catch (SqlException ex) { MessageBox.Show("Error adding Person to database:\n" + ex.Message, "Error Information"); } }
private void RefreshList() { using (var ctx = new PersonDbContext()) { lstViewPerson.ItemsSource = ctx.People.Include("Passport").ToList <Person>(); } lstViewPerson.Items.Refresh(); }
private void btSave_Click(object sender, RoutedEventArgs e) { try { if (string.IsNullOrEmpty(tbPassportNo.Text) || string.IsNullOrEmpty(imageLocation)) { MessageBox.Show("Please input Number and choose image"); return; } Match m = Regex.Match(tbPassportNo.Text, PassportPattern); if (!m.Success) { MessageBox.Show("PassportNo must be 2 uppercase characters with 6 numbers"); return; } byte[] image = File.ReadAllBytes(imageLocation); Passport newPassport = new Passport { PassportId = currentPerson.PersonId, Number = tbPassportNo.Text, Photo = image }; using (var ctx = new PersonDbContext()) { Passport toUpdate = ctx.Passports.Include("Person").Where(pa => pa.PassportId == currentPerson.PersonId).FirstOrDefault <Passport>(); if (toUpdate != null) { toUpdate.Number = tbPassportNo.Text; if (!string.IsNullOrEmpty(imageLocation)) { toUpdate.Photo = File.ReadAllBytes(imageLocation); } ctx.SaveChanges(); MessageBox.Show("Passport Updated"); resetAndRefresh(currentPerson); } else { ctx.Passports.Add(newPassport); ctx.SaveChanges(); MessageBox.Show("Passport Added"); resetAndRefresh(currentPerson); } } } catch (Exception ex) when(ex is IOException || ex is FileNotFoundException || ex is SqlException) { MessageBox.Show("Error adding Passport to database:\n" + ex.Message, "Error Information"); } }
private void loadPassport(Person person) { using (var ctx = new PersonDbContext()) { Passport currentPassport = ctx.Passports.Include("Person").Where(pa => pa.PassportId == currentPerson.PersonId).FirstOrDefault <Passport>(); if (currentPassport != null) { btSave.Content = "Update"; tbPassportNo.Text = currentPassport.Number; tbImage.Text = string.Empty; image.Source = (ImageSource)((new ImageSourceConverter()).ConvertFrom(currentPassport.Photo)); } else { resetAndRefresh(person); } } }