Eliseev E.E. LabWork07_Hard #17

Closed
ElEgEv wants to merge 26 commits from LabWork07_Hard into LabWork06_Hard
58 changed files with 4215 additions and 40 deletions

1
.gitignore vendored
View File

@ -398,3 +398,4 @@ FodyWeavers.xsd
# JetBrains Rider
*.sln.iml
/BlacksmithWorkshop/ImplementationExtensions

View File

@ -15,13 +15,19 @@ namespace BlacksmithWorkshopRestApi.Controllers
private readonly IClientLogic _logic;
public ClientController(IClientLogic logic, ILogger<ClientController> logger)
{
_logger = logger;
_logic = logic;
}
private readonly IMessageInfoLogic _mailLogic;
[HttpGet]
public int pageSize = 3;
public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger<ClientController> logger)
{
_logger = logger;
_logic = logic;
_mailLogic = mailLogic;
}
[HttpGet]
public ClientViewModel? Login(string login, string password)
{
try
@ -69,5 +75,24 @@ namespace BlacksmithWorkshopRestApi.Controllers
throw;
}
}
}
[HttpGet]
public List<MessageInfoViewModel>? GetMessages(int clientId, int page)
{
try
{
return _mailLogic.ReadList(new MessageInfoSearchModel
{
ClientId = clientId,
Page = page,
PageSize = pageSize
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения писем клиента");
throw;
}
}
}
}

View File

@ -1,4 +1,6 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopBusinessLogic.MailWorker;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopDatabaseImplement.Implements;
@ -15,11 +17,17 @@ builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IManufactureStorage, ManufactureStorage>();
builder.Services.AddTransient<IShopStorage, ShopStorage>();
builder.Services.AddTransient<IImplementerStorage, ImplementerStorage>();
builder.Services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IManufactureLogic, ManufactureLogic>();
builder.Services.AddTransient<IShopLogic, ShopLogic>();
builder.Services.AddTransient<IImplementerLogic, ImplementerLogic>();
builder.Services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers();
@ -34,6 +42,18 @@ builder.Services.AddSwaggerGen(c =>
var app = builder.Build();
var mailSender = app.Services.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty,
MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty,
SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty,
SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()),
PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty,
PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString())
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{

View File

@ -5,5 +5,12 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "uveselchak99@gmail.com",
"MailPassword": "nqkv jzzq fryi leao"
}

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SmtpClientHost" value="smtp.gmail.com" />
<add key="SmtpClientPort" value="587" />
<add key="PopHost" value="pop.gmail.com" />
<add key="PopPort" value="995" />
<add key="MailLogin" value="uveselchak99@gmail.com" />
<add key="MailPassword" value="nqkv jzzq fryi leao" />
</appSettings>
</configuration>

View File

@ -27,4 +27,10 @@
<ProjectReference Include="..\BlacksmithWorkshopListImplement\BlacksmithWorkshopListImplement.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="App.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,140 @@
namespace BlacksmithWorkshop
{
partial class FormAnswerMail
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonSave = new Button();
buttonCancel = new Button();
textBoxHead = new TextBox();
textBoxBody = new TextBox();
labelHead = new Label();
labelBody = new Label();
labelAnswer = new Label();
textBoxAnswer = new TextBox();
SuspendLayout();
//
// buttonSave
//
buttonSave.Location = new Point(203, 227);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(125, 29);
buttonSave.TabIndex = 0;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(350, 227);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(123, 29);
buttonCancel.TabIndex = 1;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// textBoxHead
//
textBoxHead.Location = new Point(151, 34);
textBoxHead.Name = "textBoxHead";
textBoxHead.Size = new Size(322, 27);
textBoxHead.TabIndex = 2;
//
// textBoxBody
//
textBoxBody.Location = new Point(151, 98);
textBoxBody.Name = "textBoxBody";
textBoxBody.Size = new Size(322, 27);
textBoxBody.TabIndex = 3;
//
// labelHead
//
labelHead.AutoSize = true;
labelHead.Location = new Point(30, 37);
labelHead.Name = "labelHead";
labelHead.Size = new Size(84, 20);
labelHead.TabIndex = 4;
labelHead.Text = "Заголовок:";
//
// labelBody
//
labelBody.AutoSize = true;
labelBody.Location = new Point(30, 101);
labelBody.Name = "labelBody";
labelBody.Size = new Size(94, 20);
labelBody.TabIndex = 5;
labelBody.Text = "Сообщение:";
//
// labelAnswer
//
labelAnswer.AutoSize = true;
labelAnswer.Location = new Point(30, 163);
labelAnswer.Name = "labelAnswer";
labelAnswer.Size = new Size(51, 20);
labelAnswer.TabIndex = 6;
labelAnswer.Text = "Ответ:";
//
// textBoxAnswer
//
textBoxAnswer.Location = new Point(151, 160);
textBoxAnswer.Name = "textBoxAnswer";
textBoxAnswer.Size = new Size(322, 27);
textBoxAnswer.TabIndex = 7;
//
// FormAnswerMail
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(512, 284);
Controls.Add(textBoxAnswer);
Controls.Add(labelAnswer);
Controls.Add(labelBody);
Controls.Add(labelHead);
Controls.Add(textBoxBody);
Controls.Add(textBoxHead);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Name = "FormAnswerMail";
Text = "Просмотр письма";
Load += FormAnswerMail_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSave;
private Button buttonCancel;
private TextBox textBoxHead;
private TextBox textBoxBody;
private Label labelHead;
private Label labelBody;
private Label labelAnswer;
private TextBox textBoxAnswer;
}
}

View File

@ -0,0 +1,98 @@
using BlacksmithWorkshopBusinessLogic.MailWorker;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BlacksmithWorkshop
{
public partial class FormAnswerMail : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic;
private readonly AbstractMailWorker _mailWorker;
private MessageInfoViewModel _message;
public string MessageId { get; set; } = string.Empty;
public FormAnswerMail(ILogger<FormAnswerMail> logger, AbstractMailWorker mailWorker, IMessageInfoLogic logic)
{
InitializeComponent();
_logger = logger;
_mailWorker = mailWorker;
_logic = logic;
}
private void FormAnswerMail_Load(object sender, EventArgs e)
{
try
{
_logger.LogInformation("Получение письма");
_message = _logic.ReadElement(new MessageInfoSearchModel { MessageId = MessageId });
if (_message != null)
{
Text += $"для {_message.SenderName}";
textBoxHead.Text = _message.Subject;
textBoxBody.Text = _message.Body;
}
if (_message.IsRead is false)
{
_logic.Update(new() { MessageId = MessageId, IsRead = true, Answer = _message.Answer });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения письма");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
//отправка письма с ответом
_mailWorker.MailSendAsync(new()
{
MailAddress = _message.SenderName,
Subject = _message.Subject,
Text = textBoxAnswer.Text,
});
_logic.Update(new()
{
MessageId = MessageId,
Answer = textBoxAnswer.Text,
IsRead = true,
});
MessageBox.Show("Успешная отправка письма", "Отправка письма", MessageBoxButtons.OK);
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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

@ -0,0 +1,101 @@
namespace BlacksmithWorkshop
{
partial class FormMails
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
buttonForward = new Button();
buttonBack = new Button();
buttonAnswer = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(781, 393);
dataGridView.TabIndex = 0;
//
// buttonForward
//
buttonForward.Location = new Point(155, 416);
buttonForward.Name = "buttonForward";
buttonForward.Size = new Size(175, 29);
buttonForward.TabIndex = 1;
buttonForward.Text = "Вперёд";
buttonForward.UseVisualStyleBackColor = true;
buttonForward.Click += ButtonForward_Click;
//
// buttonBack
//
buttonBack.Location = new Point(468, 416);
buttonBack.Name = "buttonBack";
buttonBack.Size = new Size(173, 29);
buttonBack.TabIndex = 2;
buttonBack.Text = "Назад";
buttonBack.UseVisualStyleBackColor = true;
buttonBack.Click += ButtonBack_Click;
//
// buttonAnswer
//
buttonAnswer.Location = new Point(806, 34);
buttonAnswer.Name = "buttonAnswer";
buttonAnswer.Size = new Size(136, 29);
buttonAnswer.TabIndex = 3;
buttonAnswer.Text = "Ответить";
buttonAnswer.UseVisualStyleBackColor = true;
buttonAnswer.Click += ButtonAnswer_Click;
//
// FormMails
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(963, 457);
Controls.Add(buttonAnswer);
Controls.Add(buttonBack);
Controls.Add(buttonForward);
Controls.Add(dataGridView);
Name = "FormMails";
Text = "Письма";
Load += FormMails_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonForward;
private Button buttonBack;
private Button buttonAnswer;
}
}

View File

@ -0,0 +1,134 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogic;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BlacksmithWorkshop
{
public partial class FormMails : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _messageLogic;
private int currentPage = 1;
public int pageSize = 5;
public FormMails(ILogger<FormMails> logger, IMessageInfoLogic messageLogic)
{
InitializeComponent();
_logger = logger;
_messageLogic = messageLogic;
buttonBack.Enabled = false;
}
private void FormMails_Load(object sender, EventArgs e)
{
LoadData();
}
private bool LoadData()
{
_logger.LogInformation("Загрузка писем");
try
{
var list = _messageLogic.ReadList(new()
{
Page = currentPage,
PageSize = pageSize,
});
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["MessageId"].Visible = false;
dataGridView.Columns["Body"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка списка писем");
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки писем");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private void ButtonForward_Click(object sender, EventArgs e)
{
currentPage++;
if (!LoadData() || ((List<MessageInfoViewModel>)dataGridView.DataSource).Count == 0)
{
_logger.LogWarning("Обращение к несуществующему письму");
currentPage--;
LoadData();
buttonForward.Enabled = false;
}
else
{
buttonBack.Enabled = true;
}
}
private void ButtonBack_Click(object sender, EventArgs e)
{
if (currentPage == 1)
{
_logger.LogWarning("Неккоректный номер страницы {page}", currentPage - 1);
return;
}
currentPage--;
if (LoadData())
{
buttonForward.Enabled = true;
if (currentPage == 1)
{
buttonBack.Enabled = false;
}
}
}
private void ButtonAnswer_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormAnswerMail));
if (service is FormAnswerMail form)
{
form.MessageId = dataGridView.SelectedRows[0].Cells["MessageId"].Value.ToString();
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<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

@ -51,6 +51,7 @@
clientsToolStripMenuItem = new ToolStripMenuItem();
startWorkToolStripMenuItem = new ToolStripMenuItem();
buttonSellManufacture = new Button();
messageToolStripMenuItem = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
@ -206,7 +207,7 @@
//
// работаСКлиентамиToolStripMenuItem
//
работаСКлиентамиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { clientsToolStripMenuItem });
работаСКлиентамиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { clientsToolStripMenuItem, messageToolStripMenuItem });
работаСКлиентамиToolStripMenuItem.Name = "работаСКлиентамиToolStripMenuItem";
работаСКлиентамиToolStripMenuItem.Size = new Size(161, 24);
работаСКлиентамиToolStripMenuItem.Text = "Работа с клиентами";
@ -235,6 +236,13 @@
buttonSellManufacture.UseVisualStyleBackColor = true;
buttonSellManufacture.Click += ButtonSellManufacture_Click;
//
// messageToolStripMenuItem
//
messageToolStripMenuItem.Name = "messageToolStripMenuItem";
messageToolStripMenuItem.Size = new Size(224, 26);
messageToolStripMenuItem.Text = "Письма";
messageToolStripMenuItem.Click += MessageToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -282,5 +290,6 @@
private ToolStripMenuItem работаСКлиентамиToolStripMenuItem;
private ToolStripMenuItem clientsToolStripMenuItem;
private ToolStripMenuItem startWorkToolStripMenuItem;
private ToolStripMenuItem messageToolStripMenuItem;
}
}

View File

@ -259,5 +259,15 @@ namespace BlacksmithWorkshop
form.ShowDialog();
}
}
private void MessageToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormMails));
if (service is FormMails form)
{
form.ShowDialog();
}
}
}
}

View File

@ -7,6 +7,8 @@ using BlacksmithWorkshopDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using BlacksmithWorkshopBusinessLogic.MailWorker;
using BlacksmithWorkshopContracts.BindingModels;
namespace BlacksmithWorkshop
{
@ -28,7 +30,32 @@ namespace BlacksmithWorkshop
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
try
{
var mailSender = _serviceProvider.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]),
PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty,
PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"])
});
// ñîçäàåì òàéìåð
var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000);
}
catch (Exception ex)
{
var logger = _serviceProvider.GetService<ILogger>();
logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
}
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
@ -45,6 +72,7 @@ namespace BlacksmithWorkshop
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IWorkPieceLogic, WorkPieceLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
@ -53,8 +81,10 @@ namespace BlacksmithWorkshop
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
@ -78,6 +108,10 @@ namespace BlacksmithWorkshop
services.AddTransient<FormClients>();
services.AddTransient<FormImplementers>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormMails>();
services.AddTransient<FormAnswerMail>();
}
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
}
}

View File

@ -8,6 +8,7 @@
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="MailKit" Version="4.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="MigraDocCore.DocumentObjectModel" Version="1.3.49" />
<PackageReference Include="MigraDocCore.Rendering" Version="1.3.49" />

View File

@ -8,6 +8,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
@ -141,6 +142,16 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
throw new ArgumentNullException("Отсутствие пароля в учётной записи", nameof(model.Password));
}
if (!Regex.IsMatch(model.Email, @"^[a-zA-Z0-9.!#$%&*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$", RegexOptions.IgnoreCase))
{
throw new ArgumentException("Некорректная почта", nameof(model.Email));
}
if (!Regex.IsMatch(model.Password, @"^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))[\w\d\W]*$", RegexOptions.IgnoreCase) && model.Password.Length < 10 && model.Password.Length > 50)
{
throw new ArgumentException("Необходимо придумать другой пароль", nameof(model.Password));
}
_logger.LogInformation("Client. ClientFIO:{ClientFIO}. Email:{Email}. Password:{Password}. Id:{Id}",
model.ClientFIO, model.Email, model.Password, model.Id);

View File

@ -0,0 +1,92 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
{
public class MessageInfoLogic : IMessageInfoLogic
{
private readonly ILogger _logger;
private readonly IMessageInfoStorage _messageInfoStorage;
public MessageInfoLogic(ILogger<MessageInfoLogic> logger, IMessageInfoStorage messageInfoStorage)
{
_logger = logger;
_messageInfoStorage = messageInfoStorage;
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
{
_logger.LogInformation("ReadList. MessageId:{MessageId}", model?.MessageId);
//list хранит весь список в случае, если model пришло со значением null на вход метода
var list = model == null ? _messageInfoStorage.GetFullList() : _messageInfoStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
MessageInfoViewModel? IMessageInfoLogic.ReadElement(MessageInfoSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadList. ClientId:{ClientId}. MessageId:{MessageId}", model.ClientId, model?.MessageId);
var element = _messageInfoStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.MessageId);
return element;
}
public bool Create(MessageInfoBindingModel model)
{
if (_messageInfoStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(MessageInfoBindingModel model)
{
if (_messageInfoStorage.Update(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
}
}

View File

@ -1,4 +1,5 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopBusinessLogic.MailWorker;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
@ -24,16 +25,22 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
private readonly IManufactureStorage _manufactureStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic, IManufactureStorage manufactureStorage)
private readonly IClientLogic _clientLogic;
private readonly AbstractMailWorker _mailWorker;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopLogic shopLogic, IManufactureStorage manufactureStorage, IClientLogic clientLogic, AbstractMailWorker mailWorker)
{
_logger = logger;
_orderStorage = orderStorage;
_shopLogic = shopLogic;
_manufactureStorage = manufactureStorage;
_clientLogic = clientLogic;
_mailWorker = mailWorker;
}
//вывод отфильтрованного списка компонентов
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
//вывод отфильтрованного списка компонентов
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Id:{Id}", model?.Id);
@ -88,13 +95,17 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
model.Status = OrderStatus.Принят;
if(_orderStorage.Insert(model) == null)
var result = _orderStorage.Insert(model);
if (result == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
SendOrderMessage(result.ClientId, $"Кузнечная мастерская, Заказ №{result.Id}", $"Заказ №{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят");
return true;
}
@ -213,15 +224,38 @@ namespace BlacksmithWorkshopBusinessLogic.BusinessLogic
CheckModel(model, false);
//финальная проверка на возможность обновления
if (_orderStorage.Update(model) == null)
var result = _orderStorage.Update(model);
//финальная проверка на возможность обновления
if (result == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
SendOrderMessage(result.ClientId, $"Кузнечаня мастерская, Заказ №{result.Id}", $"Заказ №{model.Id} изменен статус на {result.Status}");
return true;
}
private bool SendOrderMessage(int clientId, string subject, string text)
{
var client = _clientLogic.ReadElement(new() { Id = clientId });
if (client == null)
{
return false;
}
_mailWorker.MailSendAsync(new()
{
MailAddress = client.Email,
Subject = subject,
Text = text
});
return true;
}
}
}

View File

@ -0,0 +1,107 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.MailWorker
{
public abstract class AbstractMailWorker
{
protected string _mailLogin = string.Empty;
protected string _mailPassword = string.Empty;
protected string _smtpClientHost = string.Empty;
protected int _smtpClientPort;
protected string _popHost = string.Empty;
protected int _popPort;
private readonly IMessageInfoLogic _messageInfoLogic;
private readonly IClientLogic _clientLogic;
private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic)
{
_logger = logger;
_messageInfoLogic = messageInfoLogic;
_clientLogic = clientLogic;
}
public void MailConfig(MailConfigBindingModel config)
{
_mailLogin = config.MailLogin;
_mailPassword = config.MailPassword;
_smtpClientHost = config.SmtpClientHost;
_smtpClientPort = config.SmtpClientPort;
_popHost = config.PopHost;
_popPort = config.PopPort;
_logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, { popHost}, { popPort}",
_mailLogin, _mailPassword, _smtpClientHost, _smtpClientPort, _popHost, _popPort);
}
public async void MailSendAsync(MailSendInfoBindingModel info)
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{
return;
}
if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
{
return;
}
if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text))
{
return;
}
_logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject);
await SendMailAsync(info);
}
public async void MailCheck()
{
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{
return;
}
if (string.IsNullOrEmpty(_popHost) || _popPort == 0)
{
return;
}
if (_messageInfoLogic == null)
{
return;
}
var list = await ReceiveMailAsync();
_logger.LogDebug("Check Mail: {Count} new mails", list.Count);
foreach (var mail in list)
{
mail.ClientId = _clientLogic.ReadElement(new() { Email = mail.SenderName })?.Id;
_messageInfoLogic.Create(mail);
}
}
protected abstract Task SendMailAsync(MailSendInfoBindingModel info);
protected abstract Task<List<MessageInfoBindingModel>> ReceiveMailAsync();
}
}

View File

@ -0,0 +1,91 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using MailKit.Net.Pop3;
using MailKit.Security;
namespace BlacksmithWorkshopBusinessLogic.MailWorker
{
public class MailKitWorker : AbstractMailWorker
{
public MailKitWorker(ILogger<MailKitWorker> logger, IMessageInfoLogic messageInfoLogic, IClientLogic clientLogic)
: base(logger, messageInfoLogic, clientLogic) { }
protected override async Task SendMailAsync(MailSendInfoBindingModel info)
{
using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
try
{
objMailMessage.From = new MailAddress(_mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text;
objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8;
objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
await Task.Run(() => objSmtpClient.Send(objMailMessage));
}
catch (Exception)
{
throw;
}
}
protected override async Task<List<MessageInfoBindingModel>> ReceiveMailAsync()
{
var list = new List<MessageInfoBindingModel>();
using var client = new Pop3Client();
await Task.Run(() =>
{
try
{
client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect);
client.Authenticate(_mailLogin, _mailPassword);
for (int i = 0; i < client.Count; i++)
{
var message = client.GetMessage(i);
foreach (var mail in message.From.Mailboxes)
{
list.Add(new MessageInfoBindingModel
{
DateDelivery = message.Date.DateTime,
MessageId = message.MessageId,
SenderName = mail.Address,
Subject = message.Subject,
Body = message.TextBody
});
}
}
}
catch (AuthenticationException)
{ }
finally
{
client.Disconnect(true);
}
});
return list;
}
}
}

View File

@ -13,6 +13,9 @@ namespace BlacksmithWorkshopClientApp
//поле, хранящее клиента, которого необходимо авторизовать
public static ClientViewModel? Client { get; set; } = null;
//для пагинации
public static int CurrentPage { get; set; } = 0;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);

View File

@ -3,6 +3,7 @@ using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Text;
namespace BlacksmithWorkshopClientApp.Controllers
{
@ -169,10 +170,64 @@ namespace BlacksmithWorkshopClientApp.Controllers
[HttpPost]
public double Calc(int count, int manufacture)
{
var manuf =APIClient.GetRequest<ManufactureViewModel>($"api/main/getmanufacture?manufactureId={manufacture}"
);
var manuf =APIClient.GetRequest<ManufactureViewModel>($"api/main/getmanufacture?manufactureId={manufacture}");
return count * (manuf?.Price ?? 1);
}
}
//для работы с письмами
[HttpGet]
public IActionResult Mails()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
//Возвращает кортеж с таблицой в html, текущей страницей писем, выключать ли кнопку пред. страницы, выключать ли кнопку след. страницы
[HttpGet]
public Tuple<string?, string?, bool, bool>? SwitchPage(bool isNext)
{
if (isNext)
{
APIClient.CurrentPage++;
}
else
{
if (APIClient.CurrentPage == 1)
{
return null;
}
APIClient.CurrentPage--;
}
var res = APIClient.GetRequest<List<MessageInfoViewModel>>($"api/client/getmessages?clientId={APIClient.Client!.Id}&page={APIClient.CurrentPage}");
if (isNext && (res == null || res.Count == 0))
{
APIClient.CurrentPage--;
return Tuple.Create<string?, string?, bool, bool>(null, null, APIClient.CurrentPage != 1, false);
}
StringBuilder htmlTable = new();
foreach (var mail in res)
{
htmlTable.Append("<tr>" +
$"<td>{mail.DateDelivery}</td>" +
$"<td>{mail.Subject}</td>" +
$"<td>{mail.Body}</td>" +
"<td>" + (mail.IsRead ? "Прочитано" : "Непрочитано") + "</td>" +
$"<td>{mail.Answer}</td>" +
"</tr>");
}
return Tuple.Create<string?, string?, bool, bool>(htmlTable.ToString(), APIClient.CurrentPage.ToString(), APIClient.CurrentPage != 1, true);
}
}
}

View File

@ -9,7 +9,7 @@
<div class="row">
<div class="col-4">Логин:</div>
<div class="col-8">
<input type="text" name="login" /
<input type="text" name="login" />
</div>
</div>
<div class="row">

View File

@ -0,0 +1,83 @@
@{
ViewData["Title"] = "Mails";
}
<div class="text-center">
<h1 class="display-4">Письма</h1>
</div>
<div class="text-center">
<table class="table">
<thead>
<tr>
<th>
Дата письма
</th>
<th>
Заголовок
</th>
<th>
Текст
</th>
<th>
Статус
</th>
<th>
Ответ
</th>
</tr>
</thead>
<tbody id="mails-table-body">
</tbody>
</table>
<ul class="pagination justify-content-center">
<li id="prev-page" class="page-item">
<a class="page-link" href="#" aria-label="Previous">
<span aria-hidden="true">&laquo;</span>
<span class="sr-only">Предыдущая</span>
</a>
</li>
<li class="page-item">
<a id="current-page" class="page-link"></a>
</li>
<li id="next-page" class="page-item">
<a class="page-link" href="#" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
<span class="sr-only">Следующая</span>
</a>
</li>
</ul>
</div>
<script>
function onClicked(isNext) {
$.ajax({
method: "GET",
url: "/Home/SwitchPage",
data: { isNext: isNext },
success: function (result) {
if (result != null) {
if (result.item1 != null && result.item2 != null) {
$("#mails-table-body").html(result.item1);
$("#current-page").text(result.item2);
}
if (result.item3)
$("#prev-page").removeClass("page-item disabled");
else
$("#prev-page").addClass("page-item disabled");
if (result.item4)
$("#next-page").removeClass("page-item disabled");
else
$("#next-page").addClass("page-item disabled");
}
}
});
}
// Чтобы в первый раз загрузить данные и попасть на первую страницу
onClicked(true);
$("#prev-page").on('click', () => onClicked(false));
$("#next-page").on('click', () => onClicked(true));
</script>

View File

@ -6,8 +6,10 @@
<title>@ViewData["Title"] - BlacksmithWorkshopClientApp</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
<link rel="stylesheet" href="~/BlacksmithWorkshopClientApp.styles.css" asp-append-version="true" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</head>
<body>
<header>
@ -28,6 +30,9 @@
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Mails">Письма</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asparea="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>
@ -50,9 +55,6 @@
&copy; 2023 - BlacksmithWorkshopClientApp - <a asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BindingModels
{
//один из двух классов для передачи данных по почте
public class MailConfigBindingModel
{
public string MailLogin { get; set; } = string.Empty;
public string MailPassword { get; set; } = string.Empty;
public string SmtpClientHost { get; set; } = string.Empty;
public int SmtpClientPort { get; set; }
public string PopHost { get; set; } = string.Empty;
public int PopPort { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BindingModels
{
//один из двух классов для обмена информацией по почте
public class MailSendInfoBindingModel
{
public string MailAddress { get; set; } = string.Empty;
public string Subject { get; set; } = string.Empty;
public string Text { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,28 @@
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BindingModels
{
public class MessageInfoBindingModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
public string SenderName { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; } = DateTime.Now;
public string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public bool IsRead { get; set; } = false;
public string? Answer { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,22 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BusinessLogicsContracts
{
public interface IMessageInfoLogic
{
List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model);
MessageInfoViewModel? ReadElement(MessageInfoSearchModel model);
bool Create(MessageInfoBindingModel model);
bool Update(MessageInfoBindingModel model);
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.SearchModels
{
public class MessageInfoSearchModel
{
public string? MessageId { get; set; }
public int? ClientId { get; set; }
public int? Page { get; set; }
public int? PageSize { get; set; }
}
}

View File

@ -0,0 +1,24 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.StoragesContracts
{
public interface IMessageInfoStorage
{
List<MessageInfoViewModel> GetFullList();
List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model);
MessageInfoViewModel? GetElement(MessageInfoSearchModel model);
MessageInfoViewModel? Insert(MessageInfoBindingModel model);
MessageInfoViewModel? Update(MessageInfoBindingModel model);
}
}

View File

@ -0,0 +1,35 @@
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.ViewModels
{
public class MessageInfoViewModel : IMessageInfoModel
{
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
[DisplayName("Отправитель")]
public string SenderName { get; set; } = string.Empty;
[DisplayName("Дата отправки")]
public DateTime DateDelivery { get; set; } = DateTime.Now;
[DisplayName("Заголовок")]
public string Subject { get; set; } = string.Empty;
[DisplayName("Текст")]
public string Body { get; set; } = string.Empty;
[DisplayName("Прочитано")]
public bool IsRead { get; set; } = false;
[DisplayName("Ответ")]
public string? Answer { get; set; }
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDataModels.Models
{
public interface IMessageInfoModel
{
string MessageId { get; }
int? ClientId { get; }
string SenderName { get; }
DateTime DateDelivery { get; }
string Subject { get; }
string Body { get; }
public bool IsRead { get; }
public string Answer { get; }
}
}

View File

@ -36,5 +36,7 @@ namespace BlacksmithWorkshopDatabaseImplement
public virtual DbSet<Client> Clients { get; set; }
public virtual DbSet<Implementer> Implementers { set; get; }
public virtual DbSet<MessageInfo> Messages { set; get; }
}
}

View File

@ -46,10 +46,11 @@ namespace BlacksmithWorkshopDatabaseImplement.Implements
{
return context.Clients
.Include(x => x.Orders)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
else if (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Password))
if (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Password))
{
return context.Clients
.Include(x => x.Orders)
@ -57,7 +58,12 @@ namespace BlacksmithWorkshopDatabaseImplement.Implements
?.GetViewModel;
}
return new();
if (!string.IsNullOrEmpty(model.Email))
return context.Clients
.FirstOrDefault(x => x.Email == model.Email)
?.GetViewModel;
return null;
}
public List<ClientViewModel> GetFilteredList(ClientSearchModel model)

View File

@ -0,0 +1,102 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (string.IsNullOrEmpty(model.MessageId))
{
return null;
}
using var context = new BlacksmithWorkshopDatabase();
return context.Messages
.FirstOrDefault(x => (x.MessageId.Equals(model.MessageId)))
?.GetViewModel;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
using var context = new BlacksmithWorkshopDatabase();
var list = new List<MessageInfoViewModel>();
if (model.ClientId.HasValue)
{
list = context.Messages
.Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId)
.Select(x => x.GetViewModel).ToList();
}
else
{
list = context.Messages
.Select(x => x.GetViewModel).ToList();
}
if (!(model.Page.HasValue && model.PageSize.HasValue))
{
return list.ToList();
}
return list.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList();
}
public List<MessageInfoViewModel> GetFullList()
{
using var context = new BlacksmithWorkshopDatabase();
return context.Messages
.Select(x => x.GetViewModel)
.ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
using var context = new BlacksmithWorkshopDatabase();
var newMessage = MessageInfo.Create(model);
if (newMessage == null)
{
return null;
}
context.Messages.Add(newMessage);
context.SaveChanges();
return newMessage.GetViewModel;
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
using var context = new BlacksmithWorkshopDatabase();
var message = context.Messages
.FirstOrDefault(x => x.MessageId.Equals(model.MessageId));
if (message == null)
{
return null;
}
message.Update(model);
context.SaveChanges();
return context.Messages
.FirstOrDefault(x => x.MessageId.Equals(model.MessageId))
?.GetViewModel;
}
}
}

View File

@ -0,0 +1,286 @@
// <auto-generated />
using System;
using BlacksmithWorkshopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(BlacksmithWorkshopDatabase))]
[Migration("20230420125158_LabWork07")]
partial class LabWork07
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ManufactureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("WorkPieceId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("WorkPieceId");
b.ToTable("ManufactureWorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.IsRequired()
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.ToTable("Messages");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("ManufactureId");
b.ToTable("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("WorkPieceName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("WorkPieces")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", "WorkPiece")
.WithMany("ManufactureWorkPieces")
.HasForeignKey("WorkPieceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("WorkPiece");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Orders")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Navigation("Orders");
b.Navigation("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Navigation("ManufactureWorkPieces");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,38 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class LabWork07 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Messages",
columns: table => new
{
MessageId = table.Column<string>(type: "nvarchar(450)", nullable: false),
ClientId = table.Column<int>(type: "int", nullable: false),
SenderName = table.Column<string>(type: "nvarchar(max)", nullable: false),
DateDelivery = table.Column<DateTime>(type: "datetime2", nullable: false),
Subject = table.Column<string>(type: "nvarchar(max)", nullable: false),
Body = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Messages", x => x.MessageId);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Messages");
}
}
}

View File

@ -0,0 +1,298 @@
// <auto-generated />
using System;
using BlacksmithWorkshopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(BlacksmithWorkshopDatabase))]
[Migration("20230420201528_TwoLabWork07")]
partial class TwoLabWork07
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ManufactureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("WorkPieceId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("WorkPieceId");
b.ToTable("ManufactureWorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("ManufactureId");
b.ToTable("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("WorkPieceName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("WorkPieces")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", "WorkPiece")
.WithMany("ManufactureWorkPieces")
.HasForeignKey("WorkPieceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("WorkPiece");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("MessageInfos")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Orders")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Navigation("MessageInfos");
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Navigation("Orders");
b.Navigation("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Navigation("ManufactureWorkPieces");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,59 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class TwoLabWork07 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DELETE FROM [dbo].[Orders]");
migrationBuilder.Sql("DELETE FROM [dbo].[Messages]");
migrationBuilder.AlterColumn<int>(
name: "ClientId",
table: "Messages",
type: "int",
nullable: true,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.CreateIndex(
name: "IX_Messages_ClientId",
table: "Messages",
column: "ClientId");
migrationBuilder.AddForeignKey(
name: "FK_Messages_Clients_ClientId",
table: "Messages",
column: "ClientId",
principalTable: "Clients",
principalColumn: "Id");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Messages_Clients_ClientId",
table: "Messages");
migrationBuilder.DropIndex(
name: "IX_Messages_ClientId",
table: "Messages");
migrationBuilder.AlterColumn<int>(
name: "ClientId",
table: "Messages",
type: "int",
nullable: false,
defaultValue: 0,
oldClrType: typeof(int),
oldType: "int",
oldNullable: true);
}
}
}

View File

@ -0,0 +1,298 @@
// <auto-generated />
using System;
using BlacksmithWorkshopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(BlacksmithWorkshopDatabase))]
[Migration("20230420203801_ThreeLabWork07")]
partial class ThreeLabWork07
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ManufactureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("WorkPieceId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("WorkPieceId");
b.ToTable("ManufactureWorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("ManufactureId");
b.ToTable("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("WorkPieceName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("WorkPieces")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", "WorkPiece")
.WithMany("ManufactureWorkPieces")
.HasForeignKey("WorkPieceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("WorkPiece");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("MessageInfos")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Orders")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Navigation("MessageInfos");
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Navigation("Orders");
b.Navigation("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Navigation("ManufactureWorkPieces");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class ThreeLabWork07 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DELETE FROM [dbo].[Clients]");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@ -0,0 +1,298 @@
// <auto-generated />
using System;
using BlacksmithWorkshopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(BlacksmithWorkshopDatabase))]
[Migration("20230420204027_FourLabWork07")]
partial class FourLabWork07
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ManufactureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("WorkPieceId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("WorkPieceId");
b.ToTable("ManufactureWorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("ManufactureId");
b.ToTable("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("WorkPieceName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("WorkPieces")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", "WorkPiece")
.WithMany("ManufactureWorkPieces")
.HasForeignKey("WorkPieceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("WorkPiece");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("MessageInfos")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Orders")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Navigation("MessageInfos");
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Navigation("Orders");
b.Navigation("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Navigation("ManufactureWorkPieces");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class FourLabWork07 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DELETE FROM [dbo].[Orders]");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@ -0,0 +1,383 @@
// <auto-generated />
using System;
using BlacksmithWorkshopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(BlacksmithWorkshopDatabase))]
[Migration("20230430151520_LabWork07Hard")]
partial class LabWork07Hard
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ManufactureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("WorkPieceId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("WorkPieceId");
b.ToTable("ManufactureWorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Answer")
.HasColumnType("nvarchar(max)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<bool>("IsRead")
.HasColumnType("bit");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("ManufactureId");
b.ToTable("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateOpen")
.HasColumnType("datetime2");
b.Property<int>("MaxCountManufactures")
.HasColumnType("int");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("ShopId");
b.ToTable("ShopManufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("WorkPieceName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("WorkPieces")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", "WorkPiece")
.WithMany("ManufactureWorkPieces")
.HasForeignKey("WorkPieceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("WorkPiece");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("MessageInfos")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Orders")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Shops")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Manufactures")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("Shop");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Navigation("MessageInfos");
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Navigation("Orders");
b.Navigation("Shops");
b.Navigation("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Navigation("ManufactureWorkPieces");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,39 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class LabWork07Hard : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Answer",
table: "Messages",
type: "nvarchar(max)",
nullable: true);
migrationBuilder.AddColumn<bool>(
name: "IsRead",
table: "Messages",
type: "bit",
nullable: false,
defaultValue: false);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Answer",
table: "Messages");
migrationBuilder.DropColumn(
name: "IsRead",
table: "Messages");
}
}
}

View File

@ -0,0 +1,383 @@
// <auto-generated />
using System;
using BlacksmithWorkshopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(BlacksmithWorkshopDatabase))]
[Migration("20230430171113_LabWork07HardSecond")]
partial class LabWork07HardSecond
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.4")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ClientFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ImplementerFIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Qualification")
.HasColumnType("int");
b.Property<int>("WorkExperience")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("Implementers");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ManufactureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("WorkPieceId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("WorkPieceId");
b.ToTable("ManufactureWorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Answer")
.HasColumnType("nvarchar(max)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<bool>("IsRead")
.HasColumnType("bit");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ClientId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int?>("ImplementerId")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ClientId");
b.HasIndex("ImplementerId");
b.HasIndex("ManufactureId");
b.ToTable("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateOpen")
.HasColumnType("datetime2");
b.Property<int>("MaxCountManufactures")
.HasColumnType("int");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("ShopId");
b.ToTable("ShopManufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<double>("Cost")
.HasColumnType("float");
b.Property<string>("WorkPieceName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureWorkPiece", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("WorkPieces")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", "WorkPiece")
.WithMany("ManufactureWorkPieces")
.HasForeignKey("WorkPieceId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("WorkPiece");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("MessageInfos")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("Orders")
.HasForeignKey("ClientId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Implementer", "Implementer")
.WithMany("Orders")
.HasForeignKey("ImplementerId");
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Orders")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Client");
b.Navigation("Implementer");
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Shops")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Manufactures")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("Shop");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Navigation("MessageInfos");
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Implementer", b =>
{
b.Navigation("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Navigation("Orders");
b.Navigation("Shops");
b.Navigation("WorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.WorkPiece", b =>
{
b.Navigation("ManufactureWorkPieces");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class LabWork07HardSecond : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@ -120,6 +120,42 @@ namespace BlacksmithWorkshopDatabaseImplement.Migrations
b.ToTable("ManufactureWorkPieces");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.Property<string>("MessageId")
.HasColumnType("nvarchar(450)");
b.Property<string>("Answer")
.HasColumnType("nvarchar(max)");
b.Property<string>("Body")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int?>("ClientId")
.HasColumnType("int");
b.Property<DateTime>("DateDelivery")
.HasColumnType("datetime2");
b.Property<bool>("IsRead")
.HasColumnType("bit");
b.Property<string>("SenderName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subject")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("MessageId");
b.HasIndex("ClientId");
b.ToTable("Messages");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -255,6 +291,15 @@ namespace BlacksmithWorkshopDatabaseImplement.Migrations
b.Navigation("WorkPiece");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
.WithMany("MessageInfos")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Client", "Client")
@ -301,6 +346,8 @@ namespace BlacksmithWorkshopDatabaseImplement.Migrations
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Client", b =>
{
b.Navigation("MessageInfos");
b.Navigation("Orders");
});

View File

@ -28,6 +28,9 @@ namespace BlacksmithWorkshopDatabaseImplement.Models
[ForeignKey("ClientId")]
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("ClientId")]
public virtual List<MessageInfo> MessageInfos { get; set; } = new();
public static Client? Create(ClientBindingModel model)
{
if (model == null)
@ -44,17 +47,6 @@ namespace BlacksmithWorkshopDatabaseImplement.Models
};
}
public static Client Create(ClientViewModel model)
{
return new Client
{
Id = model.Id,
ClientFIO = model.ClientFIO,
Email = model.Email,
Password = model.Password
};
}
public void Update(ClientBindingModel model)
{
if (model == null)

View File

@ -0,0 +1,81 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class MessageInfo : IMessageInfoModel
{
[Key]
public string MessageId { get; set; } = string.Empty;
public int? ClientId { get; set; }
public bool IsRead { get; private set; } = false;
[Required]
public string SenderName { get; set; } = string.Empty;
[Required]
public DateTime DateDelivery { get; set; } = DateTime.Now;
[Required]
public string Subject { get; set; } = string.Empty;
[Required]
public string Body { get; set; } = string.Empty;
public string? Answer { get; private set; } = string.Empty;
public virtual Client? Client { get; set; }
public static MessageInfo? Create(MessageInfoBindingModel model)
{
if (model == null)
{
return null;
}
return new MessageInfo()
{
MessageId = model.MessageId,
ClientId = model.ClientId,
SenderName = model.SenderName,
Body = model.Body,
DateDelivery = model.DateDelivery,
Subject = model.Subject,
IsRead = model.IsRead,
Answer = model.Answer
};
}
public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
IsRead = model.IsRead;
Answer = model.Answer;
}
public MessageInfoViewModel GetViewModel => new()
{
MessageId = MessageId,
ClientId = ClientId,
SenderName = SenderName,
Body = Body,
DateDelivery = DateDelivery,
Subject = Subject,
IsRead = IsRead,
Answer = Answer
};
}
}

View File

@ -24,6 +24,8 @@ namespace BlacksmithWorkshopFileImplement
private readonly string ImplementerFileName = "Implementer.xml";
private readonly string MessageFileName = "Message.xml";
public List<WorkPiece> WorkPieces { get; private set; }
public List<Order> Orders { get; private set; }
@ -36,6 +38,8 @@ namespace BlacksmithWorkshopFileImplement
public List<Implementer> Implementers { get; private set; }
public List<MessageInfo> Messages { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -58,6 +62,8 @@ namespace BlacksmithWorkshopFileImplement
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
public void SaveMessages() => SaveData(Messages, MessageFileName, "Messages", x => x.GetXElement);
private DataFileSingleton()
{
WorkPieces = LoadData(WorkPieceFileName, "WorkPiece", x => WorkPiece.Create(x)!)!;
@ -66,7 +72,8 @@ namespace BlacksmithWorkshopFileImplement
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
}
Messages = LoadData(MessageFileName, "Messages", x => MessageInfo.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{

View File

@ -0,0 +1,92 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopFileImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
private readonly DataFileSingleton source;
public MessageInfoStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<MessageInfoViewModel> GetFullList()
{
return source.Messages.Select(x => GetViewModel(x)).ToList();
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
Review

Нет поиска по заявленным условиям

Нет поиска по заявленным условиям
{
if (!model.ClientId.HasValue)
{
return source.Messages
.Select(x => GetViewModel(x))
.ToList();
}
return source.Messages
.Where(x => x.ClientId == model.ClientId)
.Select(x => GetViewModel(x))
.ToList();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (!model.ClientId.HasValue)
{
return null;
}
return source.Messages.FirstOrDefault(x => (model.ClientId.HasValue && x.ClientId == model.ClientId))?.GetViewModel;
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
model.MessageId = source.Messages.Count > 0 ? Convert.ToString(source.Messages.Count + 1) : "1";
var newMessage = MessageInfo.Create(model);
if (newMessage == null)
{
return null;
}
source.Messages.Add(newMessage);
source.SaveOrders();
return GetViewModel(newMessage);
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
var message = source.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId));
if (message == null)
{
return null;
}
message.Update(model);
source.SaveClients();
return message.GetViewModel;
}
//для загрузки названий и имён в заказ
private MessageInfoViewModel GetViewModel(MessageInfo message)
{
return message.GetViewModel;
}
}
}

View File

@ -0,0 +1,113 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace BlacksmithWorkshopFileImplement.Models
{
public class MessageInfo : IMessageInfoModel
{
public string MessageId { get; private set; } = string.Empty;
public int? ClientId { get; private set; }
public bool IsRead { get; private set; } = false;
public string SenderName { get; private set; } = string.Empty;
public DateTime DateDelivery { get; private set; } = DateTime.Now;
public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty;
public string? Answer { get; private set; } = string.Empty;
public static MessageInfo? Create(MessageInfoBindingModel model)
{
if (model == null)
{
return null;
}
return new MessageInfo()
{
MessageId = model.MessageId,
ClientId = model.ClientId,
SenderName = model.SenderName,
Body = model.Body,
Subject = model.Subject,
DateDelivery = model.DateDelivery,
IsRead = model.IsRead,
Answer = model.Answer
};
}
public static MessageInfo? Create(XElement element)
{
if (element == null)
{
return null;
}
return new MessageInfo()
{
MessageId = element.Element("MessageId")!.Value,
ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value),
SenderName = element.Element("SenderName")!.Value,
Body = element.Element("Body")!.Value,
Subject = element.Element("Subject")!.Value,
DateDelivery = Convert.ToDateTime(element.Element("DateDelivery")!.Value),
IsRead = Convert.ToBoolean(element.Element("IsRead")!.Value),
Answer = element.Element("Answer")!.Value
};
}
public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
MessageId = model.MessageId;
ClientId = model.ClientId;
SenderName = model.SenderName;
Body = model.Body;
Subject = model.Subject;
DateDelivery = model.DateDelivery;
IsRead = model.IsRead;
Answer = model.Answer;
}
public MessageInfoViewModel GetViewModel => new()
{
MessageId = MessageId,
ClientId = ClientId,
SenderName = SenderName,
Body = Body,
Subject = Subject,
DateDelivery = DateDelivery,
IsRead = IsRead,
Answer = Answer
};
public XElement GetXElement => new("MessageInfo",
new XAttribute("MessageId", MessageId),
new XElement("ClientId", ClientId.ToString()),
new XElement("SenderName", SenderName),
new XElement("Body", Body),
new XElement("Subject", Subject),
new XElement("DateDelivery", DateDelivery.ToString()),
new XElement("IsRead", IsRead),
new XElement("Answer", Answer));
}
}

View File

@ -30,6 +30,10 @@ namespace BlacksmithWorkshopListImplement
//список для хранения исполнителей
public List<Implementer> Implementers { get; set; }
//список для хранения писем
public List<MessageInfo> MessageInfos { get; set; }
public DataListSingleton()
{
WorkPieces = new List<WorkPiece>();
@ -38,6 +42,7 @@ namespace BlacksmithWorkshopListImplement
Shops = new List<Shop>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
MessageInfos = new List<MessageInfo>();
}
public static DataListSingleton GetInstance()

View File

@ -0,0 +1,103 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopListImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
//поле для работы со списком изделий
private readonly DataListSingleton _source;
public MessageInfoStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<MessageInfoViewModel> GetFullList()
{
var result = new List<MessageInfoViewModel>();
foreach (var messageInfo in _source.MessageInfos)
{
result.Add(messageInfo.GetViewModel);
}
return result;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
Review

Нет поиска по заявленным условиям

Нет поиска по заявленным условиям
{
var result = new List<MessageInfoViewModel>();
if (string.IsNullOrEmpty(model.MessageId))
{
return result;
}
foreach (var messageInfo in _source.MessageInfos)
{
if (messageInfo.ClientId == model.ClientId)
{
result.Add(messageInfo.GetViewModel);
}
}
return result;
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (string.IsNullOrEmpty(model.MessageId))
{
return null;
}
foreach (var messageInfo in _source.MessageInfos)
{
if (messageInfo.MessageId == model.MessageId)
{
return messageInfo.GetViewModel;
}
}
return null;
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
var newMessage = MessageInfo.Create(model);
if (newMessage == null)
{
return null;
}
_source.MessageInfos.Add(newMessage);
return newMessage.GetViewModel;
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
foreach (var message in _source.MessageInfos)
{
if (message.MessageId.Equals(model.MessageId))
{
message.Update(model);
return message.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,84 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopListImplement.Models
{
public class MessageInfo : IMessageInfoModel
{
public string MessageId { get; private set; } = string.Empty;
public int? ClientId { get; private set; }
public bool IsRead { get; private set; }
public string SenderName { get; private set; } = string.Empty;
public DateTime DateDelivery { get; private set; } = DateTime.Now;
public string Subject { get; private set; } = string.Empty;
public string Body { get; private set; } = string.Empty;
public string? Answer { get; private set; } = string.Empty;
//метод для создания объекта от класса-компонента на основе класса-BindingModel
public static MessageInfo? Create(MessageInfoBindingModel? model)
{
if (model == null)
{
return null;
}
return new MessageInfo()
{
MessageId = model.MessageId,
ClientId = model.ClientId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
Subject = model.Subject,
Body = model.Body,
IsRead = model.IsRead,
Answer = model.Answer
};
}
//метод изменения существующего объекта
public void Update(MessageInfoBindingModel? model)
{
if (model == null)
{
return;
}
MessageId = model.MessageId;
ClientId = model.ClientId;
SenderName = model.SenderName;
DateDelivery = model.DateDelivery;
Subject = model.Subject;
Body = model.Body;
IsRead = model.IsRead;
Answer = model.Answer;
}
//метод для создания объекта класса ViewModel на основе данных объекта класса-компонента
public MessageInfoViewModel GetViewModel => new()
{
MessageId = MessageId,
ClientId = ClientId,
SenderName = SenderName,
DateDelivery = DateDelivery,
Subject = Subject,
Body = Body,
IsRead = IsRead,
Answer = Answer
};
}
}