сделала

This commit is contained in:
Татьяна Артамонова 2023-11-09 04:07:06 +04:00
parent 5ec407fa6d
commit 1bd9dce5f8
27 changed files with 554 additions and 448 deletions

View File

@ -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<string>());
}
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));
}
}
}

120
COP/UserCheckedListBox.resx Normal file
View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -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);

View File

@ -9,11 +9,9 @@ namespace UniversityBusinessLogic.BusinessLogics
{
public class DirectionLogic : IDirectionLogic
{
private readonly ILogger _logger;
private readonly IDirectionStorage _directionStorage;
public DirectionLogic(ILogger<DirectionLogic> 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);
}
@ -38,71 +36,27 @@ namespace UniversityBusinessLogic.BusinessLogics
}
}
public bool Delete(DirectionBindingModel model)
public void 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)
{
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<DirectionViewModel>? 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<DirectionViewModel> 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<DirectionViewModel> { _directionStorage.GetElement(model) };
}
return _directionStorage.GetFilteredList(model);
}
}
}

View File

@ -9,113 +9,56 @@ namespace UniversityBusinessLogic.BusinessLogics
{
public class StudentLogic : IStudentLogic
{
private readonly ILogger _logger;
private readonly IStudentStorage _studentStorage;
public StudentLogic(ILogger<StudentLogic> 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<StudentViewModel>? 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<StudentViewModel> Read(StudentBindingModel model)
{
if (model == null)
{
return _studentStorage.GetFullList();
}
if (model.Id.HasValue)
{
return new List<StudentViewModel> { _studentStorage.GetElement(model) };
}
return _studentStorage.GetFilteredList(model);
}
}
}

View File

@ -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;
}
}

View File

@ -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; }
}
}

View File

@ -6,9 +6,8 @@ namespace UniversityContracts.BusinessLogicsContracts
{
public interface IDirectionLogic
{
List<DirectionViewModel>? ReadList(DirectionBindingModel? model);
DirectionViewModel? ReadElement(DirectionBindingModel model);
bool Delete(DirectionBindingModel model);
List<DirectionViewModel> Read(DirectionBindingModel model);
void CreateOrUpdate(DirectionBindingModel model);
void Delete(DirectionBindingModel model);
}
}

View File

@ -6,10 +6,8 @@ namespace UniversityContracts.BusinessLogicsContracts
{
public interface IStudentLogic
{
List<StudentViewModel>? ReadList(StudentSearchModel? model);
StudentViewModel? ReadElement(StudentSearchModel model);
bool Create(StudentBindingModel model);
bool Update(StudentBindingModel model);
bool Delete(StudentBindingModel model);
List<StudentViewModel> Read(StudentBindingModel model);
void CreateOrUpdate(StudentBindingModel model);
void Delete(StudentBindingModel model);
}
}

View File

@ -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; }
}
}

View File

@ -1,5 +1,4 @@
using UniversityContracts.BindingModels;
using UniversityContracts.SearchModels;
using UniversityContracts.ViewModels;
namespace UniversityContracts.StoragesContracts
@ -8,9 +7,9 @@ namespace UniversityContracts.StoragesContracts
{
List<DirectionViewModel> GetFullList();
List<DirectionViewModel> 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);
}
}

View File

@ -7,10 +7,10 @@ namespace UniversityContracts.StoragesContracts
public interface IStudentStorage
{
List<StudentViewModel> GetFullList();
List<StudentViewModel> GetFilteredList(StudentSearchModel model);
StudentViewModel? GetElement(StudentSearchModel model);
StudentViewModel? Insert(StudentBindingModel model);
StudentViewModel? Update(StudentBindingModel model);
StudentViewModel? Delete(StudentBindingModel model);
List<StudentViewModel> GetFilteredList(StudentBindingModel model);
StudentViewModel? GetElement(StudentBindingModel model);
void Insert(StudentBindingModel model);
void Update(StudentBindingModel model);
void Delete(StudentBindingModel model);
}
}

View File

@ -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; }
}
}

View File

@ -1,6 +1,6 @@
namespace UniversityDataModels.Models
{
public interface IStudentModel : IId
public interface IStudentModel
{
string FIO { get; }
string PhotoFilePath { get; }

View File

@ -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<DirectionViewModel> 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<DirectionViewModel> GetFullList()
{
using var context = new UniversityDatabase();
return context.Directions
.Select(x => x.GetViewModel)
.ToList();
.Select(CreateModel)
.ToList();
}
public List<DirectionViewModel> 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
};
}
}
}

View File

@ -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<StudentViewModel> GetFilteredList(StudentBindingModel model)
{
var context = new UniversityDatabase();
return context.Students
.Where(student => student.FIO.Contains(model.FIO))
.ToList()
.Select(CreateModel)
.ToList();
}
public List<StudentViewModel> GetFullList()
{
using var context = new UniversityDatabase();
return context.Students
.Select(x => x.GetViewModel)
.ToList()
.Select(CreateModel)
.ToList();
}
public List<StudentViewModel> 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,
};
}
}
}

View File

@ -11,7 +11,7 @@ using UniversityDatabaseImplement;
namespace UniversityDatabaseImplement.Migrations
{
[DbContext(typeof(UniversityDatabase))]
[Migration("20231027233645_InitialCreate")]
[Migration("20231108231603_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />

View File

@ -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;
}
}

View File

@ -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; }
}
}

View File

@ -26,7 +26,7 @@ namespace UniversityView
{
try
{
var list = _logic.ReadList(null);
var list = _logic.Read(null);
_list.Clear();
foreach (var item in list)
{

View File

@ -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;
}
}

View File

@ -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<GridColumnConfig>
{
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<StudentSearchModel>();
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<StudentSearchModel>();
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<ImageInfo> 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<StudentBindingModel> data = new();
List<int[]> mergedColumns = new()
{
new int[] { 1, 2 }
};
List<ColumnDefinition> 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<ColumnDefinition> 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<StudentBindingModel> 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<HistogramData> gistData = new();
using var dialog = new SaveFileDialog

View File

@ -66,4 +66,7 @@
<metadata name="gistogramPdfComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>309, 17</value>
</metadata>
<metadata name="componentWord.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>499, 17</value>
</metadata>
</root>

View File

@ -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<DirectionBindingModel> _list;
private int? _id;
public int Id { set { _id = value; } }
private string? _item;
private string itemChecked { set { _item = value; } }
List<string> directions = new();
public FormStudent(ILogger<FormStudent> 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();

View File

@ -5,7 +5,7 @@ using System;
using UniversityBusinessLogic.BusinessLogics;
using UniversityContracts.BusinessLogicsContracts;
using UniversityContracts.StoragesContracts;
using UniversityDatabaseImplement.Implements;
using UniversityUniversityDatabaseImplement.Implements;
namespace UniversityView
{

View File

@ -18,7 +18,7 @@
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.1" />
<PackageReference Include="NLog" Version="5.2.5" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="winformscontrollibrary" Version="1.0.0" />
<PackageReference Include="WinFormsControlLibrary" Version="1.0.0" />
</ItemGroup>
<ItemGroup>