diff --git a/COP/UserCheckedListBox.cs b/COP/UserCheckedListBox.cs index cf46134..1613146 100644 --- a/COP/UserCheckedListBox.cs +++ b/COP/UserCheckedListBox.cs @@ -1,4 +1,6 @@ -namespace COP +using DocumentFormat.OpenXml.Spreadsheet; + +namespace COP { public partial class UserCheckedListBox : UserControl { @@ -28,27 +30,16 @@ { get { - string checkedItems = ""; - for (int i = 0; i < checkedListBox.Items.Count; i++) - { - if (checkedListBox.GetItemChecked(i)) - { - checkedItems += checkedListBox.Items[i].ToString() + " "; - } - } - if (checkedListBox.CheckedItems != null) - return checkedItems; - else - return ""; + return string.Join(";", checkedListBox.CheckedItems.Cast()); } set { - for (int i = 0; i < checkedListBox.Items.Count; i++) + if (!string.IsNullOrEmpty(value)) { - if (checkedListBox.Items[i].ToString() == value) + string[] selectedValues = value.Split(';'); + for (int i = 0; i < checkedListBox.Items.Count; i++) { - checkedListBox.SetItemChecked(i, true); - break; + checkedListBox.SetItemChecked(i, selectedValues.Contains(checkedListBox.Items[i].ToString()) || checkedListBox.GetItemChecked(i)); } } } diff --git a/COP/UserCheckedListBox.resx b/COP/UserCheckedListBox.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/COP/UserCheckedListBox.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/TestComponents/FormTestComponents.Designer.cs b/TestComponents/FormTestComponents.Designer.cs index ffe9866..1142904 100644 --- a/TestComponents/FormTestComponents.Designer.cs +++ b/TestComponents/FormTestComponents.Designer.cs @@ -49,7 +49,6 @@ // this.userCheckedListBox.Location = new System.Drawing.Point(0, -1); this.userCheckedListBox.Name = "userCheckedListBox"; - this.userCheckedListBox.SelectedValue = ""; this.userCheckedListBox.Size = new System.Drawing.Size(150, 150); this.userCheckedListBox.TabIndex = 0; this.userCheckedListBox.SelectedValueChanged += new System.EventHandler(this.UserCheckedListBox_SelectedValueChanged); diff --git a/UniversityBusinessLogic/BusinessLogics/DirectionLogic.cs b/UniversityBusinessLogic/BusinessLogics/DirectionLogic.cs index 771dcd0..b11577c 100644 --- a/UniversityBusinessLogic/BusinessLogics/DirectionLogic.cs +++ b/UniversityBusinessLogic/BusinessLogics/DirectionLogic.cs @@ -9,11 +9,9 @@ namespace UniversityBusinessLogic.BusinessLogics { public class DirectionLogic : IDirectionLogic { - private readonly ILogger _logger; private readonly IDirectionStorage _directionStorage; - public DirectionLogic(ILogger logger, IDirectionStorage directionStorage) + public DirectionLogic(IDirectionStorage directionStorage) { - _logger = logger; _directionStorage = directionStorage; } @@ -28,7 +26,7 @@ namespace UniversityBusinessLogic.BusinessLogics { throw new Exception("Такое направление уже существует"); } - if (model.Id != null) + if (model.Id.HasValue) { _directionStorage.Update(model); } @@ -36,73 +34,29 @@ namespace UniversityBusinessLogic.BusinessLogics { _directionStorage.Insert(model); } - } - - public bool Delete(DirectionBindingModel model) - { - CheckModel(model, false); - _logger.LogInformation("Delete. Id:{Id}", model.Id); - if (_directionStorage.Delete(model) == null) - { - _logger.LogWarning("Delete operation failed"); - return false; - } - return true; } - public DirectionViewModel? ReadElement(DirectionBindingModel model) + public void Delete(DirectionBindingModel model) { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - _logger.LogInformation("ReadElement. Name:{Name}. Id:{ Id}", model.Name, model.Id); - var element = _directionStorage.GetElement(model); + var element = _directionStorage.GetElement(new DirectionBindingModel { Id = model.Id }); if (element == null) { - _logger.LogWarning("ReadElement element not found"); - return null; + throw new Exception("Направление не найдено"); } - _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); - return element; + _directionStorage.Delete(model); } - public List? ReadList(DirectionBindingModel? model) - { - _logger.LogInformation("ReadList. Name:{Name}. Id:{ Id}", model?.Name, model?.Id); - var list = model == null ? _directionStorage.GetFullList() : _directionStorage.GetFilteredList(model); - if (list == null) - { - _logger.LogWarning("ReadList return null list"); - return null; - } - _logger.LogInformation("ReadList. Count:{Count}", list.Count); - return list; - } - - private void CheckModel(DirectionBindingModel model, bool withParams = true) + public List Read(DirectionBindingModel model) { if (model == null) { - throw new ArgumentNullException(nameof(model)); + return _directionStorage.GetFullList(); } - if (!withParams) + if (!string.IsNullOrEmpty(model.Name)) { - return; - } - if (string.IsNullOrEmpty(model.Name)) - { - throw new ArgumentNullException("Нет названия направления", nameof(model.Name)); - } - _logger.LogInformation("Direction. Name:{Name}. Id: {Id} ", model.Name, model.Id); - var element = _directionStorage.GetElement(new DirectionBindingModel - { - Name = model.Name - }); - if (element != null && element.Id != model.Id) - { - throw new InvalidOperationException("Направление с таким названием уже есть"); + return new List { _directionStorage.GetElement(model) }; } + return _directionStorage.GetFilteredList(model); } } } diff --git a/UniversityBusinessLogic/BusinessLogics/StudentLogic.cs b/UniversityBusinessLogic/BusinessLogics/StudentLogic.cs index 9eadef1..bcffca3 100644 --- a/UniversityBusinessLogic/BusinessLogics/StudentLogic.cs +++ b/UniversityBusinessLogic/BusinessLogics/StudentLogic.cs @@ -9,113 +9,56 @@ namespace UniversityBusinessLogic.BusinessLogics { public class StudentLogic : IStudentLogic { - private readonly ILogger _logger; private readonly IStudentStorage _studentStorage; - public StudentLogic(ILogger logger, IStudentStorage studentStorage) + public StudentLogic(IStudentStorage studentStorage) { - _logger = logger; _studentStorage = studentStorage; } - public bool Create(StudentBindingModel model) + public void CreateOrUpdate(StudentBindingModel model) { - CheckModel(model); - model.DirectionName = model.DirectionName.Trim(); - if (_studentStorage.Insert(model) == null) - { - _logger.LogWarning("Insert operation failed"); - return false; - } - return true; - } - - public bool Delete(StudentBindingModel model) - { - CheckModel(model, false); - _logger.LogInformation("Delete. Id:{Id}", model.Id); - if (_studentStorage.Delete(model) == null) - { - _logger.LogWarning("Delete operation failed"); - return false; - } - return true; - } - - public StudentViewModel? ReadElement(StudentSearchModel model) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - _logger.LogInformation("ReadElement. FIO:{FIO}. Id:{ Id}", model.FIO, model.Id); - var element = _studentStorage.GetElement(model); - if (element == null) - { - _logger.LogWarning("ReadElement element not found"); - return null; - } - _logger.LogInformation("ReadElement find. Id:{Id}", element.Id); - return element; - } - - public List? ReadList(StudentSearchModel? model) - { - _logger.LogInformation("ReadList. FIO:{FIO}. Id:{ Id}", model?.FIO, model?.Id); - var list = model == null ? _studentStorage.GetFullList() : _studentStorage.GetFilteredList(model); - if (list == null) - { - _logger.LogWarning("ReadList return null list"); - return null; - } - _logger.LogInformation("ReadList. Count:{Count}", list.Count); - return list; - } - - public bool Update(StudentBindingModel model) - { - CheckModel(model); - if (_studentStorage.Update(model) == null) - { - _logger.LogWarning("Update operation failed"); - return false; - } - return true; - } - - private void CheckModel(StudentBindingModel model, bool withParams = true) - { - if (model == null) - { - throw new ArgumentNullException(nameof(model)); - } - if (!withParams) - { - return; - } - if (string.IsNullOrEmpty(model.FIO)) - { - throw new ArgumentNullException("Нет ФИО студента", nameof(model.FIO)); - } - if (string.IsNullOrEmpty(model.PhotoFilePath)) - { - throw new ArgumentNullException("Нет пути к фото", nameof(model.PhotoFilePath)); - } - if (string.IsNullOrEmpty(model.Email)) - { - throw new ArgumentNullException("Нет электронной почты", nameof(model.Email)); - } - if (string.IsNullOrEmpty(model.DirectionName)) - { - throw new ArgumentNullException("Нет направления", nameof(model.DirectionName)); - } - _logger.LogInformation("Student. FIO:{FIO}. PhotoFilePath:{PhotoFilePath}. Email:{Email}. DirectionName:{DirectionName}. Id: {Id} ", model.FIO, model.PhotoFilePath, model.Email, model.DirectionName, model.Id); - var element = _studentStorage.GetElement(new StudentSearchModel - { - FIO = model.FIO - }); + var element = _studentStorage.GetElement( + new StudentBindingModel + { + FIO = model.FIO, + Email = model.Email, + PhotoFilePath = model.PhotoFilePath, + DirectionName = model.DirectionName, + }); if (element != null && element.Id != model.Id) { - throw new InvalidOperationException("Студент с таким ФИО уже есть"); + throw new Exception("Студент с таким именем уже существует."); } + if (model.Id.HasValue) + { + _studentStorage.Update(model); + } + else + { + _studentStorage.Insert(model); + } + } + + public void Delete(StudentBindingModel model) + { + var element = _studentStorage.GetElement(new StudentBindingModel { Id = model.Id }); + if (element == null) + { + throw new Exception("Студент не найден"); + } + _studentStorage.Delete(model); + } + + public List Read(StudentBindingModel model) + { + if (model == null) + { + return _studentStorage.GetFullList(); + } + if (model.Id.HasValue) + { + return new List { _studentStorage.GetElement(model) }; + } + return _studentStorage.GetFilteredList(model); } } } diff --git a/UniversityContracts/BindingModels/DirectionBindingModel.cs b/UniversityContracts/BindingModels/DirectionBindingModel.cs index 0abec63..e3806e6 100644 --- a/UniversityContracts/BindingModels/DirectionBindingModel.cs +++ b/UniversityContracts/BindingModels/DirectionBindingModel.cs @@ -2,9 +2,9 @@ namespace UniversityContracts.BindingModels { - public class DirectionBindingModel : IDirectionModel + public class DirectionBindingModel { - public int Id { get; set; } + public int? Id { get; set; } public string Name { get; set; } = string.Empty; } } diff --git a/UniversityContracts/BindingModels/StudentBindingModel.cs b/UniversityContracts/BindingModels/StudentBindingModel.cs index c5426bf..e8299b7 100644 --- a/UniversityContracts/BindingModels/StudentBindingModel.cs +++ b/UniversityContracts/BindingModels/StudentBindingModel.cs @@ -2,12 +2,12 @@ namespace UniversityContracts.BindingModels { - public class StudentBindingModel : IStudentModel + public class StudentBindingModel { - public int Id { get; set; } - public string FIO { get; set; } = string.Empty; - public string PhotoFilePath { get; set; } = string.Empty; - public string Email { get; set; } = string.Empty; - public string DirectionName { get; set; } = string.Empty; + public int? Id { get; set; } + public string FIO { get; set; } + public string PhotoFilePath { get; set; } + public string Email { get; set; } + public string DirectionName { get; set; } } } diff --git a/UniversityContracts/BusinessLogicsContracts/IDirectionLogic.cs b/UniversityContracts/BusinessLogicsContracts/IDirectionLogic.cs index 89161d3..393114a 100644 --- a/UniversityContracts/BusinessLogicsContracts/IDirectionLogic.cs +++ b/UniversityContracts/BusinessLogicsContracts/IDirectionLogic.cs @@ -6,9 +6,8 @@ namespace UniversityContracts.BusinessLogicsContracts { public interface IDirectionLogic { - List? ReadList(DirectionBindingModel? model); - DirectionViewModel? ReadElement(DirectionBindingModel model); - bool Delete(DirectionBindingModel model); + List Read(DirectionBindingModel model); void CreateOrUpdate(DirectionBindingModel model); + void Delete(DirectionBindingModel model); } } diff --git a/UniversityContracts/BusinessLogicsContracts/IStudentLogic.cs b/UniversityContracts/BusinessLogicsContracts/IStudentLogic.cs index 12b37d7..41a205e 100644 --- a/UniversityContracts/BusinessLogicsContracts/IStudentLogic.cs +++ b/UniversityContracts/BusinessLogicsContracts/IStudentLogic.cs @@ -6,10 +6,8 @@ namespace UniversityContracts.BusinessLogicsContracts { public interface IStudentLogic { - List? ReadList(StudentSearchModel? model); - StudentViewModel? ReadElement(StudentSearchModel model); - bool Create(StudentBindingModel model); - bool Update(StudentBindingModel model); - bool Delete(StudentBindingModel model); + List Read(StudentBindingModel model); + void CreateOrUpdate(StudentBindingModel model); + void Delete(StudentBindingModel model); } } diff --git a/UniversityContracts/SearchModels/StudentSearchModel.cs b/UniversityContracts/SearchModels/StudentSearchModel.cs index 51dbcc5..b681c88 100644 --- a/UniversityContracts/SearchModels/StudentSearchModel.cs +++ b/UniversityContracts/SearchModels/StudentSearchModel.cs @@ -2,7 +2,10 @@ { public class StudentSearchModel { - public int? Id { get; set; } - public string? FIO { get; set; } + public int Id { get; set; } + public string FIO { get; set; } + public string Email { get; set; } + public string PhotoFilePath { get; set; } + public string DirectionName { get; set; } } } diff --git a/UniversityContracts/StoragesContracts/IDirectionStorage.cs b/UniversityContracts/StoragesContracts/IDirectionStorage.cs index 73da254..9661d2f 100644 --- a/UniversityContracts/StoragesContracts/IDirectionStorage.cs +++ b/UniversityContracts/StoragesContracts/IDirectionStorage.cs @@ -1,5 +1,4 @@ using UniversityContracts.BindingModels; -using UniversityContracts.SearchModels; using UniversityContracts.ViewModels; namespace UniversityContracts.StoragesContracts @@ -8,9 +7,9 @@ namespace UniversityContracts.StoragesContracts { List GetFullList(); List GetFilteredList(DirectionBindingModel model); - DirectionViewModel? GetElement(DirectionBindingModel model); - DirectionViewModel? Insert(DirectionBindingModel model); - DirectionViewModel? Update(DirectionBindingModel model); - DirectionViewModel? Delete(DirectionBindingModel model); + DirectionViewModel GetElement(DirectionBindingModel model); + void Insert(DirectionBindingModel model); + void Update(DirectionBindingModel model); + void Delete(DirectionBindingModel model); } } diff --git a/UniversityContracts/StoragesContracts/IStudentStorage.cs b/UniversityContracts/StoragesContracts/IStudentStorage.cs index ea3bd7e..c78a7de 100644 --- a/UniversityContracts/StoragesContracts/IStudentStorage.cs +++ b/UniversityContracts/StoragesContracts/IStudentStorage.cs @@ -7,10 +7,10 @@ namespace UniversityContracts.StoragesContracts public interface IStudentStorage { List GetFullList(); - List GetFilteredList(StudentSearchModel model); - StudentViewModel? GetElement(StudentSearchModel model); - StudentViewModel? Insert(StudentBindingModel model); - StudentViewModel? Update(StudentBindingModel model); - StudentViewModel? Delete(StudentBindingModel model); + List GetFilteredList(StudentBindingModel model); + StudentViewModel? GetElement(StudentBindingModel model); + void Insert(StudentBindingModel model); + void Update(StudentBindingModel model); + void Delete(StudentBindingModel model); } } diff --git a/UniversityContracts/ViewModels/StudentViewModel.cs b/UniversityContracts/ViewModels/StudentViewModel.cs index 978b96c..5c93780 100644 --- a/UniversityContracts/ViewModels/StudentViewModel.cs +++ b/UniversityContracts/ViewModels/StudentViewModel.cs @@ -5,14 +5,14 @@ namespace UniversityContracts.ViewModels { public class StudentViewModel : IStudentModel { - public int Id { get; set; } + public int? Id { get; set; } [DisplayName("ФИО студента")] - public string FIO { get; set; } = string.Empty; + public string FIO { get; set; } [DisplayName("Путь к фото")] - public string PhotoFilePath { get; set; } = string.Empty; + public string PhotoFilePath { get; set; } [DisplayName("Электронная почта")] - public string Email { get; set; } = string.Empty; + public string Email { get; set; } [DisplayName("Направление")] - public string DirectionName { get; set; } = string.Empty; + public string DirectionName { get; set; } } } diff --git a/UniversityDataModels/Models/IStudentModel.cs b/UniversityDataModels/Models/IStudentModel.cs index b990052..dfd4c9c 100644 --- a/UniversityDataModels/Models/IStudentModel.cs +++ b/UniversityDataModels/Models/IStudentModel.cs @@ -1,6 +1,6 @@ namespace UniversityDataModels.Models { - public interface IStudentModel : IId + public interface IStudentModel { string FIO { get; } string PhotoFilePath { get; } diff --git a/UniversityDatabaseImplement/Implements/DirectionStorage.cs b/UniversityDatabaseImplement/Implements/DirectionStorage.cs index 8cf1e2d..409b24e 100644 --- a/UniversityDatabaseImplement/Implements/DirectionStorage.cs +++ b/UniversityDatabaseImplement/Implements/DirectionStorage.cs @@ -1,80 +1,116 @@ using UniversityContracts.BindingModels; -using UniversityContracts.SearchModels; using UniversityContracts.StoragesContracts; using UniversityContracts.ViewModels; +using UniversityDatabaseImplement; using UniversityDatabaseImplement.Models; -namespace UniversityDatabaseImplement.Implements +namespace UniversityUniversityDatabaseImplement.Implements { public class DirectionStorage : IDirectionStorage { + public void Delete(DirectionBindingModel model) + { + var context = new UniversityDatabase(); + var direction = context.Directions.FirstOrDefault(rec => rec.Id == model.Id); + if (direction != null) + { + context.Directions.Remove(direction); + context.SaveChanges(); + } + else + { + throw new Exception("Направление не найдено"); + } + } + + public DirectionViewModel GetElement(DirectionBindingModel model) + { + if (model == null) + { + return null; + } + using var context = new UniversityDatabase(); + + var direction = context.Directions + .ToList() + .FirstOrDefault(rec => rec.Id == model.Id || rec.Name == model.Name); + return direction != null ? CreateModel(direction) : null; + } + + + public List GetFilteredList(DirectionBindingModel model) + { + if (model == null) + { + return null; + } + using var context = new UniversityDatabase(); + return context.Directions + .Where(rec => rec.Name.Contains(model.Name)) + .Select(CreateModel) + .ToList(); + } + public List GetFullList() { using var context = new UniversityDatabase(); return context.Directions - .Select(x => x.GetViewModel) - .ToList(); + .Select(CreateModel) + .ToList(); } - public List GetFilteredList(DirectionBindingModel model) + + public void Insert(DirectionBindingModel model) { - if (string.IsNullOrEmpty(model.Name)) + var context = new UniversityDatabase(); + var transaction = context.Database.BeginTransaction(); + try { - return new(); - } - using var context = new UniversityDatabase(); - return context.Directions - .Select(x => x.GetViewModel) - .ToList(); - } - public DirectionViewModel? GetElement(DirectionBindingModel model) - { - if (string.IsNullOrEmpty(model.Name) && !model.Id.HasValue) - { - return null; - } - using var context = new UniversityDatabase(); - return context.Directions - .FirstOrDefault(x => (!string.IsNullOrEmpty(model.Name) && - x.Name == model.Name) || - (model.Id.HasValue && x.Id == model.Id)) - ?.GetViewModel; - } - public DirectionViewModel? Insert(DirectionBindingModel model) - { - using var context = new UniversityDatabase(); - var newDirection = Direction.Create(model); - if (newDirection == null) - { - return null; - } - context.Directions.Add(newDirection); - context.SaveChanges(); - return newDirection.GetViewModel; - } - public DirectionViewModel? Update(DirectionBindingModel model) - { - using var context = new UniversityDatabase(); - var direction = context.Directions.FirstOrDefault(rec => rec.Id == model.Id); - if (direction == null) - { - return null; - } - direction.Update(model); - context.SaveChanges(); - return direction.GetViewModel; - } - public DirectionViewModel? Delete(DirectionBindingModel model) - { - using var context = new UniversityDatabase(); - var element = context.Directions - .FirstOrDefault(rec => rec.Id == model.Id); - if (element != null) - { - context.Directions.Remove(element); + context.Directions.Add(CreateModel(model, new Direction())); context.SaveChanges(); - return element.GetViewModel; + transaction.Commit(); } - return null; + catch + { + transaction.Rollback(); + throw; + } + } + + public void Update(DirectionBindingModel model) + { + var context = new UniversityDatabase(); + var transaction = context.Database.BeginTransaction(); + try + { + var direction = context.Directions.FirstOrDefault(rec => rec.Id == model.Id); + if (direction == null) + { + throw new Exception("Направление не найдено"); + } + CreateModel(model, direction); + context.SaveChanges(); + transaction.Commit(); + } + catch + { + transaction.Rollback(); + throw; + } + } + + private static Direction CreateModel(DirectionBindingModel model, Direction direction) + { + direction.Name = model.Name; + return direction; + } + + private static DirectionViewModel CreateModel(Direction direction) + { + return new DirectionViewModel + { + Id = direction.Id, + Name = direction.Name + }; } } } diff --git a/UniversityDatabaseImplement/Implements/StudentStorage.cs b/UniversityDatabaseImplement/Implements/StudentStorage.cs index 68fe7ca..378a0f0 100644 --- a/UniversityDatabaseImplement/Implements/StudentStorage.cs +++ b/UniversityDatabaseImplement/Implements/StudentStorage.cs @@ -1,81 +1,119 @@ -using Microsoft.EntityFrameworkCore; -using UniversityContracts.BindingModels; -using UniversityContracts.SearchModels; +using UniversityContracts.BindingModels; using UniversityContracts.StoragesContracts; using UniversityContracts.ViewModels; +using UniversityDatabaseImplement; using UniversityDatabaseImplement.Models; -namespace UniversityDatabaseImplement.Implements +namespace UniversityUniversityDatabaseImplement.Implements { public class StudentStorage : IStudentStorage { + public void Delete(StudentBindingModel model) + { + var context = new UniversityDatabase(); + var student = context.Students.FirstOrDefault(rec => rec.Id == model.Id); + if (student != null) + { + context.Students.Remove(student); + context.SaveChanges(); + } + else + { + throw new Exception("Студент не найден"); + } + } + + public StudentViewModel GetElement(StudentBindingModel model) + { + if (model == null) + { + return null; + } + using var context = new UniversityDatabase(); + var student = context.Students + .ToList() + .FirstOrDefault(rec => rec.Id == model.Id); + return student != null ? CreateModel(student) : null; + } + + public List GetFilteredList(StudentBindingModel model) + { + var context = new UniversityDatabase(); + return context.Students + .Where(student => student.FIO.Contains(model.FIO)) + .ToList() + .Select(CreateModel) + .ToList(); + } + public List GetFullList() { using var context = new UniversityDatabase(); return context.Students - .Select(x => x.GetViewModel) + .ToList() + .Select(CreateModel) .ToList(); } - public List GetFilteredList(StudentSearchModel model) + + public void Insert(StudentBindingModel model) { - if (string.IsNullOrEmpty(model.FIO)) + var context = new UniversityDatabase(); + var transaction = context.Database.BeginTransaction(); + try { - return new(); - } - using var context = new UniversityDatabase(); - return context.Students - .Select(x => x.GetViewModel) - .ToList(); - } - public StudentViewModel? GetElement(StudentSearchModel model) - { - if (!model.Id.HasValue) - { - return null; - } - using var context = new UniversityDatabase(); - return context.Students - .FirstOrDefault(x => (!string.IsNullOrEmpty(model.FIO) && - x.FIO == model.FIO) || - (model.Id.HasValue && x.Id == model.Id)) - ?.GetViewModel; - } - public StudentViewModel? Insert(StudentBindingModel model) - { - using var context = new UniversityDatabase(); - var newStudent = Student.Create(model); - if (newStudent == null) - { - return null; - } - context.Students.Add(newStudent); - context.SaveChanges(); - return newStudent.GetViewModel; - } - public StudentViewModel? Update(StudentBindingModel model) - { - using var context = new UniversityDatabase(); - var student = context.Students.FirstOrDefault(rec => rec.Id == model.Id); - if (student == null) - { - return null; - } - student.Update(model); - context.SaveChanges(); - return student.GetViewModel; - } - public StudentViewModel? Delete(StudentBindingModel model) - { - using var context = new UniversityDatabase(); - var element = context.Students - .FirstOrDefault(rec => rec.Id == model.Id); - if (element != null) - { - context.Students.Remove(element); + context.Students.Add(CreateModel(model, new Student())); context.SaveChanges(); - return element.GetViewModel; + transaction.Commit(); } - return null; + catch + { + transaction.Rollback(); + throw; + } + } + + public void Update(StudentBindingModel model) + { + var context = new UniversityDatabase(); + var transaction = context.Database.BeginTransaction(); + try + { + var student = context.Students.FirstOrDefault(rec => rec.Id == model.Id); + if (student == null) + { + throw new Exception("Студент не найден"); + } + CreateModel(model, student); + context.SaveChanges(); + transaction.Commit(); + } + catch + { + transaction.Rollback(); + throw; + } + } + + private static Student CreateModel(StudentBindingModel model, Student student) + { + student.FIO = model.FIO; + student.PhotoFilePath = model.PhotoFilePath; + student.Email = model.Email; + student.DirectionName = model.DirectionName; + + return student; + } + + private StudentViewModel CreateModel(Student student) + { + return new StudentViewModel + { + Id = student.Id, + FIO = student.FIO, + PhotoFilePath = student.PhotoFilePath, + Email = student.Email, + DirectionName = student.DirectionName, + }; } } } diff --git a/UniversityDatabaseImplement/Migrations/20231027233645_InitialCreate.Designer.cs b/UniversityDatabaseImplement/Migrations/20231108231603_InitialCreate.Designer.cs similarity index 98% rename from UniversityDatabaseImplement/Migrations/20231027233645_InitialCreate.Designer.cs rename to UniversityDatabaseImplement/Migrations/20231108231603_InitialCreate.Designer.cs index ee98d04..06a3b47 100644 --- a/UniversityDatabaseImplement/Migrations/20231027233645_InitialCreate.Designer.cs +++ b/UniversityDatabaseImplement/Migrations/20231108231603_InitialCreate.Designer.cs @@ -11,7 +11,7 @@ using UniversityDatabaseImplement; namespace UniversityDatabaseImplement.Migrations { [DbContext(typeof(UniversityDatabase))] - [Migration("20231027233645_InitialCreate")] + [Migration("20231108231603_InitialCreate")] partial class InitialCreate { /// diff --git a/UniversityDatabaseImplement/Migrations/20231027233645_InitialCreate.cs b/UniversityDatabaseImplement/Migrations/20231108231603_InitialCreate.cs similarity index 100% rename from UniversityDatabaseImplement/Migrations/20231027233645_InitialCreate.cs rename to UniversityDatabaseImplement/Migrations/20231108231603_InitialCreate.cs diff --git a/UniversityDatabaseImplement/Models/Direction.cs b/UniversityDatabaseImplement/Models/Direction.cs index 24b1263..dbfa851 100644 --- a/UniversityDatabaseImplement/Models/Direction.cs +++ b/UniversityDatabaseImplement/Models/Direction.cs @@ -1,48 +1,12 @@ using System.ComponentModel.DataAnnotations; using UniversityDataModels.Models; -using UniversityContracts.BindingModels; -using UniversityContracts.ViewModels; namespace UniversityDatabaseImplement.Models { - public class Direction : IDirectionModel + public class Direction { - public int Id { get; private set; } + public int Id { get; set; } [Required] - public string Name { get; private set; } = string.Empty; - - public static Direction? Create(DirectionBindingModel model) - { - if (model == null) - { - return null; - } - return new Direction() - { - Id = model.Id, - Name = model.Name - }; - } - public static Direction Create(DirectionViewModel model) - { - return new Direction() - { - Id = model.Id, - Name = model.Name - }; - } - public void Update(DirectionBindingModel model) - { - if (model == null) - { - return; - } - Name = model.Name; - } - public DirectionViewModel GetViewModel => new() - { - Id = Id, - Name = Name - }; + public string Name { get; set; } = string.Empty; } } diff --git a/UniversityDatabaseImplement/Models/Student.cs b/UniversityDatabaseImplement/Models/Student.cs index 773b688..668d615 100644 --- a/UniversityDatabaseImplement/Models/Student.cs +++ b/UniversityDatabaseImplement/Models/Student.cs @@ -1,66 +1,16 @@ using System.ComponentModel.DataAnnotations; -using UniversityDataModels.Models; -using UniversityContracts.BindingModels; -using UniversityContracts.ViewModels; - namespace UniversityDatabaseImplement.Models { - public class Student : IStudentModel + public class Student { - public int Id { get; private set; } + public int Id { get; set; } [Required] - public string FIO { get; private set; } = string.Empty; + public string FIO { get; set; } [Required] - public string Email { get; private set; } = string.Empty; + public string Email { get; set; } [Required] - public string PhotoFilePath { get; private set; } = string.Empty; + public string PhotoFilePath { get; set; } [Required] - public string DirectionName { get; private set; } = string.Empty; - - public static Student? Create(StudentBindingModel model) - { - if (model == null) - { - return null; - } - return new Student() - { - Id = model.Id, - FIO = model.FIO, - Email = model.Email, - PhotoFilePath = model.PhotoFilePath, - DirectionName = model.DirectionName - }; - } - public static Student Create(StudentViewModel model) - { - return new Student() - { - Id = model.Id, - FIO = model.FIO, - Email = model.Email, - PhotoFilePath = model.PhotoFilePath, - DirectionName = model.DirectionName - }; - } - public void Update(StudentBindingModel model) - { - if (model == null) - { - return; - } - FIO = model.FIO; - Email = model.Email; - PhotoFilePath = model.PhotoFilePath; - DirectionName = model.DirectionName; - } - public StudentViewModel GetViewModel => new() - { - Id = Id, - FIO = FIO, - Email = Email, - PhotoFilePath = PhotoFilePath, - DirectionName = DirectionName - }; + public string DirectionName { get; set; } } } diff --git a/UniversityView/FormHandbooks.cs b/UniversityView/FormHandbooks.cs index 834d5cf..cfc52da 100644 --- a/UniversityView/FormHandbooks.cs +++ b/UniversityView/FormHandbooks.cs @@ -26,7 +26,7 @@ namespace UniversityView { try { - var list = _logic.ReadList(null); + var list = _logic.Read(null); _list.Clear(); foreach (var item in list) { diff --git a/UniversityView/FormMain.Designer.cs b/UniversityView/FormMain.Designer.cs index 9b58c4f..94cc690 100644 --- a/UniversityView/FormMain.Designer.cs +++ b/UniversityView/FormMain.Designer.cs @@ -40,6 +40,7 @@ this.создатьДокументСДиаграммойToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.excelComponent = new COP.ExcelComponent(this.components); this.gistogramPdfComponent = new WinFormsControlLibrary.GistogramPdfComponent3(this.components); + this.componentWord = new COPWinForms.ComponentWord2(this.components); this.contextMenuStrip.SuspendLayout(); this.SuspendLayout(); // @@ -65,7 +66,7 @@ this.создатьДокументСТаблицейToolStripMenuItem, this.создатьДокументСДиаграммойToolStripMenuItem}); this.contextMenuStrip.Name = "contextMenuStrip"; - this.contextMenuStrip.Size = new System.Drawing.Size(296, 180); + this.contextMenuStrip.Size = new System.Drawing.Size(296, 158); // // создатьToolStripMenuItem // @@ -150,5 +151,6 @@ private ToolStripMenuItem справочникиToolStripMenuItem; private COP.ExcelComponent excelComponent; private WinFormsControlLibrary.GistogramPdfComponent3 gistogramPdfComponent; + private COPWinForms.ComponentWord2 componentWord; } } \ No newline at end of file diff --git a/UniversityView/FormMain.cs b/UniversityView/FormMain.cs index 3c1081c..eaf868e 100644 --- a/UniversityView/FormMain.cs +++ b/UniversityView/FormMain.cs @@ -1,4 +1,5 @@ using COP.Info; +using COPWinForms; using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing; using DocumentFormat.OpenXml.Spreadsheet; using Microsoft.Extensions.Logging; @@ -6,9 +7,13 @@ using System.Windows.Forms; using UniversityBusinessLogic.BusinessLogics; using UniversityContracts.BindingModels; using UniversityContracts.BusinessLogicsContracts; +using UniversityContracts.SearchModels; +using UniversityContracts.ViewModels; using WinFormsControlLibrary; using static COP.ExcelComponent; +using static COPWinForms.ComponentWord2; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window; +using LegendPosition = WinFormsControlLibrary.LegendPosition; namespace UniversityView { @@ -32,7 +37,7 @@ namespace UniversityView try { tableOfValues.ClearRows(); - var list = _studentLogic.ReadList(null); + var list = _studentLogic.Read(null); if (list != null) { tableOfValues.SetCellValueFromList(list); @@ -65,6 +70,7 @@ namespace UniversityView { var columnConfigs = new List { + new GridColumnConfig { HeaderText = "Id", Width = 100, Visible = false, PropertyName = "Id" }, new GridColumnConfig { HeaderText = "ФИО", Width = 100, Visible = true, PropertyName = "FIO" }, new GridColumnConfig { HeaderText = "Направление", Width = 80, Visible = true, PropertyName = "DirectionName" }, new GridColumnConfig { HeaderText = "Электронная почта", Width = 80, Visible = true, PropertyName = "Email" }, @@ -75,19 +81,46 @@ namespace UniversityView private void ИзменитьToolStripMenuItem_Click(object sender, EventArgs e) { + var service = Program.ServiceProvider?.GetService(typeof(FormStudent)); + if (service is FormStudent form) + { + if (tableOfValues.SelectedRowIndex != -1) + { + var selectedStudent = tableOfValues.GetSelectedObject(); + form.Id = Convert.ToInt32(selectedStudent.Id); + if (form.ShowDialog() == DialogResult.OK) + { + LoadData(); + } + } + else + { + MessageBox.Show("Выберите студента для редактирования"); + } + } } private void УдалитьToolStripMenuItem_Click(object sender, EventArgs e) { - DialogResult dialogResult = MessageBox.Show("Удалить выбранный элемент?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question); - if (dialogResult == DialogResult.Yes) - _studentLogic.Delete(new StudentBindingModel { Id = tableOfValues.SelectedRowIndex }); - LoadData(); + if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) + { + var selectedStudent = tableOfValues.GetSelectedObject(); + int id = Convert.ToInt32(selectedStudent.Id); + try + { + _studentLogic.Delete(new StudentBindingModel { Id = id }); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + LoadData(); + } } private void СоздатьПростойДокументToolStripMenuItem_Click(object sender, EventArgs e) { - var list = _studentLogic.ReadList(null); + var list = _studentLogic.Read(null); List images = new(); using var dialog = new SaveFileDialog { @@ -118,13 +151,62 @@ namespace UniversityView private void СоздатьДокументСТаблицейToolStripMenuItem_Click(object sender, EventArgs e) { + var list = _studentLogic.Read(null); + List data = new(); + List mergedColumns = new() + { + new int[] { 1, 2 } + }; + + List columnDefinitions = new() + { + new ColumnDefinition { Header = "Идентификатор", PropertyName = "Id", Width = 11 }, + new ColumnDefinition { Header = "Личные данные", PropertyName = "PersonalData", Width = 11 }, + new ColumnDefinition { Header = "Личные данные", PropertyName = "PersonalData1", Width = 11 }, + new ColumnDefinition { Header = "Направление", PropertyName = "DirectionName", Width = 21 } + }; + + List columnDefinitions2 = new() + { + new ColumnDefinition { Header = "Идентификатор", PropertyName = "Id", Width = 11 }, + new ColumnDefinition { Header = "ФИО", PropertyName = "FIO", Width = 11 }, + new ColumnDefinition { Header = "Электронная почта", PropertyName = "Email", Width = 70 }, + new ColumnDefinition { Header = "Направление", PropertyName = "DirectionName", Width = 21 } + }; + + using var dialog = new SaveFileDialog + { + Filter = "docx|*.docx" + }; + + if (dialog.ShowDialog() == DialogResult.OK) + { + try + { + if (list != null) + { + foreach (var item in list) + { + data.Add(new StudentBindingModel() { Id = item.Id, FIO = item.FIO, Email = item.Email, DirectionName = item.DirectionName}); + } + } + TableWord tableWord = new(dialog.FileName, "Таблица со студентами", columnDefinitions, columnDefinitions2, data, mergedColumns); + componentWord.CreateTable(tableWord); + MessageBox.Show("Сохарнено успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } private void СоздатьДокументСДиаграммойToolStripMenuItem_Click(object sender, EventArgs e) { - var listStudents = _studentLogic.ReadList(null); - var listDirections = _directionLogic.ReadList(null); + var listStudents = _studentLogic.Read(null); + var listDirections = _directionLogic.Read(null); List<(string, int)> data = new(); List gistData = new(); using var dialog = new SaveFileDialog diff --git a/UniversityView/FormMain.resx b/UniversityView/FormMain.resx index 8b51eef..72ca80c 100644 --- a/UniversityView/FormMain.resx +++ b/UniversityView/FormMain.resx @@ -66,4 +66,7 @@ 309, 17 + + 499, 17 + \ No newline at end of file diff --git a/UniversityView/FormStudent.cs b/UniversityView/FormStudent.cs index cab5796..ee35a01 100644 --- a/UniversityView/FormStudent.cs +++ b/UniversityView/FormStudent.cs @@ -1,7 +1,11 @@ -using Microsoft.Extensions.Logging; +using DocumentFormat.OpenXml.Office2010.Excel; +using Microsoft.Extensions.Logging; +using NPOI.OpenXmlFormats.Spreadsheet; using System.ComponentModel; +using UniversityBusinessLogic.BusinessLogics; using UniversityContracts.BindingModels; using UniversityContracts.BusinessLogicsContracts; +using UniversityContracts.ViewModels; namespace UniversityView { @@ -14,6 +18,8 @@ namespace UniversityView BindingList _list; private int? _id; public int Id { set { _id = value; } } + private string? _item; + private string itemChecked { set { _item = value; } } List directions = new(); public FormStudent(ILogger logger, IStudentLogic studentLogic, IDirectionLogic directionLogic) { @@ -52,19 +58,15 @@ namespace UniversityView _logger.LogInformation("Сохранение студента"); try { - var model = new StudentBindingModel + _studentLogic.CreateOrUpdate(new StudentBindingModel { - Id = _id ?? 0, + Id = _id, FIO = textBoxFIO.Text, - Email = componenttBox1.TextBoxValue, PhotoFilePath = imagePath, + Email = componenttBox1.TextBoxValue, DirectionName = userCheckedListBox1.SelectedValue - }; - var operationResult = _id.HasValue ? _studentLogic.Update(model) : _studentLogic.Create(model); - if (!operationResult) - { - throw new Exception("Ошибка при сохранении. Дополнительная информация в логах."); - } + }); ; + MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information); DialogResult = DialogResult.OK; Close(); @@ -85,6 +87,29 @@ namespace UniversityView private void FormStudent_Load(object sender, EventArgs e) { LoadData(); + if (_id.HasValue) + { + try + { + StudentViewModel? view = _studentLogic.Read(new StudentBindingModel { Id = _id.Value })?[0]; + if (view != null) + { + textBoxFIO.Text = view.FIO; + componenttBox1.TextBoxValue = view.Email; + imagePath = view.PhotoFilePath; + string[] dirs = view.DirectionName.Split(";"); + foreach (var dir in dirs) + { + userCheckedListBox1.SelectedValue = dir; + } + pictureBox.Image = Image.FromFile(imagePath); + } + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } } private void LoadData() @@ -92,7 +117,7 @@ namespace UniversityView _logger.LogInformation("Загрузка направлений"); try { - var list = _directionLogic.ReadList(null); + var list = _directionLogic.Read(null); userCheckedListBox1.ClearList(); directions.Clear(); _list.Clear(); diff --git a/UniversityView/Program.cs b/UniversityView/Program.cs index 73ec1ab..bf2a326 100644 --- a/UniversityView/Program.cs +++ b/UniversityView/Program.cs @@ -5,7 +5,7 @@ using System; using UniversityBusinessLogic.BusinessLogics; using UniversityContracts.BusinessLogicsContracts; using UniversityContracts.StoragesContracts; -using UniversityDatabaseImplement.Implements; +using UniversityUniversityDatabaseImplement.Implements; namespace UniversityView { diff --git a/UniversityView/UniversityView.csproj b/UniversityView/UniversityView.csproj index 83eb141..9198c2d 100644 --- a/UniversityView/UniversityView.csproj +++ b/UniversityView/UniversityView.csproj @@ -18,7 +18,7 @@ - +