AddEditPage.xaml.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. using Microsoft.Win32;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Data;
  10. using System.Windows.Documents;
  11. using System.Windows.Input;
  12. using System.Windows.Media;
  13. using System.Windows.Media.Imaging;
  14. using System.Windows.Navigation;
  15. using System.Windows.Shapes;
  16. using System.IO;
  17. namespace AutoservisDrive.Pages
  18. {
  19. /// <summary>
  20. /// Логика взаимодействия для AddEditPage.xaml
  21. /// </summary>
  22. public partial class AddEditPage : Page
  23. {
  24. private Entities.Service _currentService = null;
  25. private byte[] _mainImageData;
  26. public AddEditPage()
  27. {
  28. InitializeComponent();
  29. }
  30. public AddEditPage(Entities.Service service)
  31. {
  32. InitializeComponent();
  33. _currentService = service;
  34. Title = "Редактировать услугу";
  35. TBoxTitle.Text = _currentService.Title;
  36. TBoxCost.Text = _currentService.Cost.ToString("N2");
  37. TBoxDuration.Text = (_currentService.DurationInSeconds / 60).ToString();
  38. TBoxDescription.Text = _currentService.Description;
  39. if (_currentService.Discount>0)
  40. TBoxDiscount.Text = (_currentService.Discount.Value*100).ToString();
  41. if (_currentService.MainImage != null)
  42. ImageService.Source = (ImageSource) new ImageSourceConverter().ConvertFrom(_currentService.MainImage);
  43. }
  44. private void BtnSelectImage_Click(object sender, RoutedEventArgs e)
  45. {
  46. OpenFileDialog ofd = new OpenFileDialog();
  47. ofd.Filter = "Image |*.png; *.jpg; *.jpeg";
  48. if (ofd.ShowDialog() == true)
  49. {
  50. _mainImageData = File.ReadAllBytes(ofd.FileName);
  51. ImageService.Source = (ImageSource) new ImageSourceConverter().ConvertFrom(_mainImageData);
  52. }
  53. }
  54. private void BtnSave_Click(object sender, RoutedEventArgs e)
  55. {
  56. var errorMessage = CheckErrors();
  57. if (errorMessage.Length > 0)
  58. {
  59. MessageBox.Show(errorMessage, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
  60. }
  61. else
  62. {
  63. if (_currentService != null)
  64. {
  65. var service = new Entities.Service
  66. {
  67. Title = TBoxTitle.Text,
  68. Cost = decimal.Parse(TBoxCost.Text),
  69. DurationInSeconds = int.Parse(TBoxDuration.Text) * 60,
  70. Description = TBoxDescription.Text,
  71. Discount = string.IsNullOrWhiteSpace(TBoxDiscount.Text) ? 0 : double.Parse(TBoxDiscount.Text) / 100,
  72. MainImage = _mainImageData
  73. };
  74. App.Context.Services.Add(service);
  75. App.Context.SaveChanges();
  76. }
  77. else
  78. {
  79. _currentService.Title = TBoxTitle.Text;
  80. _currentService.Cost = decimal.Parse(TBoxCost.Text);
  81. _currentService.DurationInSeconds = int.Parse(TBoxDuration.Text);
  82. _currentService.Discount = string.IsNullOrWhiteSpace(TBoxDiscount.Text) ? 0 : double.Parse(TBoxDiscount.Text) / 100;
  83. if (_mainImageData != null)
  84. {
  85. _currentService.MainImage = _mainImageData;
  86. }
  87. App.Context.SaveChanges();
  88. }
  89. NavigationService.GoBack();
  90. }
  91. }
  92. private string CheckErrors()
  93. {
  94. var errorBuilder = new StringBuilder();
  95. //Проверка на заполнение наименования услуги
  96. if (string.IsNullOrWhiteSpace(TBoxTitle.Text))
  97. errorBuilder.AppendLine("Названиеуслуги обязательно для заполнения");
  98. //Проверка новой услуги с уже существующими в БД
  99. var serviceFromDB = App.Context.Services.ToList().FirstOrDefault(P => P.Title.ToLower() == TBoxTitle.Text.ToLower());
  100. if (serviceFromDB != null && serviceFromDB != _currentService)
  101. {
  102. errorBuilder.AppendLine("Такая услуга уже есть в базе данных;");
  103. }
  104. decimal cost = 0;
  105. //Проверка неотрицательности цены за услугу
  106. if (decimal.TryParse(TBoxCost.Text, out cost) == false || cost <= 0)
  107. {
  108. errorBuilder.AppendLine("Стоимость услуги должна быть положительным числом;");
  109. }
  110. int durationInMinutes = 0;
  111. //Проверка неотрицательности длительности услуги
  112. if (int.TryParse(TBoxDuration.Text, out durationInMinutes) == false || durationInMinutes > 240 || durationInMinutes <= 0)
  113. {
  114. errorBuilder.AppendLine("Длительность оказания услуги должна быть положительным " + "числом (не больше, чем 4 часа);");
  115. }
  116. //Проверка заполения скидки
  117. if (!string.IsNullOrEmpty(TBoxDiscount.Text))
  118. {
  119. int discount = 0;
  120. //Проверка на принадлежность к диапазону от 0 до 100
  121. if (int.TryParse(TBoxDiscount.Text, out discount) == false || discount < 0 || discount > 100)
  122. {
  123. errorBuilder.AppendLine("Размер скидки - целое число в диапазоне от 0 до 100%;");
  124. }
  125. }
  126. //Просто вывод ошибок, которые нужно исправить
  127. if (errorBuilder.Length > 0)
  128. {
  129. errorBuilder.Insert(0, "Устраните следующие ошибки:\n");
  130. }
  131. return errorBuilder.ToString();
  132. }
  133. }
  134. }