Kashin M.I. Lab work 7 hard #15

Closed
Sosees04ka wants to merge 6 commits from LabWork07_hard into LabWork06_hard
45 changed files with 2008 additions and 101 deletions

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="lab7kashin@gmail.com" />
<add key="MailPassword" value="unyh tpno drla wnzo" />
</appSettings>
</configuration>

View File

@ -43,6 +43,7 @@
this.магазиныСИзделиямиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.списокГруппЗаказовToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.запускРаботToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.письмаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.DataGridView = new System.Windows.Forms.DataGridView();
this.CreateOrderButton = new System.Windows.Forms.Button();
this.IssuedOrderButton = new System.Windows.Forms.Button();
@ -59,10 +60,12 @@
this.MenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.СправочникиToolStripMenuItem,
this.отчетыToolStripMenuItem,
this.запускРаботToolStripMenuItem});
this.запускРаботToolStripMenuItem,
this.письмаToolStripMenuItem});
this.MenuStrip.Location = new System.Drawing.Point(0, 0);
this.MenuStrip.Name = "MenuStrip";
this.MenuStrip.Size = new System.Drawing.Size(1058, 24);
this.MenuStrip.Padding = new System.Windows.Forms.Padding(7, 3, 0, 3);
this.MenuStrip.Size = new System.Drawing.Size(1209, 30);
this.MenuStrip.TabIndex = 0;
this.MenuStrip.Text = "menuStrip1";
//
@ -75,41 +78,41 @@
this.исполнителиToolStripMenuItem,
this.МагазинtoolStripMenuItem});
this.СправочникиToolStripMenuItem.Name = "СправочникиToolStripMenuItem";
this.СправочникиToolStripMenuItem.Size = new System.Drawing.Size(94, 20);
this.СправочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24);
this.СправочникиToolStripMenuItem.Text = "Cправочники";
//
// ИзделияToolStripMenuItem
//
this.ИзделияToolStripMenuItem.Name = "ИзделияToolStripMenuItem";
this.ИзделияToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.ИзделияToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.ИзделияToolStripMenuItem.Text = "Изделия";
this.ИзделияToolStripMenuItem.Click += new System.EventHandler(this.ИзделияToolStripMenuItem_Click);
//
// КомпонентыToolStripMenuItem
//
this.КомпонентыToolStripMenuItem.Name = "КомпонентыToolStripMenuItem";
this.КомпонентыToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.КомпонентыToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.КомпонентыToolStripMenuItem.Text = "Компоненты";
this.КомпонентыToolStripMenuItem.Click += new System.EventHandler(this.КомпонентыToolStripMenuItem_Click);
//
// КлиентыToolStripMenuItem
//
this.КлиентыToolStripMenuItem.Name = "КлиентыToolStripMenuItem";
this.КлиентыToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.КлиентыToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.КлиентыToolStripMenuItem.Text = "Клиенты";
this.КлиентыToolStripMenuItem.Click += new System.EventHandler(this.КлиентыToolStripMenuItem_Click);
//
// исполнителиToolStripMenuItem
//
this.исполнителиToolStripMenuItem.Name = сполнителиToolStripMenuItem";
this.исполнителиToolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.исполнителиToolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.исполнителиToolStripMenuItem.Text = "Исполнители";
this.исполнителиToolStripMenuItem.Click += new System.EventHandler(this.исполнителиToolStripMenuItem_Click);
//
// МагазинtoolStripMenuItem
//
this.МагазинtoolStripMenuItem.Name = "МагазинtoolStripMenuItem";
this.МагазинtoolStripMenuItem.Size = new System.Drawing.Size(149, 22);
this.МагазинtoolStripMenuItem.Size = new System.Drawing.Size(185, 26);
this.МагазинtoolStripMenuItem.Text = "Магазины";
this.МагазинtoolStripMenuItem.Click += new System.EventHandler(this.МагазинtoolStripMenuItem_Click);
//
@ -123,73 +126,82 @@
this.магазиныСИзделиямиToolStripMenuItem,
this.списокГруппЗаказовToolStripMenuItem});
this.отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
this.отчетыToolStripMenuItem.Size = new System.Drawing.Size(60, 20);
this.отчетыToolStripMenuItem.Size = new System.Drawing.Size(73, 24);
this.отчетыToolStripMenuItem.Text = "Отчеты";
//
// списокДокументовToolStripMenuItem
//
this.списокДокументовToolStripMenuItem.Name = "списокДокументовToolStripMenuItem";
this.списокДокументовToolStripMenuItem.Size = new System.Drawing.Size(232, 22);
this.списокДокументовToolStripMenuItem.Size = new System.Drawing.Size(292, 26);
this.списокДокументовToolStripMenuItem.Text = "Список документов";
this.списокДокументовToolStripMenuItem.Click += new System.EventHandler(this.списокДокументовToolStripMenuItem_Click);
//
// компонентыПоДокументамToolStripMenuItem
//
this.компонентыПоДокументамToolStripMenuItem.Name = омпонентыПоДокументамToolStripMenuItem";
this.компонентыПоДокументамToolStripMenuItem.Size = new System.Drawing.Size(232, 22);
this.компонентыПоДокументамToolStripMenuItem.Size = new System.Drawing.Size(292, 26);
this.компонентыПоДокументамToolStripMenuItem.Text = "Компоненты по документам";
this.компонентыПоДокументамToolStripMenuItem.Click += new System.EventHandler(this.компонентыПоДокументамToolStripMenuItem_Click);
//
// списокЗаказовToolStripMenuItem
//
this.списокЗаказовToolStripMenuItem.Name = "списокЗаказовToolStripMenuItem";
this.списокЗаказовToolStripMenuItem.Size = new System.Drawing.Size(232, 22);
this.списокЗаказовToolStripMenuItem.Size = new System.Drawing.Size(292, 26);
this.списокЗаказовToolStripMenuItem.Text = "Список заказов";
this.списокЗаказовToolStripMenuItem.Click += new System.EventHandler(this.списокЗаказовToolStripMenuItem_Click);
//
// списокМагазиновToolStripMenuItem
//
this.списокМагазиновToolStripMenuItem.Name = "списокМагазиновToolStripMenuItem";
this.списокМагазиновToolStripMenuItem.Size = new System.Drawing.Size(232, 22);
this.списокМагазиновToolStripMenuItem.Size = new System.Drawing.Size(292, 26);
this.списокМагазиновToolStripMenuItem.Text = "Список магазинов";
this.списокМагазиновToolStripMenuItem.Click += new System.EventHandler(this.списокМагазиновToolStripMenuItem_Click);
//
// магазиныСИзделиямиToolStripMenuItem
//
this.магазиныСИзделиямиToolStripMenuItem.Name = агазиныСИзделиямиToolStripMenuItem";
this.магазиныСИзделиямиToolStripMenuItem.Size = new System.Drawing.Size(232, 22);
this.магазиныСИзделиямиToolStripMenuItem.Text = "Магазины с изделиями";
this.магазиныСИзделиямиToolStripMenuItem.Size = new System.Drawing.Size(292, 26);
this.магазиныСИзделиямиToolStripMenuItem.Text = "Магазины с изделями";
this.магазиныСИзделиямиToolStripMenuItem.Click += new System.EventHandler(this.магазиныСИзделиямиToolStripMenuItem_Click);
//
// списокГруппЗаказовToolStripMenuItem
//
this.списокГруппЗаказовToolStripMenuItem.Name = "списокГруппЗаказовToolStripMenuItem";
this.списокГруппЗаказовToolStripMenuItem.Size = new System.Drawing.Size(232, 22);
this.списокГруппЗаказовToolStripMenuItem.Size = new System.Drawing.Size(292, 26);
this.списокГруппЗаказовToolStripMenuItem.Text = "Список групп заказов";
this.списокГруппЗаказовToolStripMenuItem.Click += new System.EventHandler(this.списокГруппЗаказовToolStripMenuItem_Click);
//
// запускРаботToolStripMenuItem
//
this.запускРаботToolStripMenuItem.Name = апускРаботToolStripMenuItem";
this.запускРаботToolStripMenuItem.Size = new System.Drawing.Size(92, 20);
this.запускРаботToolStripMenuItem.Size = new System.Drawing.Size(114, 24);
this.запускРаботToolStripMenuItem.Text = "Запуск работ";
this.запускРаботToolStripMenuItem.Click += new System.EventHandler(this.запускРаботToolStripMenuItem_Click);
//
// письмаToolStripMenuItem
//
this.письмаToolStripMenuItem.Name = "письмаToolStripMenuItem";
this.письмаToolStripMenuItem.Size = new System.Drawing.Size(77, 24);
this.письмаToolStripMenuItem.Text = "Письма";
this.письмаToolStripMenuItem.Click += new System.EventHandler(this.письмаToolStripMenuItem_Click);
//
// DataGridView
//
this.DataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.DataGridView.Location = new System.Drawing.Point(0, 27);
this.DataGridView.Location = new System.Drawing.Point(0, 36);
this.DataGridView.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.DataGridView.Name = "DataGridView";
this.DataGridView.RowHeadersWidth = 51;
this.DataGridView.RowTemplate.Height = 25;
this.DataGridView.Size = new System.Drawing.Size(881, 421);
this.DataGridView.Size = new System.Drawing.Size(1007, 561);
this.DataGridView.TabIndex = 1;
//
// CreateOrderButton
//
this.CreateOrderButton.Location = new System.Drawing.Point(905, 27);
this.CreateOrderButton.Location = new System.Drawing.Point(1034, 36);
this.CreateOrderButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.CreateOrderButton.Name = "CreateOrderButton";
this.CreateOrderButton.Size = new System.Drawing.Size(125, 33);
this.CreateOrderButton.Size = new System.Drawing.Size(143, 44);
this.CreateOrderButton.TabIndex = 2;
this.CreateOrderButton.Text = "Создать заказ";
this.CreateOrderButton.UseVisualStyleBackColor = true;
@ -197,10 +209,10 @@
//
// IssuedOrderButton
//
this.IssuedOrderButton.Location = new System.Drawing.Point(905, 112);
this.IssuedOrderButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.IssuedOrderButton.Location = new System.Drawing.Point(1034, 149);
this.IssuedOrderButton.Margin = new System.Windows.Forms.Padding(3, 5, 3, 5);
this.IssuedOrderButton.Name = "IssuedOrderButton";
this.IssuedOrderButton.Size = new System.Drawing.Size(125, 33);
this.IssuedOrderButton.Size = new System.Drawing.Size(143, 44);
this.IssuedOrderButton.TabIndex = 5;
this.IssuedOrderButton.Text = "Заказ выдан";
this.IssuedOrderButton.UseVisualStyleBackColor = true;
@ -208,9 +220,10 @@
//
// UpdateListButton
//
this.UpdateListButton.Location = new System.Drawing.Point(905, 189);
this.UpdateListButton.Location = new System.Drawing.Point(1034, 252);
this.UpdateListButton.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.UpdateListButton.Name = "UpdateListButton";
this.UpdateListButton.Size = new System.Drawing.Size(125, 33);
this.UpdateListButton.Size = new System.Drawing.Size(143, 44);
this.UpdateListButton.TabIndex = 6;
this.UpdateListButton.Text = "Обновить список";
this.UpdateListButton.UseVisualStyleBackColor = true;
@ -218,9 +231,9 @@
//
// buttonSellReinforced
//
this.buttonSellReinforced.Location = new System.Drawing.Point(905, 295);
this.buttonSellReinforced.Location = new System.Drawing.Point(1036, 372);
this.buttonSellReinforced.Name = "buttonSellReinforced";
this.buttonSellReinforced.Size = new System.Drawing.Size(125, 33);
this.buttonSellReinforced.Size = new System.Drawing.Size(141, 46);
this.buttonSellReinforced.TabIndex = 7;
this.buttonSellReinforced.Text = "Продать изделие";
this.buttonSellReinforced.UseVisualStyleBackColor = true;
@ -228,9 +241,9 @@
//
// buttonAddReinforcedInShop
//
this.buttonAddReinforcedInShop.Location = new System.Drawing.Point(905, 365);
this.buttonAddReinforcedInShop.Location = new System.Drawing.Point(1036, 456);
this.buttonAddReinforcedInShop.Name = "buttonAddReinforcedInShop";
this.buttonAddReinforcedInShop.Size = new System.Drawing.Size(125, 39);
this.buttonAddReinforcedInShop.Size = new System.Drawing.Size(141, 51);
this.buttonAddReinforcedInShop.TabIndex = 8;
this.buttonAddReinforcedInShop.Text = "Пополнение магазина";
this.buttonAddReinforcedInShop.UseVisualStyleBackColor = true;
@ -238,9 +251,9 @@
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1058, 475);
this.ClientSize = new System.Drawing.Size(1209, 633);
this.Controls.Add(this.buttonAddReinforcedInShop);
this.Controls.Add(this.buttonSellReinforced);
this.Controls.Add(this.UpdateListButton);
@ -249,6 +262,7 @@
this.Controls.Add(this.DataGridView);
this.Controls.Add(this.MenuStrip);
this.MainMenuStrip = this.MenuStrip;
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.Name = "FormMain";
this.Text = "Завод ЖБИ";
this.Load += new System.EventHandler(this.FormMain_Load);
@ -278,10 +292,11 @@
private ToolStripMenuItem запускРаботToolStripMenuItem;
private ToolStripMenuItem исполнителиToolStripMenuItem;
private ToolStripMenuItem МагазинtoolStripMenuItem;
private Button buttonSellReinforced;
private Button buttonAddReinforcedInShop;
private ToolStripMenuItem списокМагазиновToolStripMenuItem;
private ToolStripMenuItem магазиныСИзделиямиToolStripMenuItem;
private ToolStripMenuItem списокГруппЗаказовToolStripMenuItem;
private ToolStripMenuItem письмаToolStripMenuItem;
private Button buttonSellReinforced;
private Button buttonAddReinforcedInShop;
}
}

View File

@ -258,25 +258,6 @@ namespace PrecastConcretePlantView
}
}
private void buttonSellReinforced_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSellReinforced));
if (service is FormSellReinforced form)
{
form.ShowDialog();
}
}
private void buttonAddReinforcedInShop_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReinforcedShop));
if (service is FormReinforcedShop form)
{
form.ShowDialog();
}
}
private void списокМагазиновToolStripMenuItem_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog { Filter = "docx|*.docx" };
@ -304,5 +285,33 @@ namespace PrecastConcretePlantView
form.ShowDialog();
}
}
private void письмаToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormViewMail));
if (service is FormViewMail form)
{
form.ShowDialog();
}
}
private void buttonSellReinforced_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSellReinforced));
if (service is FormSellReinforced form)
{
form.ShowDialog();
}
}
private void buttonAddReinforcedInShop_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReinforcedShop));
if (service is FormReinforcedShop form)
{
form.ShowDialog();
}
}
}
}

View File

@ -0,0 +1,149 @@
namespace PrecastConcretePlantView
{
partial class FormReplyMail
{
/// <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();
label1 = new Label();
label2 = new Label();
label3 = new Label();
textBoxHead = new TextBox();
textBoxMail = new TextBox();
textBoxReply = new TextBox();
SuspendLayout();
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSave.Location = new Point(460, 291);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(117, 30);
buttonSave.TabIndex = 0;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(337, 291);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(117, 30);
buttonCancel.TabIndex = 1;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// label1
//
label1.Location = new Point(12, 9);
label1.Name = "label1";
label1.Size = new Size(117, 23);
label1.TabIndex = 2;
label1.Text = "Заголовок письма:";
label1.TextAlign = ContentAlignment.TopRight;
//
// label2
//
label2.Location = new Point(12, 38);
label2.Name = "label2";
label2.Size = new Size(117, 23);
label2.TabIndex = 3;
label2.Text = "Текст письма:";
label2.TextAlign = ContentAlignment.TopRight;
//
// label3
//
label3.Location = new Point(12, 117);
label3.Name = "label3";
label3.Size = new Size(117, 31);
label3.TabIndex = 4;
label3.Text = "Ответ на письмо:";
label3.TextAlign = ContentAlignment.TopRight;
//
// textBoxHead
//
textBoxHead.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxHead.Location = new Point(135, 5);
textBoxHead.Name = "textBoxHead";
textBoxHead.ReadOnly = true;
textBoxHead.Size = new Size(442, 23);
textBoxHead.TabIndex = 5;
//
// textBoxMail
//
textBoxMail.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxMail.Location = new Point(135, 35);
textBoxMail.Multiline = true;
textBoxMail.Name = "textBoxMail";
textBoxMail.ReadOnly = true;
textBoxMail.Size = new Size(442, 76);
textBoxMail.TabIndex = 6;
//
// textBoxReply
//
textBoxReply.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
textBoxReply.Location = new Point(135, 117);
textBoxReply.Multiline = true;
textBoxReply.Name = "textBoxReply";
textBoxReply.Size = new Size(442, 168);
textBoxReply.TabIndex = 7;
//
// FormReplyMail
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(589, 333);
Controls.Add(textBoxReply);
Controls.Add(textBoxMail);
Controls.Add(textBoxHead);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Name = "FormReplyMail";
Text = "Ответ на письмо";
Load += FormReplyMail_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSave;
private Button buttonCancel;
private Label label1;
private Label label2;
private Label label3;
private TextBox textBoxHead;
private TextBox textBoxMail;
private TextBox textBoxReply;
}
}

View File

@ -0,0 +1,83 @@
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;
using PrecastConcretePlantBusinessLogic.MailWorker;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using PrecastConcretePlantContracts.ViewModels;
using Microsoft.Extensions.Logging;
using MimeKit;
namespace PrecastConcretePlantView
{
public partial class FormReplyMail : Form
{
private readonly ILogger _logger;
private readonly AbstractMailWorker _mailWorker;
private readonly IMessageInfoLogic _logic;
private MessageInfoViewModel _message;
public string MessageId { get; set; } = string.Empty;
public FormReplyMail(ILogger<FormReplyMail> logger, AbstractMailWorker mailWorker, IMessageInfoLogic logic)
{
InitializeComponent();
_logger = logger;
_mailWorker = mailWorker;
_logic = logic;
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
_mailWorker.MailSendAsync(new()
{
MailAddress = _message.SenderName,
Subject = _message.Subject,
Text = textBoxReply.Text,
});
_logic.Update(new()
{
MessageId = MessageId,
Reply = textBoxReply.Text,
HasRead = true,
});
MessageBox.Show("Успешно отправлено письмо", "Отправка письма", MessageBoxButtons.OK);
DialogResult = DialogResult.OK;
Close();
}
private void FormReplyMail_Load(object sender, EventArgs e)
{
try
{
_message = _logic.ReadElement(new() { MessageId = MessageId });
if (_message == null)
throw new ArgumentNullException("Письма с таким id не существует");
Text += $"для {_message.SenderName}";
textBoxHead.Text = _message.Subject;
textBoxMail.Text = _message.Body;
if (_message.HasRead is false)
{
_logic.Update(new() { MessageId = MessageId, HasRead = true, Reply = _message.Reply });
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения собщения");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
}

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,104 @@
namespace PrecastConcretePlantView
{
partial class FormViewMail
{
/// <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();
buttonPrevPage = new Button();
buttonNextPage = new Button();
labelInfoPages = new Label();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 0);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(730, 454);
dataGridView.TabIndex = 0;
dataGridView.RowHeaderMouseClick += dataGridView_RowHeaderMouseClick;
//
// buttonPrevPage
//
buttonPrevPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonPrevPage.Location = new Point(12, 460);
buttonPrevPage.Name = "buttonPrevPage";
buttonPrevPage.Size = new Size(75, 23);
buttonPrevPage.TabIndex = 1;
buttonPrevPage.Text = "<<<";
buttonPrevPage.UseVisualStyleBackColor = true;
buttonPrevPage.Click += ButtonPrevPage_Click;
//
// buttonNextPage
//
buttonNextPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonNextPage.Location = new Point(203, 460);
buttonNextPage.Name = "buttonNextPage";
buttonNextPage.Size = new Size(75, 23);
buttonNextPage.TabIndex = 2;
buttonNextPage.Text = ">>>";
buttonNextPage.UseVisualStyleBackColor = true;
buttonNextPage.Click += ButtonNextPage_Click;
//
// labelInfoPages
//
labelInfoPages.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
labelInfoPages.Location = new Point(93, 464);
labelInfoPages.Name = "labelInfoPages";
labelInfoPages.Size = new Size(104, 19);
labelInfoPages.TabIndex = 3;
labelInfoPages.Text = "{0} страница";
labelInfoPages.TextAlign = ContentAlignment.MiddleCenter;
//
// FormViewMail
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(727, 498);
Controls.Add(labelInfoPages);
Controls.Add(buttonNextPage);
Controls.Add(buttonPrevPage);
Controls.Add(dataGridView);
Name = "FormViewMail";
Text = "Письма";
Load += FormViewMail_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonPrevPage;
private Button buttonNextPage;
private Label labelInfoPages;
}
}

View File

@ -0,0 +1,111 @@
using PrecastConcretePlantBusinessLogic.MailWorker;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
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;
using PrecastConcretePlantContracts.ViewModels;
namespace PrecastConcretePlantView
{
public partial class FormViewMail : Form
{
private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic;
private int currentPage = 1;
public int pageSize = 5;
public FormViewMail(ILogger<FormViewMail> logger, IMessageInfoLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
buttonPrevPage.Enabled = false;
}
private void FormViewMail_Load(object sender, EventArgs e)
{
MailLoad();
}
private bool MailLoad()
{
try
{
var list = _logic.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("Загрузка списка писем");
labelInfoPages.Text = $"{currentPage} страница";
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки писем");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
}
private void ButtonPrevPage_Click(object sender, EventArgs e)
{
if (currentPage == 1)
{
_logger.LogWarning("Неккоректный номер страницы {page}", currentPage - 1);
return;
}
currentPage--;
if (MailLoad())
{
buttonNextPage.Enabled = true;
if (currentPage == 1)
{
buttonPrevPage.Enabled = false;
}
}
}
private void ButtonNextPage_Click(object sender, EventArgs e)
{
currentPage++;
if (!MailLoad() || ((List<MessageInfoViewModel>)dataGridView.DataSource).Count == 0)
{
_logger.LogWarning("Out of range messages");
currentPage--;
MailLoad();
buttonNextPage.Enabled = false;
}
else
{
buttonPrevPage.Enabled = true;
}
}
private void dataGridView_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormReplyMail));
if (service is FormReplyMail form)
{
form.MessageId = (string)dataGridView.Rows[e.RowIndex].Cells["MessageId"].Value;
form.ShowDialog();
MailLoad();
}
}
}
}

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

@ -8,6 +8,8 @@ using PrecastConcretePlantDatabaseImplement.Implements;
using PrecastConcretePlantBusinessLogic.OfficePackage.Implements;
using PrecastConcretePlantBusinessLogic.OfficePackage;
using PrecastConcretePlant;
using PrecastConcretePlantBusinessLogic.MailWorker;
using PrecastConcretePlantContracts.BindingModels;
namespace PrecastConcretePlantView
{
@ -23,6 +25,27 @@ namespace PrecastConcretePlantView
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
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, "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>");
}
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
@ -48,6 +71,8 @@ namespace PrecastConcretePlantView
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
@ -70,7 +95,11 @@ namespace PrecastConcretePlantView
services.AddTransient<FormReportOrder>();
services.AddTransient<FormViewImplementers>();
services.AddTransient<FormImplementer>();
services.AddTransient<FormViewMail>();
services.AddTransient<FormReplyMail>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>();
}
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
}
}

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 PrecastConcretePlantBusinessLogic.BusinessLogic
@ -106,6 +107,15 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
{
throw new ArgumentNullException("Нет логина клиента", nameof(model.Email));
}
if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
{
throw new ArgumentException("Некорретно введенный email", nameof(model.Email));
}
if (!Regex.IsMatch(model.Password, @"^(?=.*\d)(?=.*\W)(?=.*[^\d\s]).+$"))
{
throw new ArgumentException("Некорректно введенный пароль. Пароль должен содержать хотя бы одну букву, цифру и не буквенный символ", nameof(model.Password));
}
_logger.LogInformation("Client. Id: {Id}, FIO: {fio}, email: {email}", model.Id, model.ClientFIO, model.Email);
var element = _clientStorage.GetElement(new ClientSearchModel
{

View File

@ -0,0 +1,68 @@
using Microsoft.Extensions.Logging;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.StoragesContracts;
using PrecastConcretePlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantBusinessLogic.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 bool Create(MessageInfoBindingModel model)
{
if (_messageInfoStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
{
_logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId} ", model?.MessageId, model?.ClientId);
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;
}
public bool Update(MessageInfoBindingModel model)
{
if (_messageInfoStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public MessageInfoViewModel? ReadElement(MessageInfoSearchModel model)
{
var res = _messageInfoStorage.GetElement(model);
if (res == null)
{
_logger.LogWarning("Read element operation failed");
return null;
}
return res;
}
}
}

View File

@ -11,6 +11,7 @@ using PrecastConcretePlantContracts.ViewModels;
using Microsoft.Extensions.Logging;
using PrecastConcretePlantDataModels.Enums;
using DocumentFormat.OpenXml.EMMA;
using PrecastConcretePlantBusinessLogic.MailWorker;
namespace PrecastConcretePlantBusinessLogic.BusinessLogic
{
@ -20,13 +21,17 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
private readonly IOrderStorage _orderStorage;
private readonly IReinforcedStorage _reinforcedStorage;
private readonly IShopLogic _shopLogic;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IReinforcedStorage reinforcedStorage, IShopLogic shopLogic)
private readonly AbstractMailWorker _mailWorker;
private readonly IClientLogic _clientLogic;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IReinforcedStorage reinforcedStorage, IShopLogic shopLogic, AbstractMailWorker mailWorker, IClientLogic clientLogic)
{
_logger = logger;
_shopLogic = shopLogic;
_reinforcedStorage = reinforcedStorage;
_orderStorage = orderStorage;
_mailWorker = mailWorker;
_clientLogic = clientLogic;
}
public bool CreateOrder(OrderBindingModel model)
@ -39,11 +44,13 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
}
model.Status = OrderStatus.Принят;
model.DateCreate = DateTime.Now;
if (_orderStorage.Insert(model) == null)
var result = _orderStorage.Insert(model);
if (result == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
SendOrderStatusMail(result.ClientId, $"Новый заказ создан. Номер заказа #{result.Id}", $"Заказ #{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят");
return true;
}
@ -128,11 +135,13 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
model.ReinforcedId = vmodel.ReinforcedId;
model.Sum = vmodel.Sum;
model.Count = vmodel.Count;
if (_orderStorage.Update(model) == null)
var result = _orderStorage.Update(model);
if (result == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{model.Id} изменен статус на {result.Status}");
return true;
}
@ -152,5 +161,20 @@ namespace PrecastConcretePlantBusinessLogic.BusinessLogic
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
private bool SendOrderStatusMail(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,100 @@
using Microsoft.Extensions.Logging;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantBusinessLogic.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,83 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using MailKit.Net.Pop3;
using MailKit.Security;
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;
namespace PrecastConcretePlantBusinessLogic.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

@ -8,6 +8,7 @@
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.19.0" />
<PackageReference Include="MailKit" Version="4.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>

View File

@ -11,6 +11,8 @@ namespace PrecastConcretePlantClientApp
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,16 +3,19 @@ using PrecastConcretePlantClientApp.Models;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.ViewModels;
using System.Diagnostics;
using System.Text;
namespace PrecastConcretePlantClientApp.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
if (APIClient.Client == null)
@ -21,6 +24,7 @@ namespace PrecastConcretePlantClientApp.Controllers
}
return View(APIClient.GetRequest<List<OrderViewModel>>($"api/main/getorders?clientId={APIClient.Client.Id}"));
}
[HttpGet]
public IActionResult Privacy()
{
@ -30,6 +34,7 @@ namespace PrecastConcretePlantClientApp.Controllers
}
return View(APIClient.Client);
}
[HttpPost]
public void Privacy(string login, string password, string fio)
{
@ -41,32 +46,32 @@ namespace PrecastConcretePlantClientApp.Controllers
{
throw new Exception("Введите логин, пароль и ФИО");
}
APIClient.PostRequest("api/client/updatedata", new
ClientBindingModel
APIClient.PostRequest("api/client/updatedata", new ClientBindingModel
{
Id = APIClient.Client.Id,
ClientFIO = fio,
Email = login,
Password = password
});
APIClient.Client.ClientFIO = fio;
APIClient.Client.Email = login;
APIClient.Client.Password = password;
Response.Redirect("Index");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
});
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[HttpGet]
public IActionResult Enter()
{
return View();
}
[HttpPost]
public void Enter(string login, string password)
{
@ -81,11 +86,13 @@ namespace PrecastConcretePlantClientApp.Controllers
}
Response.Redirect("Index");
}
[HttpGet]
public IActionResult Register()
{
return View();
}
[HttpPost]
public void Register(string login, string password, string fio)
{
@ -102,12 +109,14 @@ namespace PrecastConcretePlantClientApp.Controllers
Response.Redirect("Enter");
return;
}
[HttpGet]
public IActionResult Create()
{
ViewBag.Reinforcedies = APIClient.GetRequest<List<ReinforcedViewModel>>("api/main/getreinforcedlist");
return View();
}
[HttpPost]
public void Create(int reinforced, int count)
{
@ -128,11 +137,59 @@ namespace PrecastConcretePlantClientApp.Controllers
});
Response.Redirect("Index");
}
[HttpPost]
public double Calc(int count, int reinforced)
{
var doc = APIClient.GetRequest<ReinforcedViewModel>($"api/main/getreinforced?reinforcedId={reinforced}");
return count * (doc?.Price ?? 1);
var prod = APIClient.GetRequest<ReinforcedViewModel>($"api/main/getreinforced?reinforcedId={reinforced}");
return count * (prod?.Price ?? 1);
}
[HttpGet]
public IActionResult Mails()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
[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.HasRead ? "Прочитано" : "Непрочитано") + "</td>" +
$"<td>{mail.Reply}</td>" +
"</tr>");
}
return Tuple.Create<string?, string?, bool, bool>(htmlTable.ToString(), APIClient.CurrentPage.ToString(), APIClient.CurrentPage != 1, true);
}
}
}
}

View File

@ -0,0 +1,80 @@
@{
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

@ -7,6 +7,7 @@
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/PrecastConcretePlantClientApp.styles.css" asp-append-version="true" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
</head>
<body>
<header>
@ -25,6 +26,9 @@
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Mails">Письма</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Вход</a>
</li>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantContracts.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,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantContracts.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,26 @@
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantContracts.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 string Subject { get; set; } = string.Empty;
public string Body { get; set; } = string.Empty;
public DateTime DateDelivery { get; set; }
public bool HasRead { get; set; }
public string? Reply { get; set; }
}
}

View File

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

View File

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

View File

@ -0,0 +1,23 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantContracts.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,33 @@
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantContracts.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; }
[DisplayName("Заголовок")]
public string Subject { get; set; } = string.Empty;
[DisplayName("Текст")]
public string Body { get; set; } = string.Empty;
[DisplayName("Прочитано")]
public bool HasRead { get; set; }
[DisplayName("Ответ")]
public string? Reply { get; set; }
}
}

View File

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

View File

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

View File

@ -12,8 +12,8 @@ using PrecastConcretePlantDatabaseImplement;
namespace PrecastConcretePlantDatabaseImplement.Migrations
{
[DbContext(typeof(PrecastConcretePlantDataBase))]
[Migration("20230424164351_lab6hard")]
partial class lab6hard
[Migration("20230503180531_Lab7Hard")]
partial class Lab7Hard
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -97,6 +97,42 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
b.ToTable("Implementers");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.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<bool>("HasRead")
.HasColumnType("bit");
b.Property<string>("Reply")
.HasColumnType("nvarchar(max)");
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("PrecastConcretePlantDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -239,6 +275,15 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
b.ToTable("ShopReinforcedies");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b =>
{
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client")
@ -304,6 +349,8 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});

View File

@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations;
namespace PrecastConcretePlantDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class lab6hard : Migration
public partial class Lab7Hard : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
@ -86,6 +86,29 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
table.PrimaryKey("PK_Shops", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Messages",
columns: table => new
{
MessageId = table.Column<string>(type: "nvarchar(450)", nullable: false),
ClientId = table.Column<int>(type: "int", nullable: true),
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),
HasRead = table.Column<bool>(type: "bit", nullable: false),
Reply = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Messages", x => x.MessageId);
table.ForeignKey(
name: "FK_Messages_Clients_ClientId",
column: x => x.ClientId,
principalTable: "Clients",
principalColumn: "Id");
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
@ -177,6 +200,11 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Messages_ClientId",
table: "Messages",
column: "ClientId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ClientId",
table: "Orders",
@ -216,6 +244,9 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Messages");
migrationBuilder.DropTable(
name: "Orders");

View File

@ -94,6 +94,42 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
b.ToTable("Implementers");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.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<bool>("HasRead")
.HasColumnType("bit");
b.Property<string>("Reply")
.HasColumnType("nvarchar(max)");
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("PrecastConcretePlantDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
@ -236,6 +272,15 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
b.ToTable("ShopReinforcedies");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Order", b =>
{
b.HasOne("PrecastConcretePlantDatabaseImplement.Models.Client", "Client")
@ -301,6 +346,8 @@ namespace PrecastConcretePlantDatabaseImplement.Migrations
modelBuilder.Entity("PrecastConcretePlantDatabaseImplement.Models.Client", b =>
{
b.Navigation("Messages");
b.Navigation("Orders");
});

View File

@ -26,6 +26,8 @@ namespace PrecastConcretePlantDatabaseImplement.Models
[ForeignKey("ClientId")]
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("ClientId")]
public virtual List<MessageInfo> Messages { get; set; } = new();
public static Client? Create(ClientBindingModel model)
{

View File

@ -0,0 +1,75 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantDatabaseImplement.Models
{
public class MessageInfo : IMessageInfoModel
{
[Key]
public string MessageId { get; private set; } = string.Empty;
public int? ClientId { 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 Client? Client { get; private set; }
public bool HasRead { get; private set; }
public string? Reply { get; private set; }
public static MessageInfo? Create(MessageInfoBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Body = model.Body,
Reply = model.Reply,
HasRead = model.HasRead,
Subject = model.Subject,
ClientId = model.ClientId,
MessageId = model.MessageId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
};
}
public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
Reply = model.Reply;
HasRead = model.HasRead;
}
public MessageInfoViewModel GetViewModel => new()
{
Body = Body,
Reply = Reply,
HasRead = HasRead,
Subject = Subject,
ClientId = ClientId,
MessageId = MessageId,
SenderName = SenderName,
DateDelivery = DateDelivery,
};
}
}

View File

@ -1,30 +0,0 @@
using Microsoft.EntityFrameworkCore;
using PrecastConcretePlantDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantDatabaseImplement
{
public class PrecastConcretePlantDataBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-V0ON61E\SQLEXPRESS;Initial Catalog=PrecastConcretePlantDataBaseFullHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Reinforced> Reinforcedies { set; get; }
public virtual DbSet<ReinforcedComponent> ReinforcedComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopReinforced> ShopReinforcedies { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
}
}

View File

@ -0,0 +1,32 @@
using Microsoft.EntityFrameworkCore;
using PrecastConcretePlantDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantDatabaseImplement
{
public class PrecastConcretePlantDataBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=MAKSIM\SQLEXPRESS;Initial Catalog=PrecastConcretePlantDataBaseFullHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Reinforced> Reinforcedies { set; get; }
public virtual DbSet<ReinforcedComponent> ReinforcedComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopReinforced> ShopReinforcedies { set; get; }
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; }
public virtual DbSet<MessageInfo> Messages { set; get; }
}
}

View File

@ -18,6 +18,7 @@ namespace PrecastConcretePlantFileImplement
private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml";
private readonly string ShopFileName = "Shop.xml";
private readonly string MessageInfoFileName = "MessageInfo.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Reinforced> Reinforcedies { get; private set; }
@ -25,6 +26,7 @@ namespace PrecastConcretePlantFileImplement
public List<Implementer> Implementers { get; private set; }
public List<Reinforced> Reinforceds { get; private set; }
public List<Shop> Shops { get; private set; }
public List<MessageInfo> Messages { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
@ -42,6 +44,7 @@ namespace PrecastConcretePlantFileImplement
public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Implementers, ImplementerFileName, "Implementers", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x =>
@ -52,6 +55,7 @@ namespace PrecastConcretePlantFileImplement
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)

View File

@ -0,0 +1,74 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.StoragesContracts;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantFileImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
private readonly DataFileSingleton _source;
public MessageInfoStorage()
{
_source = DataFileSingleton.GetInstance();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
if (model.MessageId != null)
{
return _source.Messages.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel;
}
return null;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
var res = _source.Messages
.Where(x => !model.ClientId.HasValue || x.ClientId == model.ClientId)
.Select(x => x.GetViewModel);
if (!(model.Page.HasValue && model.PageSize.HasValue))
{
return res.ToList();
}
return res.Skip((model.Page.Value - 1) * model.PageSize.Value).Take(model.PageSize.Value).ToList();
}
public List<MessageInfoViewModel> GetFullList()
{
return _source.Messages
.Select(x => x.GetViewModel)
.ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
var newMessage = MessageInfo.Create(model);
if (newMessage == null)
{
return null;
}
_source.Messages.Add(newMessage);
_source.SaveMessages();
return newMessage.GetViewModel;
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
var res = _source.Messages.FirstOrDefault(x => x.MessageId.Equals(model.MessageId));
if (res != null)
{
res.Update(model);
_source.SaveMessages();
}
return res?.GetViewModel;
}
}
}

View File

@ -0,0 +1,101 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace PrecastConcretePlantFileImplement.Models
{
public class MessageInfo : IMessageInfoModel
{
public string MessageId { get; private set; } = string.Empty;
public int? ClientId { 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 bool HasRead { get; private set; }
public string? Reply { get; private set; }
public static MessageInfo? Create(MessageInfoBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Body = model.Body,
Reply = model.Reply,
HasRead = model.HasRead,
Subject = model.Subject,
ClientId = model.ClientId,
MessageId = model.MessageId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
};
}
public static MessageInfo? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
Body = element.Attribute("Body")!.Value,
Reply = element.Attribute("Reply")!.Value,
HasRead = Convert.ToBoolean(element.Attribute("HasRead")!.Value),
Subject = element.Attribute("Subject")!.Value,
ClientId = Convert.ToInt32(element.Attribute("ClientId")!.Value),
MessageId = element.Attribute("MessageId")!.Value,
SenderName = element.Attribute("SenderName")!.Value,
DateDelivery = Convert.ToDateTime(element.Attribute("DateDelivery")!.Value),
};
}
public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
Reply = model.Reply;
HasRead = model.HasRead;
}
public MessageInfoViewModel GetViewModel => new()
{
Body = Body,
Reply = Reply,
HasRead = HasRead,
Subject = Subject,
ClientId = ClientId,
MessageId = MessageId,
SenderName = SenderName,
DateDelivery = DateDelivery,
};
public XElement GetXElement => new("MessageInfo",
new XAttribute("Body", Body),
new XAttribute("Reply", Reply),
new XAttribute("HasRead", HasRead),
new XAttribute("Subject", Subject),
new XAttribute("ClientId", ClientId),
new XAttribute("MessageId", MessageId),
new XAttribute("SenderName", SenderName),
new XAttribute("DateDelivery", DateDelivery)
);
}
}

View File

@ -15,6 +15,7 @@ namespace PrecastConcretePlantListImplement
public List<Reinforced> Reinforcedies { get; set; }
public List<Client> Clients { get; set; }
public List<Implementer> Implementers { get; set; }
public List<MessageInfo> Messages { get; set; }
public List<Reinforced> Reinforceds { get; set; }
public List<Shop> Shops { get; set; }
private DataListSingleton()
@ -24,6 +25,7 @@ namespace PrecastConcretePlantListImplement
Reinforcedies = new List<Reinforced>();
Clients = new List<Client>();
Implementers = new List<Implementer>();
Messages = new List<MessageInfo>();
Reinforceds = new List<Reinforced>();
Shops = new List<Shop>();
}

View File

@ -0,0 +1,93 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.SearchModels;
using PrecastConcretePlantContracts.StoragesContracts;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantListImplement.Implements
{
public class MessageInfoStorage : IMessageInfoStorage
{
private readonly DataListSingleton _source;
public MessageInfoStorage()
{
_source = DataListSingleton.GetInstance();
}
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
foreach (var message in _source.Messages)
{
if (model.MessageId != null && model.MessageId.Equals(message.MessageId))
return message.GetViewModel;
}
return null;
}
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{
List<MessageInfoViewModel> result = new();
foreach (var item in _source.Messages)
{
if (item.ClientId.HasValue && item.ClientId == model.ClientId)
{
result.Add(item.GetViewModel);
}
}
if (!(model.Page.HasValue && model.PageSize.HasValue))
{
return result;
}
if (model.Page * model.PageSize >= result.Count)
{
return null;
}
List<MessageInfoViewModel> filteredResult = new();
for (var i = (model.Page.Value - 1) * model.PageSize.Value; i < model.Page.Value * model.PageSize.Value; i++)
{
filteredResult.Add(result[i]);
}
return filteredResult;
}
public List<MessageInfoViewModel> GetFullList()
{
List<MessageInfoViewModel> result = new();
foreach (var item in _source.Messages)
{
result.Add(item.GetViewModel);
}
return result;
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
var newMessage = MessageInfo.Create(model);
if (newMessage == null)
{
return null;
}
_source.Messages.Add(newMessage);
return newMessage.GetViewModel;
}
public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{
foreach (var message in _source.Messages)
{
if (message.MessageId.Equals(model.MessageId))
{
message.Update(model);
return message.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,70 @@
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.ViewModels;
using PrecastConcretePlantDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrecastConcretePlantListImplement.Models
{
public class MessageInfo : IMessageInfoModel
{
public string MessageId { get; private set; } = string.Empty;
public int? ClientId { 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 bool HasRead { get; private set; }
public string? Reply { get; private set; }
public static MessageInfo? Create(MessageInfoBindingModel model)
{
if (model == null)
{
return null;
}
return new()
{
Body = model.Body,
Reply = model.Reply,
HasRead = model.HasRead,
Subject = model.Subject,
ClientId = model.ClientId,
MessageId = model.MessageId,
SenderName = model.SenderName,
DateDelivery = model.DateDelivery,
};
}
public void Update(MessageInfoBindingModel model)
{
if (model == null)
{
return;
}
Reply = model.Reply;
HasRead = model.HasRead;
}
public MessageInfoViewModel GetViewModel => new()
{
Body = Body,
Reply = Reply,
HasRead = HasRead,
Subject = Subject,
ClientId = ClientId,
MessageId = MessageId,
SenderName = SenderName,
DateDelivery = DateDelivery,
};
}
}

View File

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

View File

@ -1,5 +1,7 @@
using Microsoft.OpenApi.Models;
using PrecastConcretePlantBusinessLogic.BusinessLogic;
using PrecastConcretePlantBusinessLogic.MailWorker;
using PrecastConcretePlantContracts.BindingModels;
using PrecastConcretePlantContracts.BusinessLogicsContracts;
using PrecastConcretePlantContracts.StoragesContracts;
using PrecastConcretePlantDatabaseImplement.Implements;
@ -12,8 +14,12 @@ builder.Logging.AddLog4Net("log4net.config");
builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IReinforcedStorage, ReinforcedStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
builder.Services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
builder.Services.AddTransient<IShopStorage, ShopStorage>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IReinforcedLogic, ReinforcedLogic>();
@ -30,6 +36,17 @@ 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())
});
if (app.Environment.IsDevelopment())
{
app.UseSwagger();

View File

@ -5,5 +5,12 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
"AllowedHosts": "*",
"SmtpClientHost": "smtp.gmail.com",
"SmtpClientPort": "587",
"PopHost": "pop.gmail.com",
"PopPort": "995",
"MailLogin": "lab7kashin@gmail.com",
"MailPassword": "unyh tpno drla wnzo"
}