ИСЭбд-21 Мосевнин А.М. LabWork_2 #2

Closed
Aleks_andr435 wants to merge 1 commits from LabWork_2 into LabWork_1
28 changed files with 848 additions and 261 deletions

View File

@ -7,18 +7,16 @@
public int Id { get; private set; } public int Id { get; private set; }
public string Author { get; private set; } = string.Empty; public string Author { get; private set; } = string.Empty;
public string Name { get; private set; } = string.Empty; public string Name { get; private set; } = string.Empty;
public BookType Type { get; set; } = BookType.None; public BookType TypeBookID { get; set; } = BookType.None;
public int LibraryID { get; private set; }
public static Book CreateEntity(int id, string author, string name, int libraryID, BookType type = BookType.None) public static Book CreateEntity(int id, string author, string name, BookType typeBookID = BookType.None)
{ {
return new Book return new Book
{ {
Id = id, Id = id,
Author = author ?? string.Empty, Author = author ?? string.Empty,
Name = name ?? string.Empty, Name = name ?? string.Empty,
LibraryID = libraryID, TypeBookID = typeBookID
Type = type
}; };
} }
} }

View File

@ -16,7 +16,7 @@ namespace ProjectLibrary.Entites
{ {
get; get;
private set; private set;
} = []; }
public static Library CreateEntity(int id, string name, string address, IEnumerable<Book_Library> bookLibrary) public static Library CreateEntity(int id, string name, string address, IEnumerable<Book_Library> bookLibrary)
{ {

View File

@ -13,7 +13,6 @@ namespace ProjectLibrary.Entites
public DateTime OrderDate { get; private set; } public DateTime OrderDate { get; private set; }
public DateTime ReturnDate { get; private set; } public DateTime ReturnDate { get; private set; }
public int ReaderID { get; private set; } public int ReaderID { get; private set; }
public IEnumerable<Book_Orders> BookOrders public IEnumerable<Book_Orders> BookOrders
{ {
get; get;
@ -21,12 +20,12 @@ namespace ProjectLibrary.Entites
} = []; } = [];
public static Orders CreateEntity(int id, DateTime orderDate, DateTime returnDate, int readerID, IEnumerable<Book_Orders> bookOrders) public static Orders CreateEntity(int id, DateTime returnDate, int readerID, IEnumerable<Book_Orders> bookOrders)
{ {
return new Orders return new Orders
{ {
Id = id, Id = id,
OrderDate = orderDate, OrderDate = DateTime.Now,
ReturnDate = returnDate, ReturnDate = returnDate,
ReaderID = readerID, ReaderID = readerID,
BookOrders = bookOrders BookOrders = bookOrders

View File

@ -2,14 +2,16 @@
{ {
public class TicketExtensions public class TicketExtensions
{ {
public int Id { get; private set; }
public int ReaderID { get; private set; } public int ReaderID { get; private set; }
public DateTime LastUpdateDate { get; private set; } public DateTime LastUpdateDate { get; private set; }
public DateTime NextUpdateDate { get; private set; } public DateTime NextUpdateDate { get; private set; }
public static TicketExtensions CreateEntity(int readerID, DateTime lastUpdateDate, DateTime nextUpdateDate) public static TicketExtensions CreateEntity(int id, int readerID, DateTime lastUpdateDate, DateTime nextUpdateDate)
{ {
return new TicketExtensions return new TicketExtensions
{ {
Id = id,
ReaderID = readerID, ReaderID = readerID,
LastUpdateDate = lastUpdateDate, LastUpdateDate = lastUpdateDate,
NextUpdateDate = nextUpdateDate NextUpdateDate = nextUpdateDate

View File

@ -33,10 +33,8 @@
lblName = new Label(); lblName = new Label();
txtName = new TextBox(); txtName = new TextBox();
lblType = new Label(); lblType = new Label();
lblLibraryId = new Label();
btnSave = new Button(); btnSave = new Button();
buttonCancel_Click = new Button(); buttonCancel_Click = new Button();
comboBoxLibrary = new ComboBox();
checkedListBox1 = new CheckedListBox(); checkedListBox1 = new CheckedListBox();
SuspendLayout(); SuspendLayout();
// //
@ -81,15 +79,6 @@
lblType.TabIndex = 6; lblType.TabIndex = 6;
lblType.Text = "Тип:"; lblType.Text = "Тип:";
// //
// lblLibraryId
//
lblLibraryId.AutoSize = true;
lblLibraryId.Location = new Point(19, 226);
lblLibraryId.Name = "lblLibraryId";
lblLibraryId.Size = new Size(114, 20);
lblLibraryId.TabIndex = 8;
lblLibraryId.Text = "ID библиотеки:";
//
// btnSave // btnSave
// //
btnSave.Location = new Point(19, 266); btnSave.Location = new Point(19, 266);
@ -109,16 +98,6 @@
buttonCancel_Click.Text = "Отмена"; buttonCancel_Click.Text = "Отмена";
buttonCancel_Click.Click += ButtonCancel_Click; buttonCancel_Click.Click += ButtonCancel_Click;
// //
// comboBoxLibrary
//
comboBoxLibrary.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxLibrary.FormattingEnabled = true;
comboBoxLibrary.Items.AddRange(new object[] { "Fiction", "Non-Fiction", "Science", "Biography" });
comboBoxLibrary.Location = new Point(151, 223);
comboBoxLibrary.Name = "comboBoxLibrary";
comboBoxLibrary.Size = new Size(200, 28);
comboBoxLibrary.TabIndex = 12;
//
// checkedListBox1 // checkedListBox1
// //
checkedListBox1.FormattingEnabled = true; checkedListBox1.FormattingEnabled = true;
@ -126,20 +105,17 @@
checkedListBox1.Name = "checkedListBox1"; checkedListBox1.Name = "checkedListBox1";
checkedListBox1.Size = new Size(246, 114); checkedListBox1.Size = new Size(246, 114);
checkedListBox1.TabIndex = 13; checkedListBox1.TabIndex = 13;
checkedListBox1.SelectedIndexChanged += checkedListBox1_SelectedIndexChanged;
// //
// FBook // FBook
// //
ClientSize = new Size(400, 300); ClientSize = new Size(400, 300);
Controls.Add(checkedListBox1); Controls.Add(checkedListBox1);
Controls.Add(comboBoxLibrary);
Controls.Add(buttonCancel_Click); Controls.Add(buttonCancel_Click);
Controls.Add(lblAuthor); Controls.Add(lblAuthor);
Controls.Add(txtAuthor); Controls.Add(txtAuthor);
Controls.Add(lblName); Controls.Add(lblName);
Controls.Add(txtName); Controls.Add(txtName);
Controls.Add(lblType); Controls.Add(lblType);
Controls.Add(lblLibraryId);
Controls.Add(btnSave); Controls.Add(btnSave);
Name = "FBook"; Name = "FBook";
Text = "Книга"; Text = "Книга";
@ -153,10 +129,8 @@
private System.Windows.Forms.Label lblName; private System.Windows.Forms.Label lblName;
private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.Label lblType; private System.Windows.Forms.Label lblType;
private System.Windows.Forms.Label lblLibraryId;
private System.Windows.Forms.Button btnSave; private System.Windows.Forms.Button btnSave;
private Button buttonCancel_Click; private Button buttonCancel_Click;
private ComboBox comboBoxLibrary;
private CheckedListBox checkedListBox1; private CheckedListBox checkedListBox1;
} }
} }

View File

@ -24,8 +24,12 @@ namespace ProjectLibrary.Forms
txtAuthor.Text = book.Author; txtAuthor.Text = book.Author;
txtName.Text = book.Name; txtName.Text = book.Name;
//cmbType.SelectedItem = book.Type; //checkedListBox1.SelectedItem = book.TypeBookID;
Review

Закомментированного кода быть не должно

Закомментированного кода быть не должно
comboBoxLibrary.SelectedItem = book.LibraryID; char[] listInd = Convert.ToString((int)book.TypeBookID, 2).ToCharArray();
for (int i = 0; i < listInd.Length; i++)
{
checkedListBox1.SetItemChecked(i, listInd[i]=='1');
}
_bookId = value; _bookId = value;
} }
@ -36,11 +40,10 @@ namespace ProjectLibrary.Forms
} }
} }
public FBook(IBookRepository bookRepository, ILibraryRepository libraryRepository) public FBook(IBookRepository bookRepository)
{ {
InitializeComponent(); InitializeComponent();
_bookRepository = bookRepository ?? throw new ArgumentNullException(nameof(bookRepository)); _bookRepository = bookRepository ?? throw new ArgumentNullException(nameof(bookRepository));
comboBoxLibrary.DataSource = libraryRepository.ReadLibraries();
foreach(var elem in Enum.GetValues(typeof(BookType))) foreach(var elem in Enum.GetValues(typeof(BookType)))
{ {
if (!elem.Equals(BookType.None)) checkedListBox1.Items.Add(elem); if (!elem.Equals(BookType.None)) checkedListBox1.Items.Add(elem);
@ -51,39 +54,22 @@ namespace ProjectLibrary.Forms
{ {
try try
{ {
if (string.IsNullOrWhiteSpace(txtAuthor.Text) || string.IsNullOrWhiteSpace(txtName.Text) || comboBoxLibrary.SelectedItem == null) if (string.IsNullOrWhiteSpace(txtAuthor.Text) || string.IsNullOrWhiteSpace(txtName.Text))
{ {
throw new Exception("Имеются незаполненные поля."); throw new Exception("Имеются незаполненные поля.");
} }
BookType selectedType = BookType.None;
foreach (var item in checkedListBox1.CheckedItems)
{
if (item is BookType type)
{
selectedType |= type;
}
}
var book = Book.CreateEntity(
_bookId ?? 0,
txtAuthor.Text,
txtName.Text,
Convert.ToInt32(comboBoxLibrary.SelectedItem),
selectedType
);
if (_bookId.HasValue) if (_bookId.HasValue)
{ {
_bookRepository.UpdateBook(book); _bookRepository.UpdateBook(CreateBook(_bookId.Value));
} }
else else
{ {
_bookRepository.CreateBook(book); _bookRepository.CreateBook(CreateBook(0));
} }
Close(); Close();
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -91,35 +77,26 @@ namespace ProjectLibrary.Forms
} }
} }
private Book CreateBook(int bookId)
{
BookType selectedType = BookType.None;
foreach (var item in checkedListBox1.CheckedItems)
{
if (item is BookType type)
{
selectedType |= type; // Это должно работать, если тип является BookType
}
}
return Book.CreateEntity(bookId, txtAuthor.Text, txtName.Text, selectedType);
}
private void ButtonCancel_Click(object sender, EventArgs e) private void ButtonCancel_Click(object sender, EventArgs e)
{ {
Close(); Close();
} }
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
BookType selectedType = BookType.None;
foreach (var item in checkedListBox1.CheckedItems)
{
if (item is BookType type)
{
selectedType |= type;
}
}
var book = _bookRepository.ReadBookById(_bookId ?? 0);
book.Type = selectedType;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при обработке выбора", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
} }
} }

View File

@ -25,7 +25,7 @@ namespace ProjectLibrary.Forms
txtName.Text = library.Name; txtName.Text = library.Name;
txtAddress.Text = library.Address; txtAddress.Text = library.Address;
dataGridView.DataSource = library.BookLibrary; SetListBooksToDataGrid(library.BookLibrary);
_orderId = value; _orderId = value;
} }
catch (Exception ex) catch (Exception ex)
@ -69,6 +69,8 @@ namespace ProjectLibrary.Forms
{ {
_libraryRepository.CreateLibrary(library); _libraryRepository.CreateLibrary(library);
} }
Close(); Close();
} }
catch (Exception ex) catch (Exception ex)
@ -79,7 +81,7 @@ namespace ProjectLibrary.Forms
private void buttonCancel_Click_Click(object sender, EventArgs e) private void buttonCancel_Click_Click(object sender, EventArgs e)
{ {
this.Close(); Close();
} }
private List<Book_Library> CreateListBooksFromDataGrid() private List<Book_Library> CreateListBooksFromDataGrid()
@ -91,9 +93,21 @@ namespace ProjectLibrary.Forms
{ {
continue; continue;
} }
list.Add(Book_Library.CreateEntity(0, Convert.ToInt32(row.Cells["ColumnBook"].Value), Convert.ToInt32(row.Cells["ColumnCount"].Value))); list.Add(Book_Library.CreateEntity(0, Convert.ToInt32(row.Cells["Book"].Value), Convert.ToInt32(row.Cells["Count"].Value)));
} }
return list; return list;
} }
private void SetListBooksToDataGrid(IEnumerable<Book_Library> list)
{
int index = 0;
foreach (Book_Library elem in list)
{
dataGridView.Rows.Add();
dataGridView.Rows[index].Cells["Book"].Value = elem.BookID;
dataGridView.Rows[index].Cells["Count"].Value = elem.Count;
index++;
}
}
} }
} }

View File

@ -4,9 +4,7 @@
{ {
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
private Label lblOrderDate; private Label lblOrderDate;
private TextBox txtOrderDate;
private Label lblReturnDate; private Label lblReturnDate;
private TextBox txtReturnDate;
private Label lblReaderID; private Label lblReaderID;
private Label lblBookID; private Label lblBookID;
private Button btnSave; private Button btnSave;
@ -23,9 +21,7 @@
private void InitializeComponent() private void InitializeComponent()
{ {
lblOrderDate = new Label(); lblOrderDate = new Label();
txtOrderDate = new TextBox();
lblReturnDate = new Label(); lblReturnDate = new Label();
txtReturnDate = new TextBox();
lblReaderID = new Label(); lblReaderID = new Label();
lblBookID = new Label(); lblBookID = new Label();
btnSave = new Button(); btnSave = new Button();
@ -33,6 +29,8 @@
comboBox = new ComboBox(); comboBox = new ComboBox();
dataGridViewBook = new DataGridView(); dataGridViewBook = new DataGridView();
Book = new DataGridViewComboBoxColumn(); Book = new DataGridViewComboBoxColumn();
dtpOrderDate = new DateTimePicker();
dtptxtReturnDate = new DateTimePicker();
((System.ComponentModel.ISupportInitialize)dataGridViewBook).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridViewBook).BeginInit();
SuspendLayout(); SuspendLayout();
// //
@ -41,39 +39,25 @@
lblOrderDate.AutoSize = true; lblOrderDate.AutoSize = true;
lblOrderDate.Location = new Point(12, 25); lblOrderDate.Location = new Point(12, 25);
lblOrderDate.Name = "lblOrderDate"; lblOrderDate.Name = "lblOrderDate";
lblOrderDate.Size = new Size(72, 15); lblOrderDate.Size = new Size(93, 20);
lblOrderDate.TabIndex = 2; lblOrderDate.TabIndex = 2;
lblOrderDate.Text = "Дата заказа:"; lblOrderDate.Text = "Дата заказа:";
// //
// txtOrderDate
//
txtOrderDate.Location = new Point(129, 25);
txtOrderDate.Name = "txtOrderDate";
txtOrderDate.Size = new Size(200, 23);
txtOrderDate.TabIndex = 3;
//
// lblReturnDate // lblReturnDate
// //
lblReturnDate.AutoSize = true; lblReturnDate.AutoSize = true;
lblReturnDate.Location = new Point(12, 65); lblReturnDate.Location = new Point(12, 65);
lblReturnDate.Name = "lblReturnDate"; lblReturnDate.Name = "lblReturnDate";
lblReturnDate.Size = new Size(86, 15); lblReturnDate.Size = new Size(111, 20);
lblReturnDate.TabIndex = 4; lblReturnDate.TabIndex = 4;
lblReturnDate.Text = "Дата возврата:"; lblReturnDate.Text = "Дата возврата:";
// //
// txtReturnDate
//
txtReturnDate.Location = new Point(129, 65);
txtReturnDate.Name = "txtReturnDate";
txtReturnDate.Size = new Size(200, 23);
txtReturnDate.TabIndex = 5;
//
// lblReaderID // lblReaderID
// //
lblReaderID.AutoSize = true; lblReaderID.AutoSize = true;
lblReaderID.Location = new Point(12, 105); lblReaderID.Location = new Point(12, 105);
lblReaderID.Name = "lblReaderID"; lblReaderID.Name = "lblReaderID";
lblReaderID.Size = new Size(73, 15); lblReaderID.Size = new Size(92, 20);
lblReaderID.TabIndex = 6; lblReaderID.TabIndex = 6;
lblReaderID.Text = "ID читателя:"; lblReaderID.Text = "ID читателя:";
// //
@ -82,7 +66,7 @@
lblBookID.AutoSize = true; lblBookID.AutoSize = true;
lblBookID.Location = new Point(12, 145); lblBookID.Location = new Point(12, 145);
lblBookID.Name = "lblBookID"; lblBookID.Name = "lblBookID";
lblBookID.Size = new Size(56, 15); lblBookID.Size = new Size(71, 20);
lblBookID.TabIndex = 8; lblBookID.TabIndex = 8;
lblBookID.Text = "ID книги:"; lblBookID.Text = "ID книги:";
// //
@ -108,7 +92,7 @@
// //
comboBox.Location = new Point(129, 108); comboBox.Location = new Point(129, 108);
comboBox.Name = "comboBox"; comboBox.Name = "comboBox";
comboBox.Size = new Size(203, 23); comboBox.Size = new Size(203, 28);
comboBox.TabIndex = 0; comboBox.TabIndex = 0;
// //
// dataGridViewBook // dataGridViewBook
@ -128,16 +112,31 @@
Book.Name = "Book"; Book.Name = "Book";
Book.Width = 125; Book.Width = 125;
// //
// dtpOrderDate
//
dtpOrderDate.Enabled = false;
dtpOrderDate.Location = new Point(129, 20);
dtpOrderDate.Name = "dtpOrderDate";
dtpOrderDate.Size = new Size(203, 27);
dtpOrderDate.TabIndex = 13;
//
// dtptxtReturnDate
//
dtptxtReturnDate.Location = new Point(129, 60);
dtptxtReturnDate.Name = "dtptxtReturnDate";
dtptxtReturnDate.Size = new Size(203, 27);
dtptxtReturnDate.TabIndex = 14;
//
// FOrder // FOrder
// //
ClientSize = new Size(372, 332); ClientSize = new Size(372, 332);
Controls.Add(dtptxtReturnDate);
Controls.Add(dtpOrderDate);
Controls.Add(dataGridViewBook); Controls.Add(dataGridViewBook);
Controls.Add(comboBox); Controls.Add(comboBox);
Controls.Add(buttonCancel_Click); Controls.Add(buttonCancel_Click);
Controls.Add(lblOrderDate); Controls.Add(lblOrderDate);
Controls.Add(txtOrderDate);
Controls.Add(lblReturnDate); Controls.Add(lblReturnDate);
Controls.Add(txtReturnDate);
Controls.Add(lblReaderID); Controls.Add(lblReaderID);
Controls.Add(lblBookID); Controls.Add(lblBookID);
Controls.Add(btnSave); Controls.Add(btnSave);
@ -152,5 +151,7 @@
private ComboBox comboBox; private ComboBox comboBox;
private DataGridView dataGridViewBook; private DataGridView dataGridViewBook;
private DataGridViewComboBoxColumn Book; private DataGridViewComboBoxColumn Book;
private DateTimePicker dtpOrderDate;
private DateTimePicker dtptxtReturnDate;
} }
} }

View File

@ -1,43 +1,28 @@
using ProjectLibrary.Repositories; using ProjectLibrary.Repositories;
using ProjectLibrary.Entites; using ProjectLibrary.Entites;
using System.Xml.Linq; using System.Xml.Linq;
using ProjectLibrary.Repositores;
using System.Windows.Forms;
namespace ProjectLibrary.Forms namespace ProjectLibrary.Forms
{ {
public partial class FOrder : Form public partial class FOrder : Form
{ {
private readonly IOrderRepository _orderRepository; private readonly IOrderRepository _orderRepository;
private int? _orderId; private readonly IBookRepository _bookRepository;
public FOrder(IOrderRepository orderRepository) public FOrder(IOrderRepository orderRepository, IReaderRepository _readerRepository, IBookRepository bookRepository)
{ {
InitializeComponent(); InitializeComponent();
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository)); _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
} _bookRepository = bookRepository ?? throw new ArgumentNullException(nameof(_bookRepository));
comboBox.DataSource = _readerRepository.ReadReaders();
comboBox.DisplayMember = "Name";
comboBox.ValueMember = "Id";
public int Id Book.DataSource = bookRepository.ReadBooks();
{ Book.DisplayMember = "Name";
set Book.ValueMember = "Id";
{
try
{
var order = _orderRepository.ReadOrderById(value);
if (order == null)
{
throw new InvalidOperationException("Заказ не найден.");
}
txtOrderDate.Text = order.OrderDate.ToString();
txtReturnDate.Text = order.ReturnDate.ToString();
comboBox.SelectedItem = order.ReaderID;
dataGridViewBook.DataSource = order.BookOrders;
_orderId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
} }
private List<Book_Orders> CreateListBooksFromDataGrid() private List<Book_Orders> CreateListBooksFromDataGrid()
@ -45,11 +30,11 @@ namespace ProjectLibrary.Forms
var list = new List<Book_Orders>(); var list = new List<Book_Orders>();
foreach (DataGridViewRow row in dataGridViewBook.Rows) foreach (DataGridViewRow row in dataGridViewBook.Rows)
{ {
if (row.Cells["ColumnBook"].Value == null) if (row.Cells["Book"].Value == null)
{ {
continue; continue;
} }
list.Add(Book_Orders.CreateEntity(0, Convert.ToInt32(row.Cells["ColumnBook"].Value))); list.Add(Book_Orders.CreateEntity(0, Convert.ToInt32(row.Cells["Book"].Value)));
} }
return list; return list;
} }
@ -58,27 +43,20 @@ namespace ProjectLibrary.Forms
{ {
try try
{ {
if (string.IsNullOrWhiteSpace(txtOrderDate.Text) || string.IsNullOrWhiteSpace(txtReturnDate.Text) || comboBox.SelectedItem == null) if (comboBox.SelectedItem == null)
{ {
throw new Exception("Не все поля заполнены."); throw new Exception("Не все поля заполнены.");
} }
var order = Orders.CreateEntity( var order = Orders.CreateEntity(
_orderId ?? 0, 0,
DateTime.Parse(txtOrderDate.Text), dtptxtReturnDate.Value,
DateTime.Parse(txtReturnDate.Text), Convert.ToInt32(comboBox.SelectedValue),
int.Parse(comboBox.SelectedItem.ToString()),
CreateListBooksFromDataGrid() CreateListBooksFromDataGrid()
); );
if (_orderId.HasValue) _orderRepository.CreateOrder(order);
{
_orderRepository.UpdateOrder(order);
}
else
{
_orderRepository.CreateOrder(order);
}
Close(); Close();
} }
catch (Exception ex) catch (Exception ex)

View File

@ -120,7 +120,4 @@
<metadata name="Book.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> <metadata name="Book.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value> <value>True</value>
</metadata> </metadata>
<metadata name="Book.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root> </root>

View File

@ -30,7 +30,6 @@
{ {
dataGridViewOrders = new DataGridView(); dataGridViewOrders = new DataGridView();
buttonAdd = new Button(); buttonAdd = new Button();
buttonUpdate = new Button();
buttonRemove = new Button(); buttonRemove = new Button();
((System.ComponentModel.ISupportInitialize)dataGridViewOrders).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridViewOrders).BeginInit();
SuspendLayout(); SuspendLayout();
@ -40,55 +39,40 @@
dataGridViewOrders.AllowUserToAddRows = false; dataGridViewOrders.AllowUserToAddRows = false;
dataGridViewOrders.AllowUserToDeleteRows = false; dataGridViewOrders.AllowUserToDeleteRows = false;
dataGridViewOrders.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; dataGridViewOrders.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewOrders.Location = new Point(10, 9); dataGridViewOrders.Location = new Point(11, 12);
dataGridViewOrders.Margin = new Padding(3, 2, 3, 2);
dataGridViewOrders.Name = "dataGridViewOrders"; dataGridViewOrders.Name = "dataGridViewOrders";
dataGridViewOrders.ReadOnly = true; dataGridViewOrders.ReadOnly = true;
dataGridViewOrders.RowHeadersWidth = 51; dataGridViewOrders.RowHeadersWidth = 51;
dataGridViewOrders.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridViewOrders.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewOrders.Size = new Size(525, 225); dataGridViewOrders.Size = new Size(600, 300);
dataGridViewOrders.TabIndex = 4; dataGridViewOrders.TabIndex = 4;
// //
// buttonAdd // buttonAdd
// //
buttonAdd.Location = new Point(10, 249); buttonAdd.Location = new Point(11, 332);
buttonAdd.Margin = new Padding(3, 2, 3, 2);
buttonAdd.Name = "buttonAdd"; buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(88, 22); buttonAdd.Size = new Size(101, 29);
buttonAdd.TabIndex = 5; buttonAdd.TabIndex = 5;
buttonAdd.Text = "Добавить"; buttonAdd.Text = "Добавить";
buttonAdd.Click += buttonAdd_Click; buttonAdd.Click += buttonAdd_Click;
// //
// buttonUpdate
//
buttonUpdate.Location = new Point(225, 249);
buttonUpdate.Margin = new Padding(3, 2, 3, 2);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(88, 22);
buttonUpdate.TabIndex = 6;
buttonUpdate.Text = "Изменить";
buttonUpdate.Click += buttonUpdate_Click;
//
// buttonRemove // buttonRemove
// //
buttonRemove.Location = new Point(448, 249); buttonRemove.Location = new Point(512, 332);
buttonRemove.Margin = new Padding(3, 2, 3, 2);
buttonRemove.Name = "buttonRemove"; buttonRemove.Name = "buttonRemove";
buttonRemove.Size = new Size(88, 22); buttonRemove.Size = new Size(101, 29);
buttonRemove.TabIndex = 7; buttonRemove.TabIndex = 7;
buttonRemove.Text = "Удалить"; buttonRemove.Text = "Удалить";
buttonRemove.Click += buttonRemove_Click; buttonRemove.Click += buttonRemove_Click;
// //
// FOrders // FOrders
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(551, 309); ClientSize = new Size(630, 412);
Controls.Add(dataGridViewOrders); Controls.Add(dataGridViewOrders);
Controls.Add(buttonAdd); Controls.Add(buttonAdd);
Controls.Add(buttonUpdate);
Controls.Add(buttonRemove); Controls.Add(buttonRemove);
Margin = new Padding(3, 2, 3, 2);
Name = "FOrders"; Name = "FOrders";
Text = "FOrders"; Text = "FOrders";
Load += FOrders_Load; Load += FOrders_Load;
@ -100,7 +84,6 @@
private DataGridView dataGridViewOrders; private DataGridView dataGridViewOrders;
private Button buttonAdd; private Button buttonAdd;
private Button buttonUpdate;
private Button buttonRemove; private Button buttonRemove;
} }
} }

View File

@ -46,26 +46,6 @@ namespace ProjectLibrary.Forms
return true; return true;
} }
private void buttonUpdate_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FOrder>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonRemove_Click(object sender, EventArgs e) private void buttonRemove_Click(object sender, EventArgs e)
{ {
if (!TryGetIdentifierFromSelectedRow(out var findId)) if (!TryGetIdentifierFromSelectedRow(out var findId))

View File

@ -1,5 +1,6 @@
using ProjectLibrary.Entites; using ProjectLibrary.Entites;
using ProjectLibrary.Repositores; using ProjectLibrary.Repositores;
using ProjectLibrary.Repositories;
namespace ProjectLibrary.Forms namespace ProjectLibrary.Forms
{ {
@ -30,10 +31,16 @@ namespace ProjectLibrary.Forms
} }
} }
} }
public FTicket_Extension(ITicketExtensionsRepository ticketRepository) public FTicket_Extension(ITicketExtensionsRepository ticketRepository, IReaderRepository readerRepository)
{ {
InitializeComponent(); InitializeComponent();
_ticketExtensionsRepository = ticketRepository ?? throw new ArgumentNullException(nameof(ticketRepository)); _ticketExtensionsRepository = ticketRepository ?? throw new ArgumentNullException(nameof(ticketRepository));
readerRepository = readerRepository ?? throw new ArgumentNullException(nameof(readerRepository));
comboBoxId.DataSource = readerRepository.ReadReaders();
comboBoxId.DisplayMember = "Name"; // Предполагается, что у Reader есть свойство Name
comboBoxId.ValueMember = "Id"; // И свойство Id для идентификации
} }
private void btnSave_Click(object sender, EventArgs e) private void btnSave_Click(object sender, EventArgs e)
@ -46,7 +53,8 @@ namespace ProjectLibrary.Forms
} }
var ticket = TicketExtensions.CreateEntity( var ticket = TicketExtensions.CreateEntity(
_extensionId ?? 0, 0,
(int)comboBoxId.SelectedValue!,
DateTime.Parse(dtpLastUpdateDate.Text), DateTime.Parse(dtpLastUpdateDate.Text),
DateTime.Parse(dtpNextUpdateDate.Text) DateTime.Parse(dtpNextUpdateDate.Text)
); );

View File

@ -72,7 +72,7 @@ namespace ProjectLibrary.Forms
return false; return false;
} }
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value); id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ReaderID"].Value);
return true; return true;
} }
} }

View File

@ -2,6 +2,11 @@ using ProjectLibrary.Repositories.Implementations;
using ProjectLibrary.Repositories; using ProjectLibrary.Repositories;
using Unity; using Unity;
using ProjectLibrary.Repositores; using ProjectLibrary.Repositores;
using ProjectLibrary.Repositores.Implementations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Unity.Microsoft.Logging;
namespace ProjectLibrary namespace ProjectLibrary
{ {
@ -23,13 +28,28 @@ namespace ProjectLibrary
{ {
var container = new UnityContainer(); var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
// Ðåãèñòðàöèÿ ðåïîçèòîðèåâ // Ðåãèñòðàöèÿ ðåïîçèòîðèåâ
container.RegisterType<IBookRepository, BookRepository>(); container.RegisterType<IBookRepository, BookRepository>();
container.RegisterType<ILibraryRepository, LibraryRepository>(); container.RegisterType<ILibraryRepository, LibraryRepository>();
container.RegisterType<IReaderRepository, ReaderRepository>(); container.RegisterType<IReaderRepository, ReaderRepository>();
container.RegisterType<IOrderRepository, OrderRepository>(); container.RegisterType<IOrderRepository, OrderRepository>();
container.RegisterType<ITicketExtensionsRepository, TicketExtensionsRepository>(); container.RegisterType<ITicketExtensionsRepository, TicketExtensionsRepository>();
container.RegisterType<IConnectionString, ConnectionString>();
return container; return container;
} }
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
}
} }
} }

View File

@ -9,7 +9,18 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.1" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Unity" Version="5.11.10" /> <PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@ -27,4 +38,10 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,6 @@
namespace ProjectLibrary.Repositores;
public interface IConnectionString
{
public string ConnectionString { get; }
}

View File

@ -7,7 +7,6 @@
IEnumerable<Orders> ReadOrders(); IEnumerable<Orders> ReadOrders();
Orders ReadOrderById(int id); Orders ReadOrderById(int id);
void CreateOrder(Orders order); void CreateOrder(Orders order);
void UpdateOrder(Orders order);
void DeleteOrder(int id); void DeleteOrder(int id);
} }
} }

View File

@ -1,35 +1,145 @@
using ProjectLibrary.Entities; using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectLibrary.Entities;
using ProjectLibrary.Entities.Enums; using ProjectLibrary.Entities.Enums;
using ProjectLibrary.Repositories;
using Dapper;
using ProjectLibrary.Repositores; using ProjectLibrary.Repositores;
namespace ProjectLibrary.Repositories.Implementations namespace ProjectLibrary.Repositories.Implementations
{ {
public class BookRepository : IBookRepository public class BookRepository : IBookRepository
{ {
private readonly IConnectionString _connectionString;
private readonly ILogger<BookRepository> _logger;
public BookRepository(IConnectionString connectionString, ILogger<BookRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
// Добавление книги
public void CreateBook(Book book) public void CreateBook(Book book)
{ {
_logger.LogInformation("Добавление книги");
_logger.LogDebug("Книга: {json}", JsonConvert.SerializeObject(book));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Book (Author, Name, TypeBookID)
VALUES (@Author, @Name, @TypeBookID)";
connection.Execute(queryInsert, book);
_logger.LogInformation("Книга успешно добавлена");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении книги");
throw;
}
} }
// Обновление информации о книге
public void UpdateBook(Book book) public void UpdateBook(Book book)
{ {
_logger.LogInformation("Редактирование книги");
_logger.LogDebug("Книга: {json}", JsonConvert.SerializeObject(book));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Book
SET
Author = @Author,
Name = @Name,
TypeBookID = @TypeBookID
WHERE ID = @ID";
connection.Execute(queryUpdate, book);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании книги");
throw;
}
} }
// Удаление книги
public void DeleteBook(int id) public void DeleteBook(int id)
{ {
_logger.LogInformation("Удаление книги с Id={id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Book
WHERE ID = @id";
var affectedRows = connection.Execute(queryDelete, new { id });
if (affectedRows > 0)
{
_logger.LogInformation("Книга с Id={id} успешно удалена", id);
}
else
{
_logger.LogWarning("Книга с Id={id} не найдена для удаления", id);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении книги с Id={id}", id);
throw;
}
} }
// Получение книги по ID
public Book ReadBookById(int id) public Book ReadBookById(int id)
{ {
_logger.LogInformation("Получение книги по Id={id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Book
WHERE ID = @id";
var book = connection.QueryFirstOrDefault<Book>(querySelect, new { id });
return Book.CreateEntity(id, "", "", 0); if (book != null)
{
_logger.LogDebug("Найдена книга: {json}", JsonConvert.SerializeObject(book));
}
else
{
_logger.LogWarning("Книга с Id={id} не найдена", id);
}
return book;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении книги с Id={id}", id);
throw;
}
} }
// Получение всех книг
public IEnumerable<Book> ReadBooks() public IEnumerable<Book> ReadBooks()
{ {
return []; _logger.LogInformation("Получение всех книг");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Book";
var books = connection.Query<Book>(querySelect);
_logger.LogDebug("Полученные книги: {json}", JsonConvert.SerializeObject(books));
return books;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении списка книг");
throw;
}
} }
} }
} }

View File

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectLibrary.Repositores.Implementations;
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=127.0.0.1;Port=5432;Username=postgres;Database=labsofdatabase;Password=3565;";
}

View File

@ -1,33 +1,202 @@
using ProjectLibrary.Entites; using ProjectLibrary.Entities;
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectLibrary.Repositores;
using ProjectLibrary.Entites;
namespace ProjectLibrary.Repositories.Implementations namespace ProjectLibrary.Repositories.Implementations
{ {
public class LibraryRepository : ILibraryRepository public class LibraryRepository : ILibraryRepository
{ {
private readonly IConnectionString _connectionString;
private readonly ILogger<LibraryRepository> _logger;
public LibraryRepository(IConnectionString connectionString, ILogger<LibraryRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateLibrary(Library library) public void CreateLibrary(Library library)
{ {
_logger.LogInformation("Добавление новой библиотеки");
_logger.LogDebug("Библиотека: {json}", JsonConvert.SerializeObject(library));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open(); // открываем соединение
using var transaction = connection.BeginTransaction(); // начинаем транзакцию
var queryInsert = @"
INSERT INTO Library (Name, Address)
VALUES (@Name, @Address);
SELECT MAX(Id) FROM LIBRARY";
var libraryID = connection.QueryFirst<int>(queryInsert, library, transaction); // добавляем в транзакцию запросы,
var querySubInsert = @"INSERT INTO BOOK_LIBRARY (BOOKID, LIBRARYID, COUNT)
VALUES (@BOOKID, @LIBRARYID, @COUNT) ";
foreach (var elem in library.BookLibrary)
{
connection.Execute(querySubInsert, new
{
elem.BookID,
libraryID,
elem.Count
}, transaction); // добавляем в транзакцию запросы, качество параметра
}
transaction.Commit(); // отправляем транзакцию и она выполняет все положенные в неё запросы
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении библиотеки");
throw;
}
} }
public void UpdateLibrary(Library library) public void UpdateLibrary(Library library)
{ {
_logger.LogInformation("Редактирование библиотеки");
_logger.LogDebug("Библиотека: {json}", JsonConvert.SerializeObject(library));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryUpdate = @"
UPDATE Library
SET
Name = @Name,
Address = @Address
WHERE ID = @ID";
connection.Execute(queryUpdate, library, transaction);
var querySubUpdate = @"
UPDATE BOOK_LIBRARY
SET
BOOKID = @BOOKID,
COUNT = @COUNT
WHERE ID = @id";
var querySubInsert = @"INSERT INTO BOOK_LIBRARY (BookID, LibraryID, Count)
VALUES (@BookID, @Id, @Count) ";
int ind = 0;
List<int> listId = connection.Query<int>("Select Id From BOOK_LIBRARY Where LIBRARYID = @id", new { library.Id }).ToList();
foreach (var elem in library.BookLibrary)
{
if (ind > listId.Count-1)
{
connection.Execute(querySubInsert, new
{
elem.BookID,
library.Id,
elem.Count
}, transaction);
continue;
}
int id = listId[ind];
connection.Execute(querySubUpdate, new
{
id,
elem.BookID,
elem.Count
}, transaction);
ind++;
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании библиотеки");
throw;
}
} }
public void DeleteLibrary(int id) public void DeleteLibrary(int id)
{ {
_logger.LogInformation("Удаление библиотеки");
_logger.LogDebug("ID библиотеки: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var querySubDelete = @"
DELETE FROM Book_Library
WHERE LibraryID = @id";
connection.Execute(querySubDelete, new { id }, transaction);
var queryDelete = @"
DELETE FROM Library
WHERE ID = @id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении библиотеки");
throw;
}
} }
public Library ReadLibraryById(int id) public Library ReadLibraryById(int id)
{ {
return Library.CreateEntity(id, "", "", []); _logger.LogInformation("Получение библиотеки по идентификатору");
_logger.LogDebug("ID библиотеки: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Library
WHERE ID = @id";
var library = connection.QueryFirstOrDefault<Library>(querySelect, new { id });
library = Library.CreateEntity(id, library.Name, library.Address, ReadBookLibraryById(id));
_logger.LogDebug("Найденная библиотека: {json}", JsonConvert.SerializeObject(library));
return library;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске библиотеки");
throw;
}
} }
public IEnumerable<Library> ReadLibraries() public IEnumerable<Library> ReadLibraries()
{ {
return []; _logger.LogInformation("Получение всех библиотек");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Library";
var libraries = connection.Query<Library>(querySelect);
_logger.LogDebug("Полученные библиотеки: {json}", JsonConvert.SerializeObject(libraries));
return libraries;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении библиотек");
throw;
}
}
public IEnumerable<Book_Library> ReadBookLibraryById(int id)
{
_logger.LogInformation("Получение всех библиотек");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Book_Library WHERE LibraryID = @id";
var libraries = connection.Query<Book_Library>(querySelect, new { id });
_logger.LogDebug("Полученные библиотеки: {json}", JsonConvert.SerializeObject(libraries));
return libraries;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении библиотек");
throw;
}
} }
} }
} }

View File

@ -1,31 +1,128 @@
using ProjectLibrary.Entites; using ProjectLibrary.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Dapper;
using System.Collections.Generic;
using ProjectLibrary.Repositories;
using System.Transactions;
using System.Data.Common;
using ProjectLibrary.Entites;
using ProjectLibrary.Repositores;
namespace ProjectLibrary.Repositories.Implementations namespace ProjectLibrary.Repositories.Implementations
{ {
public class OrderRepository : IOrderRepository public class OrderRepository : IOrderRepository
{ {
private readonly IConnectionString _connectionString;
private readonly ILogger<OrderRepository> _logger;
public OrderRepository(IConnectionString connectionString, ILogger<OrderRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
// Добавление нового заказа
public void CreateOrder(Orders order) public void CreateOrder(Orders order)
{ {
_logger.LogInformation("Добавление нового заказа");
_logger.LogDebug("Заказ: {json}", JsonConvert.SerializeObject(order));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
} // Вставляем сам заказ в таблицу Orders
public void UpdateOrder(Orders order) var queryInsertOrder = @"
{ INSERT INTO Orders (OrderDate, ReturnDate, ReaderID)
VALUES (@OrderDate, @ReturnDate, @ReaderID);
SELECT MAX(Id) FROM Orders"; // Возвращаем ID вставленного заказа
var orderId = connection.QueryFirst<int>(queryInsertOrder, order, transaction);
// Вставляем ассоциации книг с заказом в таблицу Book_Orders
foreach (var bookId in order.BookOrders) // Предполагается, что Order.BookOrders содержит список ID книг
{
var queryInsertBookOrder = @"
INSERT INTO Book_Orders (BookID, OrderID)
VALUES (@BookID, @OrderID)";
connection.Execute(queryInsertBookOrder, new { bookId.BookID, orderId }, transaction);
}
transaction.Commit();
_logger.LogInformation("Заказ успешно добавлен с ID={OrderId}", orderId);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении заказа");
throw;
}
} }
// Удаление заказа
public void DeleteOrder(int id) public void DeleteOrder(int id)
{ {
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var querySubDelete = @"
DELETE FROM Book_Orders
WHERE OrderId=@id";
connection.Execute(querySubDelete, new { id }, transaction);
var queryDelete = @"
DELETE FROM Orders
WHERE Id=@id";
connection.Execute(queryDelete, new { id }, transaction);
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
} }
// Получение заказа по ID
public Orders ReadOrderById(int id) public Orders ReadOrderById(int id)
{ {
return Orders.CreateEntity(0, DateTime.Now, DateTime.Now, 0, []); _logger.LogInformation("Получение заказа по ID={id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelectOrder = "SELECT * FROM Orders WHERE ID = @id";
var order = connection.QueryFirstOrDefault<Orders>(querySelectOrder, new { id });
_logger.LogDebug("Найден заказ: {json}", JsonConvert.SerializeObject(order));
return order;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении заказа с ID={id}", id);
throw;
}
} }
// Получение всех заказов
public IEnumerable<Orders> ReadOrders() public IEnumerable<Orders> ReadOrders()
{ {
return [] ; _logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT * FROM Orders";
var order = connection.Query<Orders>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(order));
return order;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
} }
} }
} }

View File

@ -1,31 +1,159 @@
using ProjectLibrary.Entities; using ProjectLibrary.Entities;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Dapper;
using System.Collections.Generic;
using ProjectLibrary.Repositores;
namespace ProjectLibrary.Repositories namespace ProjectLibrary.Repositories
{ {
public class ReaderRepository : IReaderRepository public class ReaderRepository : IReaderRepository
{ {
private readonly IConnectionString _connectionString;
private readonly ILogger<ReaderRepository> _logger;
public ReaderRepository(IConnectionString connectionString, ILogger<ReaderRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
// Добавление нового читателя
public void CreateReader(Reader reader) public void CreateReader(Reader reader)
{ {
_logger.LogInformation("Добавление читателя");
_logger.LogDebug("Читатель: {json}", JsonConvert.SerializeObject(reader));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Reader (Name, ReaderTicket, RegistrationDateRT) -- Используем правильные названия столбцов из вашей таблицы
VALUES (@Name, @ReaderTicket, @RegistrationDateRT)";
connection.Execute(queryInsert, reader);
_logger.LogInformation("Читатель успешно добавлен");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении читателя");
throw;
}
} }
// Обновление информации о читателе
public void UpdateReader(Reader reader) public void UpdateReader(Reader reader)
{ {
_logger.LogInformation("Редактирование читателя");
_logger.LogDebug("Читатель: {json}", JsonConvert.SerializeObject(reader));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Reader -- Используем правильное имя таблицы
SET
Name = @Name, -- Используем правильные названия столбцов
ReaderTicket = @ReaderTicket,
RegistrationDateRT = @RegistrationDateRT
WHERE ID = @ID";
var affectedRows = connection.Execute(queryUpdate, new
{
Name = reader.Name,
ReaderTicket = reader.ReaderTicket,
RegistrationDateRT = reader.RegistrationDateRT,
ID = reader.Id
});
if (affectedRows > 0)
{
_logger.LogInformation("Читатель успешно обновлен");
}
else
{
_logger.LogWarning("Читатель с ID={Id} не найден для обновления", reader.Id);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании читателя");
throw;
}
} }
// Удаление читателя
public void DeleteReader(int id) public void DeleteReader(int id)
{ {
_logger.LogInformation("Удаление читателя с ID={id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Reader -- Используем правильное имя таблицы
WHERE ID = @id";
var affectedRows = connection.Execute(queryDelete, new { id });
if (affectedRows > 0)
{
_logger.LogInformation("Читатель с ID={id} успешно удален", id);
}
else
{
_logger.LogWarning("Читатель с ID={id} не найден для удаления", id);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении читателя с ID={id}", id);
throw;
}
} }
// Получение читателя по ID
public Reader ReadReaderById(int id) public Reader ReadReaderById(int id)
{ {
return Reader.CreateEntity(id, "", 0); _logger.LogInformation("Получение читателя по ID={id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Reader -- Используем правильное имя таблицы
WHERE ID = @id";
var reader = connection.QueryFirstOrDefault<Reader>(querySelect, new { id });
if (reader != null)
{
_logger.LogDebug("Найден читатель: {json}", JsonConvert.SerializeObject(reader));
}
else
{
_logger.LogWarning("Читатель с ID={id} не найден", id);
}
return reader;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске читателя");
throw;
}
} }
// Получение всех читателей
public List<Reader> ReadReaders() public List<Reader> ReadReaders()
{ {
return []; _logger.LogInformation("Получение всех читателей");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Reader"; // Используем правильное имя таблицы
var readers = connection.Query<Reader>(querySelect).ToList();
_logger.LogDebug("Полученные читатели: {json}", JsonConvert.SerializeObject(readers));
return readers;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении списка читателей");
throw;
}
} }
} }
} }

View File

@ -1,25 +1,128 @@
using ProjectLibrary.Entites; using ProjectLibrary.Entities;
using ProjectLibrary.Repositories;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using ProjectLibrary.Entites;
using ProjectLibrary.Repositores; using ProjectLibrary.Repositores;
public class TicketExtensionsRepository : ITicketExtensionsRepository namespace ProjectLibrary.Repositories.Implementations
{ {
public void CreateTicketExtension(TicketExtensions ticketExtension) public class TicketExtensionsRepository : ITicketExtensionsRepository
{ {
private readonly IConnectionString _connectionString;
private readonly ILogger<TicketExtensionsRepository> _logger;
} public TicketExtensionsRepository(IConnectionString connectionString, ILogger<TicketExtensionsRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void UpdateTicketExtension(TicketExtensions ticketExtension) // Создание новой записи о продлении билета
{ public void CreateTicketExtension(TicketExtensions ticketExtension)
{
_logger.LogInformation("Добавление нового продления билета для читателя с ID={ReaderID}", ticketExtension.ReaderID);
_logger.LogDebug("Данные продления: {json}", JsonConvert.SerializeObject(ticketExtension));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
} var queryInsert = @"
INSERT INTO Ticket_Extensions (ReaderID, LastUpdateDate, NextUpdateDate)
VALUES (@ReaderID, @LastUpdateDate, @NextUpdateDate)";
connection.Execute(queryInsert, ticketExtension);
public TicketExtensions ReadTicketExtensionById(int id) _logger.LogInformation("Продление билета успешно добавлено для читателя с ID={ReaderID}", ticketExtension.ReaderID);
{ }
return TicketExtensions.CreateEntity(0, DateTime.Now, DateTime.Now); catch (Exception ex)
} {
_logger.LogError(ex, "Ошибка при добавлении продления билета");
throw;
}
}
public List<TicketExtensions> ReadTicketExtensions() // Обновление информации о продлении билета
{ public void UpdateTicketExtension(TicketExtensions ticketExtension)
return []; {
_logger.LogInformation("Редактирование продления билета для читателя с ID={ReaderID}", ticketExtension.ReaderID);
_logger.LogDebug("Данные продления: {json}", JsonConvert.SerializeObject(ticketExtension));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Ticket_Extensions
SET LastUpdateDate = @LastUpdateDate, NextUpdateDate = @NextUpdateDate
WHERE ReaderID = @ReaderID";
var affectedRows = connection.Execute(queryUpdate, ticketExtension);
if (affectedRows > 0)
{
_logger.LogInformation("Продление билета успешно обновлено для читателя с ID={ReaderID}", ticketExtension.ReaderID);
}
else
{
_logger.LogWarning("Продление билета для читателя с ID={ReaderID} не найдено для обновления", ticketExtension.ReaderID);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании продления билета");
throw;
}
}
// Получение продления билета по ID читателя
public TicketExtensions ReadTicketExtensionById(int readerId)
{
_logger.LogInformation("Получение продления билета для читателя с ID={readerId}", readerId);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Ticket_Extensions WHERE ReaderID = @readerId";
var ticketExtension = connection.QueryFirstOrDefault<TicketExtensions>(querySelect, new { readerId });
if (ticketExtension != null)
{
_logger.LogDebug("Найдено продление билета: {json}", JsonConvert.SerializeObject(ticketExtension));
}
else
{
_logger.LogWarning("Продление билета для читателя с ID={readerId} не найдено", readerId);
}
return ticketExtension;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении продления билета с ID={readerId}", readerId);
throw;
}
}
// Получение всех продлений билетов
public List<TicketExtensions> ReadTicketExtensions()
{
_logger.LogInformation("Получение всех продлений билетов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Ticket_Extensions";
var ticketExtensions = connection.Query<TicketExtensions>(querySelect).ToList();
_logger.LogDebug("Полученные продления билетов: {json}", JsonConvert.SerializeObject(ticketExtensions));
return ticketExtensions;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении списка продлений билетов");
throw;
}
}
} }
} }

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs.txt",
"rollingInterval": "Day"
}
}
]
}
}