Revert "фиксик"

This reverts commit 30a05fea30.
This commit is contained in:
Вячеслав Иванов 2024-04-03 10:29:36 +04:00
parent 30a05fea30
commit 26dda0e2b2
10 changed files with 1057 additions and 1048 deletions

View File

@ -8,113 +8,113 @@ using System.Text.RegularExpressions;
namespace PizzeriaBusinessLogic.BusinessLogics namespace PizzeriaBusinessLogic.BusinessLogics
{ {
public class ClientLogic : IClientLogic public class ClientLogic : IClientLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IClientStorage _clientStorage; private readonly IClientStorage _clientStorage;
public ClientLogic(ILogger<ClientLogic> logger, IClientStorage clientStorage) public ClientLogic(ILogger<ClientLogic> logger, IClientStorage clientStorage)
{ {
_logger = logger; _logger = logger;
_clientStorage = clientStorage; _clientStorage = clientStorage;
} }
public List<ClientViewModel>? ReadList(ClientSearchModel? model) public List<ClientViewModel>? ReadList(ClientSearchModel? model)
{ {
_logger.LogInformation("ReadList. ClientId:{Id}", model?.Id); _logger.LogInformation("ReadList. ClientId:{Id}", model?.Id);
var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model); var list = model == null ? _clientStorage.GetFullList() : _clientStorage.GetFilteredList(model);
if (list == null) if (list == null)
{ {
_logger.LogWarning("ReadList return null list"); _logger.LogWarning("ReadList return null list");
return null; return null;
} }
_logger.LogInformation("ReadList. Count:{Count}", list.Count); _logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list; return list;
} }
public ClientViewModel? ReadElement(ClientSearchModel model) public ClientViewModel? ReadElement(ClientSearchModel model)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
_logger.LogInformation("ReadElement. ClientFio:{ClientFio}.Id:{ Id}", model.ClientFIO, model.Id); _logger.LogInformation("ReadElement. ClientFio:{ClientFio}.Id:{ Id}", model.ClientFIO, model.Id);
var element = _clientStorage.GetElement(model); var element = _clientStorage.GetElement(model);
if (element == null) if (element == null)
{ {
_logger.LogWarning("ReadElement element not found"); _logger.LogWarning("ReadElement element not found");
return null; return null;
} }
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id); _logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element; return element;
} }
public bool Create(ClientBindingModel model) public bool Create(ClientBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (_clientStorage.Insert(model) == null) if (_clientStorage.Insert(model) == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
return false; return false;
} }
return true; return true;
} }
public bool Update(ClientBindingModel model) public bool Update(ClientBindingModel model)
{ {
CheckModel(model); CheckModel(model);
if (_clientStorage.Update(model) == null) if (_clientStorage.Update(model) == null)
{ {
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
return true; return true;
} }
public bool Delete(ClientBindingModel model) public bool Delete(ClientBindingModel model)
{ {
CheckModel(model, false); CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id); _logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_clientStorage.Delete(model) == null) if (_clientStorage.Delete(model) == null)
{ {
_logger.LogWarning("Delete operation failed"); _logger.LogWarning("Delete operation failed");
return false; return false;
} }
return true; return true;
} }
private void CheckModel(ClientBindingModel model, bool withParams = true) private void CheckModel(ClientBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
if (!withParams) if (!withParams)
{ {
return; return;
} }
if (string.IsNullOrEmpty(model.ClientFIO)) if (string.IsNullOrEmpty(model.ClientFIO))
{ {
throw new ArgumentNullException("Нет ФИО пользователя", nameof(model.ClientFIO)); throw new ArgumentNullException("Нет ФИО пользователя", nameof(model.ClientFIO));
} }
if (string.IsNullOrEmpty(model.Email) || !Regex.IsMatch(model.Email, @"^[a-z0-9._%+-]+\@([a-z0-9-]+\.)+[a-z]{2,4}$")) if (string.IsNullOrEmpty(model.Email) || !Regex.IsMatch(model.Email, @"^[a-z0-9._%+-]+\@([a-z0-9-]+\.)+[a-z]{2,4}$"))
{ {
throw new ArgumentNullException("Не указана валидная почта", nameof(model.Email)); throw new ArgumentNullException("Не указана валидная почта", nameof(model.Email));
} }
if (string.IsNullOrEmpty(model.Password) || !Regex.IsMatch(model.Password, @"^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z0-9\n]).{10,50}$")) if (string.IsNullOrEmpty(model.Password) || !Regex.IsMatch(model.Password, @"^(?=.*[A-Za-z])(?=.*\d)(?=.*[^A-Za-z0-9\n]).{10,50}$"))
{ {
throw new ArgumentNullException("Не указан правильный пароль", nameof(model.Password)); throw new ArgumentNullException("Не указан правильный пароль", nameof(model.Password));
} }
_logger.LogInformation("Client. ClientFIO:{ClientFIO}.Email:{Email}.Id:{Id}", _logger.LogInformation("Client. ClientFIO:{ClientFIO}.Email:{Email}.Id:{Id}",
model.ClientFIO, model.Email, model.Id); model.ClientFIO, model.Email, model.Id);
var element = _clientStorage.GetElement(new ClientSearchModel var element = _clientStorage.GetElement(new ClientSearchModel
{ {
ClientFIO = model.ClientFIO ClientFIO = model.ClientFIO
}); });
if (element != null && element.Id != model.Id) if (element != null && element.Id != model.Id)
{ {
throw new InvalidOperationException("Клиент с таким именем уже есть"); throw new InvalidOperationException("Клиент с таким именем уже есть");
} }
} }
} }
} }

View File

@ -12,111 +12,111 @@ using System.Threading.Tasks;
namespace PizzeriaBusinessLogic.BusinessLogics namespace PizzeriaBusinessLogic.BusinessLogics
{ {
public class MessageInfoLogic : IMessageInfoLogic public class MessageInfoLogic : IMessageInfoLogic
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IMessageInfoStorage _messageInfoStorage; private readonly IMessageInfoStorage _messageInfoStorage;
private readonly IClientStorage _clientStorage; private readonly IClientStorage _clientStorage;
public MessageInfoLogic(ILogger<MessageInfoLogic> logger, IMessageInfoStorage messageInfoStorage, IClientStorage clientStorage) public MessageInfoLogic(ILogger<MessageInfoLogic> logger, IMessageInfoStorage messageInfoStorage, IClientStorage clientStorage)
{ {
_logger = logger; _logger = logger;
_messageInfoStorage = messageInfoStorage; _messageInfoStorage = messageInfoStorage;
_clientStorage = clientStorage; _clientStorage = clientStorage;
} }
public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model) public List<MessageInfoViewModel>? ReadList(MessageInfoSearchModel? model)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
_logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId}.PageLength:{PageLength}.PageCount:{PageIndex}", model?.MessageId, model?.ClientId, model?.PageLength, model?.PageIndex); _logger.LogInformation("ReadList. MessageId:{MessageId}.ClientId:{ClientId}.PageLength:{PageLength}.PageCount:{PageIndex}", model?.MessageId, model?.ClientId, model?.PageLength, model?.PageIndex);
var list = _messageInfoStorage.GetFilteredList(model); var list = _messageInfoStorage.GetFilteredList(model);
if (list == null) if (list == null)
{ {
_logger.LogWarning("ReadList return null list"); _logger.LogWarning("ReadList return null list");
return null; return null;
} }
_logger.LogInformation("ReadList. Count:{Count}", list.Count); _logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list; return list;
} }
public bool Create(MessageInfoBindingModel model) public bool Create(MessageInfoBindingModel model)
{ {
CheckModel(model); CheckModel(model);
var message = _messageInfoStorage.Insert(model); var message = _messageInfoStorage.Insert(model);
if (message == null) if (message == null)
{ {
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
return false; return false;
} }
return true; return true;
} }
private void CheckModel(MessageInfoBindingModel model, bool withParams = true) private void CheckModel(MessageInfoBindingModel model, bool withParams = true)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
if (string.IsNullOrEmpty(model.MessageId)) if (string.IsNullOrEmpty(model.MessageId))
{ {
throw new ArgumentNullException("Не указан id сообщения", nameof(model.MessageId)); throw new ArgumentNullException("Не указан id сообщения", nameof(model.MessageId));
} }
if (!withParams) if (!withParams)
{ {
return; return;
} }
if (string.IsNullOrEmpty(model.SenderName)) if (string.IsNullOrEmpty(model.SenderName))
{ {
throw new ArgumentNullException("Не указао имя отправителя(электронная почта)", nameof(model.SenderName)); throw new ArgumentNullException("Не указао имя отправителя(электронная почта)", nameof(model.SenderName));
} }
if (string.IsNullOrEmpty(model.Subject)) if (string.IsNullOrEmpty(model.Subject))
{ {
throw new ArgumentNullException("Не указана темма", nameof(model.Subject)); throw new ArgumentNullException("Не указана темма", nameof(model.Subject));
} }
if (string.IsNullOrEmpty(model.Body)) if (string.IsNullOrEmpty(model.Body))
{ {
throw new ArgumentNullException("Не указан текст сообщения", nameof(model.Subject)); throw new ArgumentNullException("Не указан текст сообщения", nameof(model.Subject));
} }
_logger.LogInformation("MessageInfo. MessageId:{MessageId}.SenderName:{SenderName}.Subject:{Subject}.Body:{Body}", model.MessageId, model.SenderName, model.Subject, model.Body); _logger.LogInformation("MessageInfo. MessageId:{MessageId}.SenderName:{SenderName}.Subject:{Subject}.Body:{Body}", model.MessageId, model.SenderName, model.Subject, model.Body);
var element = _clientStorage.GetElement(new ClientSearchModel var element = _clientStorage.GetElement(new ClientSearchModel
{ {
Email = model.SenderName Email = model.SenderName
}); });
if (element == null) if (element == null)
{ {
_logger.LogWarning("Не удалоссь найти клиента, отправившего письмо с адреса Email:{Email}", model.SenderName); _logger.LogWarning("Не удалоссь найти клиента, отправившего письмо с адреса Email:{Email}", model.SenderName);
} }
else else
{ {
model.ClientId = element.Id; model.ClientId = element.Id;
} }
} }
public MessageInfoViewModel? ReadElement(MessageInfoSearchModel model) public MessageInfoViewModel? ReadElement(MessageInfoSearchModel model)
{ {
if (model == null) if (model == null)
{ {
throw new ArgumentNullException(nameof(model)); throw new ArgumentNullException(nameof(model));
} }
_logger.LogInformation("ReadElement. MessageId:{MessageId}", model?.MessageId); _logger.LogInformation("ReadElement. MessageId:{MessageId}", model?.MessageId);
var element = _messageInfoStorage.GetElement(model); var element = _messageInfoStorage.GetElement(model);
if (element == null) if (element == null)
{ {
_logger.LogWarning("ReadElement element not found"); _logger.LogWarning("ReadElement element not found");
return null; return null;
} }
_logger.LogInformation("ReadElement find. Id:{Id}", element.MessageId); _logger.LogInformation("ReadElement find. Id:{Id}", element.MessageId);
return element; return element;
} }
public bool Update(MessageInfoBindingModel model) public bool Update(MessageInfoBindingModel model)
{ {
CheckModel(model, withParams: false); CheckModel(model, withParams: false);
if (_messageInfoStorage.Update(model) == null) if (_messageInfoStorage.Update(model) == null)
{ {
_logger.LogWarning("Update operation failed"); _logger.LogWarning("Update operation failed");
return false; return false;
} }
return true; return true;
} }
} }
} }

View File

@ -9,121 +9,121 @@ using System.Threading.Tasks;
namespace PizzeriaBusinessLogic.MailWorker namespace PizzeriaBusinessLogic.MailWorker
{ {
public abstract class AbstractMailWorker public abstract class AbstractMailWorker
{ {
protected string _mailLogin = string.Empty; protected string _mailLogin = string.Empty;
protected string _mailPassword = string.Empty; protected string _mailPassword = string.Empty;
protected string _smtpClientHost = string.Empty; protected string _smtpClientHost = string.Empty;
protected int _smtpClientPort; protected int _smtpClientPort;
protected string _popHost = string.Empty; protected string _popHost = string.Empty;
protected int _popPort; protected int _popPort;
private readonly IMessageInfoLogic _messageInfoLogic; private readonly IMessageInfoLogic _messageInfoLogic;
private readonly ILogger _logger; private readonly ILogger _logger;
public AbstractMailWorker(ILogger<AbstractMailWorker> logger, IMessageInfoLogic messageInfoLogic) public AbstractMailWorker(ILogger<AbstractMailWorker> logger, IMessageInfoLogic messageInfoLogic)
{ {
_logger = logger; _logger = logger;
_messageInfoLogic = messageInfoLogic; _messageInfoLogic = messageInfoLogic;
} }
public void MailConfig(MailConfigBindingModel config) public void MailConfig(MailConfigBindingModel config)
{ {
_mailLogin = config.MailLogin; _mailLogin = config.MailLogin;
_mailPassword = config.MailPassword; _mailPassword = config.MailPassword;
_smtpClientHost = config.SmtpClientHost; _smtpClientHost = config.SmtpClientHost;
_smtpClientPort = config.SmtpClientPort; _smtpClientPort = config.SmtpClientPort;
_popHost = config.PopHost; _popHost = config.PopHost;
_popPort = config.PopPort; _popPort = config.PopPort;
_logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword.Length, _smtpClientHost, _smtpClientPort, _popHost, _popPort); _logger.LogDebug("Config: {login}, {password}, {clientHost}, {clientPOrt}, {popHost}, {popPort}", _mailLogin, _mailPassword.Length, _smtpClientHost, _smtpClientPort, _popHost, _popPort);
} }
public async void MailSendAsync(MailSendInfoBindingModel info) public async void MailSendAsync(MailSendInfoBindingModel info)
{ {
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{ {
return; return;
} }
if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
{ {
return; return;
} }
if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text)) if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text))
{ {
return; return;
} }
_logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject); _logger.LogDebug("Send Mail: {To}, {Subject}", info.MailAddress, info.Subject);
await SendMailAsync(info); await SendMailAsync(info);
} }
public async void MailCheck() public async void MailCheck()
{ {
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{ {
return; return;
} }
if (string.IsNullOrEmpty(_popHost) || _popPort == 0) if (string.IsNullOrEmpty(_popHost) || _popPort == 0)
{ {
return; return;
} }
if (_messageInfoLogic == null) if (_messageInfoLogic == null)
{ {
return; return;
} }
var list = await ReceiveMailAsync(); var list = await ReceiveMailAsync();
_logger.LogDebug("Check Mail: {Count} new mails", list.Count); _logger.LogDebug("Check Mail: {Count} new mails", list.Count);
foreach (var mail in list) foreach (var mail in list)
{ {
_messageInfoLogic.Create(mail); _messageInfoLogic.Create(mail);
} }
} }
public async void MailSendReplyAsync(MailReplySendInfoBindingModel info) public async void MailSendReplyAsync(MailReplySendInfoBindingModel info)
{ {
if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword)) if (string.IsNullOrEmpty(_mailLogin) || string.IsNullOrEmpty(_mailPassword))
{ {
return; return;
} }
if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0) if (string.IsNullOrEmpty(_smtpClientHost) || _smtpClientPort == 0)
{ {
return; return;
} }
if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text) || string.IsNullOrEmpty(info.ParentMessageId)) if (string.IsNullOrEmpty(info.MailAddress) || string.IsNullOrEmpty(info.Subject) || string.IsNullOrEmpty(info.Text) || string.IsNullOrEmpty(info.ParentMessageId))
{ {
return; return;
} }
_logger.LogDebug("Send Mail as reply: {To}, {Subject}, {parentId}", info.MailAddress, info.Subject, info.ParentMessageId); _logger.LogDebug("Send Mail as reply: {To}, {Subject}, {parentId}", info.MailAddress, info.Subject, info.ParentMessageId);
string? messageId = await SendMailAsync(info); string? messageId = await SendMailAsync(info);
if (string.IsNullOrEmpty(messageId)) if (string.IsNullOrEmpty(messageId))
{ {
throw new InvalidOperationException("Непредвиденная ошибка при отправке сообщения в ответ"); throw new InvalidOperationException("Непредвиденная ошибка при отправке сообщения в ответ");
} }
if (_messageInfoLogic.Create(new MessageInfoBindingModel if (_messageInfoLogic.Create(new MessageInfoBindingModel
{ {
MessageId = messageId, MessageId = messageId,
DateDelivery = DateTime.Now, DateDelivery = DateTime.Now,
SenderName = _mailLogin, SenderName = _mailLogin,
IsReply = true, IsReply = true,
Subject = info.Subject, Subject = info.Subject,
Body = info.Text, Body = info.Text,
})) }))
{ {
_messageInfoLogic.Update(new MessageInfoBindingModel() _messageInfoLogic.Update(new MessageInfoBindingModel()
{ {
MessageId = info.ParentMessageId, MessageId = info.ParentMessageId,
ReplyMessageId = messageId, ReplyMessageId = messageId,
IsReaded = true IsReaded = true
}); });
} }
} }
protected abstract Task<string?> SendMailAsync(MailSendInfoBindingModel info); protected abstract Task<string?> SendMailAsync(MailSendInfoBindingModel info);
protected abstract Task<List<MessageInfoBindingModel>> ReceiveMailAsync(); protected abstract Task<List<MessageInfoBindingModel>> ReceiveMailAsync();
} }
} }

View File

@ -13,92 +13,92 @@ using System.Threading.Tasks;
namespace PizzeriaBusinessLogic.MailWorker namespace PizzeriaBusinessLogic.MailWorker
{ {
public class MailKitWorker : AbstractMailWorker public class MailKitWorker : AbstractMailWorker
{ {
public MailKitWorker(ILogger<MailKitWorker> logger, IMessageInfoLogic messageInfoLogic) : base(logger, messageInfoLogic) { } public MailKitWorker(ILogger<MailKitWorker> logger, IMessageInfoLogic messageInfoLogic) : base(logger, messageInfoLogic) { }
protected override async Task<string?> SendMailAsync(MailSendInfoBindingModel info) protected override async Task<string?> SendMailAsync(MailSendInfoBindingModel info)
{ {
string? resount = null; string? resount = null;
using var objMailMessage = new MailMessage(); using var objMailMessage = new MailMessage();
using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort); using var objSmtpClient = new SmtpClient(_smtpClientHost, _smtpClientPort);
try try
{ {
ConfigurateSmtpClient(objSmtpClient); ConfigurateSmtpClient(objSmtpClient);
CreateMessage(objMailMessage, info); CreateMessage(objMailMessage, info);
if (info is MailReplySendInfoBindingModel replyInfo) if (info is MailReplySendInfoBindingModel replyInfo)
{ {
objMailMessage.Headers.Add("In-Reply-To", replyInfo.ParentMessageId); objMailMessage.Headers.Add("In-Reply-To", replyInfo.ParentMessageId);
objMailMessage.Headers.Add("References", replyInfo.ParentMessageId); objMailMessage.Headers.Add("References", replyInfo.ParentMessageId);
string messageGuid = Guid.NewGuid().ToString(); string messageGuid = Guid.NewGuid().ToString();
objMailMessage.Headers.Add("Message-Id", messageGuid); objMailMessage.Headers.Add("Message-Id", messageGuid);
resount = messageGuid; resount = messageGuid;
} }
await Task.Run(() => objSmtpClient.Send(objMailMessage)); await Task.Run(() => objSmtpClient.Send(objMailMessage));
} }
catch (Exception) catch (Exception)
{ {
throw; throw;
} }
return resount; return resount;
} }
protected override async Task<List<MessageInfoBindingModel>> ReceiveMailAsync() protected override async Task<List<MessageInfoBindingModel>> ReceiveMailAsync()
{ {
var list = new List<MessageInfoBindingModel>(); var list = new List<MessageInfoBindingModel>();
using var client = new Pop3Client(); using var client = new Pop3Client();
await Task.Run(() => await Task.Run(() =>
{ {
try try
{ {
client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect); client.Connect(_popHost, _popPort, SecureSocketOptions.SslOnConnect);
client.Authenticate(_mailLogin, _mailPassword); client.Authenticate(_mailLogin, _mailPassword);
for (int i = 0; i < client.Count; i++) for (int i = 0; i < client.Count; i++)
{ {
var message = client.GetMessage(i); var message = client.GetMessage(i);
foreach (var mail in message.From.Mailboxes) foreach (var mail in message.From.Mailboxes)
{ {
list.Add(new MessageInfoBindingModel list.Add(new MessageInfoBindingModel
{ {
DateDelivery = message.Date.DateTime, DateDelivery = message.Date.DateTime,
MessageId = message.MessageId, MessageId = message.MessageId,
SenderName = mail.Address, SenderName = mail.Address,
Subject = message.Subject, Subject = message.Subject,
Body = message.TextBody Body = message.TextBody
}); });
} }
} }
} }
catch (MailKit.Security.AuthenticationException) catch (MailKit.Security.AuthenticationException)
{ } { }
finally finally
{ {
client.Disconnect(true); client.Disconnect(true);
} }
}); });
return list; return list;
} }
private void CreateMessage(MailMessage objMailMessage, MailSendInfoBindingModel info) private void CreateMessage(MailMessage objMailMessage, MailSendInfoBindingModel info)
{ {
objMailMessage.From = new MailAddress(_mailLogin); objMailMessage.From = new MailAddress(_mailLogin);
objMailMessage.To.Add(new MailAddress(info.MailAddress)); objMailMessage.To.Add(new MailAddress(info.MailAddress));
objMailMessage.Subject = info.Subject; objMailMessage.Subject = info.Subject;
objMailMessage.Body = info.Text; objMailMessage.Body = info.Text;
objMailMessage.SubjectEncoding = Encoding.UTF8; objMailMessage.SubjectEncoding = Encoding.UTF8;
objMailMessage.BodyEncoding = Encoding.UTF8; objMailMessage.BodyEncoding = Encoding.UTF8;
} }
private void ConfigurateSmtpClient(SmtpClient objSmtpClient) private void ConfigurateSmtpClient(SmtpClient objSmtpClient)
{ {
objSmtpClient.UseDefaultCredentials = false; objSmtpClient.UseDefaultCredentials = false;
objSmtpClient.EnableSsl = true; objSmtpClient.EnableSsl = true;
objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; objSmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword); objSmtpClient.Credentials = new NetworkCredential(_mailLogin, _mailPassword);
} }
} }
} }

View File

@ -11,72 +11,72 @@ using System.Threading.Tasks;
namespace PizzeriaDatabaseImplement.Implements namespace PizzeriaDatabaseImplement.Implements
{ {
public class MessageInfoStorage : IMessageInfoStorage public class MessageInfoStorage : IMessageInfoStorage
{ {
public List<MessageInfoViewModel> GetFullList() public List<MessageInfoViewModel> GetFullList()
{ {
using var context = new PizzeriaDatabase(); using var context = new PizzeriaDatabase();
return context.MessageInfos.Select(x => x.GetViewModel).ToList(); return context.MessageInfos.Select(x => x.GetViewModel).ToList();
} }
public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model) public List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model)
{ {
if (!model.ClientId.HasValue && !model.PageLength.HasValue && !model.PageIndex.HasValue) if (!model.ClientId.HasValue && !model.PageLength.HasValue && !model.PageIndex.HasValue)
{ {
return new(); return new();
} }
using var context = new PizzeriaDatabase(); using var context = new PizzeriaDatabase();
IEnumerable<MessageInfo> request = context.MessageInfos.Where(x => !x.IsReply); IEnumerable<MessageInfo> request = context.MessageInfos.Where(x => !x.IsReply);
if (model.ClientId.HasValue) if (model.ClientId.HasValue)
request = request.Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId); request = request.Where(x => x.ClientId.HasValue && x.ClientId == model.ClientId);
if (model.PageLength.HasValue) if (model.PageLength.HasValue)
{ {
int skipRows = model.PageIndex.HasValue ? (model.PageIndex.Value - 1) * model.PageLength.Value : 0; int skipRows = model.PageIndex.HasValue ? (model.PageIndex.Value - 1) * model.PageLength.Value : 0;
request = request.Skip(skipRows).Take(model.PageLength.Value); request = request.Skip(skipRows).Take(model.PageLength.Value);
} }
return request.Select(x => x.GetViewModel).ToList(); return request.Select(x => x.GetViewModel).ToList();
} }
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model) public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{ {
if (string.IsNullOrEmpty(model.MessageId)) if (string.IsNullOrEmpty(model.MessageId))
{ {
return new(); return new();
} }
using var context = new PizzeriaDatabase(); using var context = new PizzeriaDatabase();
return context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel; return context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId)?.GetViewModel;
} }
public MessageInfoViewModel? Insert(MessageInfoBindingModel model) public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{ {
var newMessage = MessageInfo.Create(model); var newMessage = MessageInfo.Create(model);
if (newMessage == null) if (newMessage == null)
{ {
return null; return null;
} }
using var context = new PizzeriaDatabase(); using var context = new PizzeriaDatabase();
try try
{ {
context.MessageInfos.Add(newMessage); context.MessageInfos.Add(newMessage);
context.SaveChanges(); context.SaveChanges();
return newMessage.GetViewModel; return newMessage.GetViewModel;
} }
catch (Exception ex) catch (Exception ex)
{ {
return null; return null;
} }
} }
public MessageInfoViewModel? Update(MessageInfoBindingModel model) public MessageInfoViewModel? Update(MessageInfoBindingModel model)
{ {
using var context = new PizzeriaDatabase(); using var context = new PizzeriaDatabase();
var message = context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId); var message = context.MessageInfos.FirstOrDefault(x => x.MessageId == model.MessageId);
if (message == null) if (message == null)
{ {
return null; return null;
} }
message.Update(context, model); message.Update(context, model);
context.SaveChanges(); context.SaveChanges();
return message.GetViewModel; return message.GetViewModel;
} }
} }
} }

View File

@ -1,182 +1,182 @@
namespace PizzeriaView namespace PizzeriaView
{ {
partial class FormLetter partial class FormLetter
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.textBoxEmail = new System.Windows.Forms.TextBox(); this.textBoxEmail = new System.Windows.Forms.TextBox();
this.labelAdress = new System.Windows.Forms.Label(); this.labelAdress = new System.Windows.Forms.Label();
this.labelSubject = new System.Windows.Forms.Label(); this.labelSubject = new System.Windows.Forms.Label();
this.textBoxSubject = new System.Windows.Forms.TextBox(); this.textBoxSubject = new System.Windows.Forms.TextBox();
this.labelBody = new System.Windows.Forms.Label(); this.labelBody = new System.Windows.Forms.Label();
this.textBoxBody = new System.Windows.Forms.TextBox(); this.textBoxBody = new System.Windows.Forms.TextBox();
this.buttonClose = new System.Windows.Forms.Button(); this.buttonClose = new System.Windows.Forms.Button();
this.buttonReply = new System.Windows.Forms.Button(); this.buttonReply = new System.Windows.Forms.Button();
this.labelDate = new System.Windows.Forms.Label(); this.labelDate = new System.Windows.Forms.Label();
this.textBoxDate = new System.Windows.Forms.TextBox(); this.textBoxDate = new System.Windows.Forms.TextBox();
this.buttonSend = new System.Windows.Forms.Button(); this.buttonSend = new System.Windows.Forms.Button();
this.SuspendLayout(); this.SuspendLayout();
// //
// textBoxEmail // textBoxEmail
// //
this.textBoxEmail.Location = new System.Drawing.Point(72, 6); this.textBoxEmail.Location = new System.Drawing.Point(72, 6);
this.textBoxEmail.Name = "textBoxEmail"; this.textBoxEmail.Name = "textBoxEmail";
this.textBoxEmail.ReadOnly = true; this.textBoxEmail.ReadOnly = true;
this.textBoxEmail.Size = new System.Drawing.Size(186, 27); this.textBoxEmail.Size = new System.Drawing.Size(186, 27);
this.textBoxEmail.TabIndex = 0; this.textBoxEmail.TabIndex = 0;
// //
// labelAdress // labelAdress
// //
this.labelAdress.AutoSize = true; this.labelAdress.AutoSize = true;
this.labelAdress.Location = new System.Drawing.Point(12, 9); this.labelAdress.Location = new System.Drawing.Point(12, 9);
this.labelAdress.Name = "labelAdress"; this.labelAdress.Name = "labelAdress";
this.labelAdress.Size = new System.Drawing.Size(54, 20); this.labelAdress.Size = new System.Drawing.Size(54, 20);
this.labelAdress.TabIndex = 1; this.labelAdress.TabIndex = 1;
this.labelAdress.Text = "Адрес:"; this.labelAdress.Text = "Адрес:";
// //
// labelSubject // labelSubject
// //
this.labelSubject.AutoSize = true; this.labelSubject.AutoSize = true;
this.labelSubject.Location = new System.Drawing.Point(12, 55); this.labelSubject.Location = new System.Drawing.Point(12, 55);
this.labelSubject.Name = "labelSubject"; this.labelSubject.Name = "labelSubject";
this.labelSubject.Size = new System.Drawing.Size(47, 20); this.labelSubject.Size = new System.Drawing.Size(47, 20);
this.labelSubject.TabIndex = 2; this.labelSubject.TabIndex = 2;
this.labelSubject.Text = "Тема:"; this.labelSubject.Text = "Тема:";
// //
// textBoxSubject // textBoxSubject
// //
this.textBoxSubject.Location = new System.Drawing.Point(72, 52); this.textBoxSubject.Location = new System.Drawing.Point(72, 52);
this.textBoxSubject.Name = "textBoxSubject"; this.textBoxSubject.Name = "textBoxSubject";
this.textBoxSubject.ReadOnly = true; this.textBoxSubject.ReadOnly = true;
this.textBoxSubject.Size = new System.Drawing.Size(552, 27); this.textBoxSubject.Size = new System.Drawing.Size(552, 27);
this.textBoxSubject.TabIndex = 3; this.textBoxSubject.TabIndex = 3;
// //
// labelBody // labelBody
// //
this.labelBody.AutoSize = true; this.labelBody.AutoSize = true;
this.labelBody.Location = new System.Drawing.Point(12, 96); this.labelBody.Location = new System.Drawing.Point(12, 96);
this.labelBody.Name = "labelBody"; this.labelBody.Name = "labelBody";
this.labelBody.Size = new System.Drawing.Size(104, 20); this.labelBody.Size = new System.Drawing.Size(104, 20);
this.labelBody.TabIndex = 4; this.labelBody.TabIndex = 4;
this.labelBody.Text = "Текст письма:"; this.labelBody.Text = "Текст письма:";
// //
// textBoxBody // textBoxBody
// //
this.textBoxBody.Location = new System.Drawing.Point(12, 119); this.textBoxBody.Location = new System.Drawing.Point(12, 119);
this.textBoxBody.Multiline = true; this.textBoxBody.Multiline = true;
this.textBoxBody.Name = "textBoxBody"; this.textBoxBody.Name = "textBoxBody";
this.textBoxBody.ReadOnly = true; this.textBoxBody.ReadOnly = true;
this.textBoxBody.Size = new System.Drawing.Size(612, 186); this.textBoxBody.Size = new System.Drawing.Size(612, 186);
this.textBoxBody.TabIndex = 5; this.textBoxBody.TabIndex = 5;
// //
// buttonClose // buttonClose
// //
this.buttonClose.Location = new System.Drawing.Point(491, 326); this.buttonClose.Location = new System.Drawing.Point(491, 326);
this.buttonClose.Name = "buttonClose"; this.buttonClose.Name = "buttonClose";
this.buttonClose.Size = new System.Drawing.Size(111, 39); this.buttonClose.Size = new System.Drawing.Size(111, 39);
this.buttonClose.TabIndex = 6; this.buttonClose.TabIndex = 6;
this.buttonClose.Text = "Закрыть"; this.buttonClose.Text = "Закрыть";
this.buttonClose.UseVisualStyleBackColor = true; this.buttonClose.UseVisualStyleBackColor = true;
this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click); this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
// //
// buttonReply // buttonReply
// //
this.buttonReply.Location = new System.Drawing.Point(290, 326); this.buttonReply.Location = new System.Drawing.Point(290, 326);
this.buttonReply.Name = "buttonReply"; this.buttonReply.Name = "buttonReply";
this.buttonReply.Size = new System.Drawing.Size(177, 39); this.buttonReply.Size = new System.Drawing.Size(177, 39);
this.buttonReply.TabIndex = 7; this.buttonReply.TabIndex = 7;
this.buttonReply.Text = "Ответить"; this.buttonReply.Text = "Ответить";
this.buttonReply.UseVisualStyleBackColor = true; this.buttonReply.UseVisualStyleBackColor = true;
this.buttonReply.Click += new System.EventHandler(this.buttonReply_Click); this.buttonReply.Click += new System.EventHandler(this.buttonReply_Click);
// //
// labelDate // labelDate
// //
this.labelDate.AutoSize = true; this.labelDate.AutoSize = true;
this.labelDate.Location = new System.Drawing.Point(278, 9); this.labelDate.Location = new System.Drawing.Point(278, 9);
this.labelDate.Name = "labelDate"; this.labelDate.Name = "labelDate";
this.labelDate.Size = new System.Drawing.Size(127, 20); this.labelDate.Size = new System.Drawing.Size(127, 20);
this.labelDate.TabIndex = 8; this.labelDate.TabIndex = 8;
this.labelDate.Text = "Дата получения: "; this.labelDate.Text = "Дата получения: ";
// //
// textBoxDate // textBoxDate
// //
this.textBoxDate.Location = new System.Drawing.Point(411, 6); this.textBoxDate.Location = new System.Drawing.Point(411, 6);
this.textBoxDate.Name = "textBoxDate"; this.textBoxDate.Name = "textBoxDate";
this.textBoxDate.ReadOnly = true; this.textBoxDate.ReadOnly = true;
this.textBoxDate.Size = new System.Drawing.Size(213, 27); this.textBoxDate.Size = new System.Drawing.Size(213, 27);
this.textBoxDate.TabIndex = 9; this.textBoxDate.TabIndex = 9;
// //
// buttonSend // buttonSend
// //
this.buttonSend.Location = new System.Drawing.Point(149, 326); this.buttonSend.Location = new System.Drawing.Point(149, 326);
this.buttonSend.Name = "buttonSend"; this.buttonSend.Name = "buttonSend";
this.buttonSend.Size = new System.Drawing.Size(109, 39); this.buttonSend.Size = new System.Drawing.Size(109, 39);
this.buttonSend.TabIndex = 10; this.buttonSend.TabIndex = 10;
this.buttonSend.Text = "Отправить"; this.buttonSend.Text = "Отправить";
this.buttonSend.UseVisualStyleBackColor = true; this.buttonSend.UseVisualStyleBackColor = true;
this.buttonSend.Visible = false; this.buttonSend.Visible = false;
this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click); this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click);
// //
// FormLetter // FormLetter
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(636, 377); this.ClientSize = new System.Drawing.Size(636, 377);
this.Controls.Add(this.buttonSend); this.Controls.Add(this.buttonSend);
this.Controls.Add(this.textBoxDate); this.Controls.Add(this.textBoxDate);
this.Controls.Add(this.labelDate); this.Controls.Add(this.labelDate);
this.Controls.Add(this.buttonReply); this.Controls.Add(this.buttonReply);
this.Controls.Add(this.buttonClose); this.Controls.Add(this.buttonClose);
this.Controls.Add(this.textBoxBody); this.Controls.Add(this.textBoxBody);
this.Controls.Add(this.labelBody); this.Controls.Add(this.labelBody);
this.Controls.Add(this.textBoxSubject); this.Controls.Add(this.textBoxSubject);
this.Controls.Add(this.labelSubject); this.Controls.Add(this.labelSubject);
this.Controls.Add(this.labelAdress); this.Controls.Add(this.labelAdress);
this.Controls.Add(this.textBoxEmail); this.Controls.Add(this.textBoxEmail);
this.Name = "FormLetter"; this.Name = "FormLetter";
this.Text = "Письмо"; this.Text = "Письмо";
this.Load += new System.EventHandler(this.FormLetter_Load); this.Load += new System.EventHandler(this.FormLetter_Load);
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout(); this.PerformLayout();
} }
#endregion #endregion
private TextBox textBoxEmail; private TextBox textBoxEmail;
private Label labelAdress; private Label labelAdress;
private Label labelSubject; private Label labelSubject;
private TextBox textBoxSubject; private TextBox textBoxSubject;
private Label labelBody; private Label labelBody;
private TextBox textBoxBody; private TextBox textBoxBody;
private Button buttonClose; private Button buttonClose;
private Button buttonReply; private Button buttonReply;
private Label labelDate; private Label labelDate;
private TextBox textBoxDate; private TextBox textBoxDate;
private Button buttonSend; private Button buttonSend;
} }
} }

View File

@ -5,138 +5,148 @@ using PizzeriaContracts.BindingModels;
using PizzeriaContracts.BusinessLogicsContracts; using PizzeriaContracts.BusinessLogicsContracts;
using PizzeriaContracts.SearchModels; using PizzeriaContracts.SearchModels;
using PizzeriaContracts.ViewModels; using PizzeriaContracts.ViewModels;
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 System.Windows.Forms.VisualStyles;
namespace PizzeriaView namespace PizzeriaView
{ {
public partial class FormLetter : Form public partial class FormLetter : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic; private readonly IMessageInfoLogic _logic;
private readonly AbstractMailWorker _worker; private readonly AbstractMailWorker _worker;
public MessageInfoViewModel? model; public MessageInfoViewModel? model;
public string? messageId; public string? messageId;
public FormLetter(ILogger<FormLetter> logger, IMessageInfoLogic logic, AbstractMailWorker worker) public FormLetter(ILogger<FormLetter> logger, IMessageInfoLogic logic, AbstractMailWorker worker)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
_worker = worker; _worker = worker;
} }
private void FormLetter_Load(object sender, EventArgs e) private void FormLetter_Load(object sender, EventArgs e)
{ {
if (!string.IsNullOrEmpty(messageId)) if (!string.IsNullOrEmpty(messageId))
{ {
ReloadLetter(); ReloadLetter();
return; return;
} }
else if (model != null) else if (model != null)
{ {
ConfigurateToCreateAnsver(); ConfigurateToCreateAnsver();
return; return;
} }
_logger.LogError("Для формы не переданно сведений о письме, на которое отвечаем!"); _logger.LogError("Для формы не переданно сведений о письме, на которое отвечаем!");
DialogResult = DialogResult.Abort; DialogResult = DialogResult.Abort;
Close(); Close();
return; return;
} }
private void ReloadLetter() private void ReloadLetter()
{ {
_logger.LogInformation("Загрузка существующего письма с id:{}", messageId); _logger.LogInformation("Загрузка существующего письма с id:{}", messageId);
model = _logic.ReadElement(new MessageInfoSearchModel model = _logic.ReadElement(new MessageInfoSearchModel
{ {
MessageId = messageId MessageId = messageId
}); });
if (model != null) if (model != null)
{ {
_logger.LogInformation("Письмо найдено"); _logger.LogInformation("Письмо найдено");
textBoxEmail.Text = model.SenderName; textBoxEmail.Text = model.SenderName;
textBoxDate.Text = model.DateDelivery.ToString(); textBoxDate.Text = model.DateDelivery.ToString();
textBoxSubject.Text = model.Subject; textBoxSubject.Text = model.Subject;
textBoxBody.Text = model.Body; textBoxBody.Text = model.Body;
if (model.IsReply) if (model.IsReply)
{ {
_logger.LogInformation("Письмо само и есть ответ"); _logger.LogInformation("Письмо само и есть ответ");
buttonReply.Visible = false; buttonReply.Visible = false;
} }
else else
{ {
if (!string.IsNullOrEmpty(model.ReplyMessageId)) if (!string.IsNullOrEmpty(model.ReplyMessageId))
{ {
_logger.LogInformation("У письма есть ответ."); _logger.LogInformation("У письма есть ответ.");
buttonReply.Text = "Прочитать ответ"; buttonReply.Text = "Прочитать ответ";
} }
} }
return; return;
} }
_logger.LogWarning("Письмо с таким id не удалось найти"); _logger.LogWarning("Письмо с таким id не удалось найти");
DialogResult = DialogResult.Abort; DialogResult = DialogResult.Abort;
Close(); Close();
return; return;
} }
private void ConfigurateToCreateAnsver() private void ConfigurateToCreateAnsver()
{ {
textBoxEmail.Text = model.SenderName; textBoxEmail.Text = model.SenderName;
labelDate.Visible = false; labelDate.Visible = false;
textBoxDate.Visible = false; textBoxDate.Visible = false;
textBoxSubject.Text = $"re: {model.Subject}"; textBoxSubject.Text = $"re: {model.Subject}";
textBoxBody.ReadOnly = false; textBoxBody.ReadOnly = false;
buttonReply.Visible = false; buttonReply.Visible = false;
buttonSend.Visible = true; buttonSend.Visible = true;
_logger.LogInformation("Запущена форма создания нового письма - ответа"); _logger.LogInformation("Запущена форма создания нового письма - ответа");
} }
private void buttonClose_Click(object sender, EventArgs e) private void buttonClose_Click(object sender, EventArgs e)
{ {
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
Close(); Close();
} }
private void buttonReply_Click(object sender, EventArgs e) private void buttonReply_Click(object sender, EventArgs e)
{ {
var service = Program.ServiceProvider?.GetService(typeof(FormLetter)); var service = Program.ServiceProvider?.GetService(typeof(FormLetter));
if (service is FormLetter form) if (service is FormLetter form)
{ {
if (!string.IsNullOrEmpty(model.ReplyMessageId)) if (!string.IsNullOrEmpty(model.ReplyMessageId))
{ {
form.messageId = model.ReplyMessageId; form.messageId = model.ReplyMessageId;
} }
else else
{ {
form.model = model; form.model = model;
} }
if (form.ShowDialog() != DialogResult.Cancel) if (form.ShowDialog() != DialogResult.Cancel)
{ {
buttonReply.Visible = false; buttonReply.Visible = false;
} }
} }
} }
private void buttonSend_Click(object sender, EventArgs e) private void buttonSend_Click(object sender, EventArgs e)
{ {
if (model == null) if (model == null)
{ {
return; return;
} }
string subject = textBoxSubject.Text; string subject = textBoxSubject.Text;
string text = textBoxBody.Text; string text = textBoxBody.Text;
Task.Run(() => _worker.MailSendReplyAsync(new MailReplySendInfoBindingModel Task.Run(() => _worker.MailSendReplyAsync(new MailReplySendInfoBindingModel
{ {
MailAddress = model.SenderName, MailAddress = model.SenderName,
Subject = subject, Subject = subject,
Text = text, Text = text,
ParentMessageId = model.MessageId, ParentMessageId = model.MessageId,
})); }));
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
Close(); Close();
} }
} }
} }

View File

@ -1,133 +1,133 @@
namespace PizzeriaView namespace PizzeriaView
{ {
partial class FormMail partial class FormMail
{ {
/// <summary> /// <summary>
/// Required designer variable. /// Required designer variable.
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// Clean up any resources being used. /// Clean up any resources being used.
/// </summary> /// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>
/// Required method for Designer support - do not modify /// Required method for Designer support - do not modify
/// the contents of this method with the code editor. /// the contents of this method with the code editor.
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.panel1 = new System.Windows.Forms.Panel(); this.panel1 = new System.Windows.Forms.Panel();
this.dataGridView = new System.Windows.Forms.DataGridView(); this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonOpen = new System.Windows.Forms.Button(); this.buttonOpen = new System.Windows.Forms.Button();
this.numericUpDownPage = new System.Windows.Forms.NumericUpDown(); this.numericUpDownPage = new System.Windows.Forms.NumericUpDown();
this.buttonPreveous = new System.Windows.Forms.Button(); this.buttonPreveous = new System.Windows.Forms.Button();
this.buttonNext = new System.Windows.Forms.Button(); this.buttonNext = new System.Windows.Forms.Button();
this.panel1.SuspendLayout(); this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownPage)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownPage)).BeginInit();
this.SuspendLayout(); this.SuspendLayout();
// //
// panel1 // panel1
// //
this.panel1.Controls.Add(this.dataGridView); this.panel1.Controls.Add(this.dataGridView);
this.panel1.Location = new System.Drawing.Point(3, 1); this.panel1.Location = new System.Drawing.Point(3, 1);
this.panel1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.panel1.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.panel1.Name = "panel1"; this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(795, 431); this.panel1.Size = new System.Drawing.Size(795, 431);
this.panel1.TabIndex = 0; this.panel1.TabIndex = 0;
// //
// dataGridView // dataGridView
// //
this.dataGridView.AllowUserToAddRows = false; this.dataGridView.AllowUserToAddRows = false;
this.dataGridView.AllowUserToDeleteRows = false; this.dataGridView.AllowUserToDeleteRows = false;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView.Location = new System.Drawing.Point(0, 0); this.dataGridView.Location = new System.Drawing.Point(0, 0);
this.dataGridView.Name = "dataGridView"; this.dataGridView.Name = "dataGridView";
this.dataGridView.ReadOnly = true; this.dataGridView.ReadOnly = true;
this.dataGridView.RowHeadersWidth = 51; this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29; this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(795, 431); this.dataGridView.Size = new System.Drawing.Size(795, 431);
this.dataGridView.TabIndex = 2; this.dataGridView.TabIndex = 2;
// //
// buttonOpen // buttonOpen
// //
this.buttonOpen.Location = new System.Drawing.Point(806, 80); this.buttonOpen.Location = new System.Drawing.Point(806, 80);
this.buttonOpen.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4); this.buttonOpen.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.buttonOpen.Name = "buttonOpen"; this.buttonOpen.Name = "buttonOpen";
this.buttonOpen.Size = new System.Drawing.Size(107, 31); this.buttonOpen.Size = new System.Drawing.Size(107, 31);
this.buttonOpen.TabIndex = 1; this.buttonOpen.TabIndex = 1;
this.buttonOpen.Text = "Прочитать"; this.buttonOpen.Text = "Прочитать";
this.buttonOpen.UseVisualStyleBackColor = true; this.buttonOpen.UseVisualStyleBackColor = true;
this.buttonOpen.Click += new System.EventHandler(this.buttonOpen_Click); this.buttonOpen.Click += new System.EventHandler(this.buttonOpen_Click);
// //
// numericUpDownPage // numericUpDownPage
// //
this.numericUpDownPage.Location = new System.Drawing.Point(825, 287); this.numericUpDownPage.Location = new System.Drawing.Point(825, 287);
this.numericUpDownPage.Name = "numericUpDownPage"; this.numericUpDownPage.Name = "numericUpDownPage";
this.numericUpDownPage.Size = new System.Drawing.Size(85, 27); this.numericUpDownPage.Size = new System.Drawing.Size(85, 27);
this.numericUpDownPage.TabIndex = 4; this.numericUpDownPage.TabIndex = 4;
this.numericUpDownPage.ValueChanged += new System.EventHandler(this.numericUpDownPage_ValueChanged); this.numericUpDownPage.ValueChanged += new System.EventHandler(this.numericUpDownPage_ValueChanged);
// //
// buttonPreveous // buttonPreveous
// //
this.buttonPreveous.Location = new System.Drawing.Point(825, 323); this.buttonPreveous.Location = new System.Drawing.Point(825, 323);
this.buttonPreveous.Name = "buttonPreveous"; this.buttonPreveous.Name = "buttonPreveous";
this.buttonPreveous.Size = new System.Drawing.Size(39, 29); this.buttonPreveous.Size = new System.Drawing.Size(39, 29);
this.buttonPreveous.TabIndex = 5; this.buttonPreveous.TabIndex = 5;
this.buttonPreveous.Text = "<-"; this.buttonPreveous.Text = "<-";
this.buttonPreveous.UseVisualStyleBackColor = true; this.buttonPreveous.UseVisualStyleBackColor = true;
this.buttonPreveous.Click += new System.EventHandler(this.buttonPreveous_Click); this.buttonPreveous.Click += new System.EventHandler(this.buttonPreveous_Click);
// //
// buttonNext // buttonNext
// //
this.buttonNext.Location = new System.Drawing.Point(872, 323); this.buttonNext.Location = new System.Drawing.Point(872, 323);
this.buttonNext.Name = "buttonNext"; this.buttonNext.Name = "buttonNext";
this.buttonNext.Size = new System.Drawing.Size(39, 29); this.buttonNext.Size = new System.Drawing.Size(39, 29);
this.buttonNext.TabIndex = 6; this.buttonNext.TabIndex = 6;
this.buttonNext.Text = "->"; this.buttonNext.Text = "->";
this.buttonNext.UseVisualStyleBackColor = true; this.buttonNext.UseVisualStyleBackColor = true;
this.buttonNext.Click += new System.EventHandler(this.buttonNext_Click); this.buttonNext.Click += new System.EventHandler(this.buttonNext_Click);
// //
// FormMail // FormMail
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(925, 428); this.ClientSize = new System.Drawing.Size(925, 428);
this.Controls.Add(this.buttonNext); this.Controls.Add(this.buttonNext);
this.Controls.Add(this.buttonPreveous); this.Controls.Add(this.buttonPreveous);
this.Controls.Add(this.numericUpDownPage); this.Controls.Add(this.numericUpDownPage);
this.Controls.Add(this.buttonOpen); this.Controls.Add(this.buttonOpen);
this.Controls.Add(this.panel1); this.Controls.Add(this.panel1);
this.Name = "FormMail"; this.Name = "FormMail";
this.Text = "Письма"; this.Text = "Письма";
this.Load += new System.EventHandler(this.FormMail_Load); this.Load += new System.EventHandler(this.FormMail_Load);
this.panel1.ResumeLayout(false); this.panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownPage)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownPage)).EndInit();
this.ResumeLayout(false); this.ResumeLayout(false);
} }
#endregion #endregion
private Panel panel1; private Panel panel1;
private DataGridView dataGridView; private DataGridView dataGridView;
private Button buttonOpen; private Button buttonOpen;
private NumericUpDown numericUpDownPage; private NumericUpDown numericUpDownPage;
private Button buttonPreveous; private Button buttonPreveous;
private Button buttonNext; private Button buttonNext;
} }
} }

View File

@ -17,99 +17,99 @@ using System.Windows.Forms;
namespace PizzeriaView namespace PizzeriaView
{ {
public partial class FormMail : Form public partial class FormMail : Form
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly IMessageInfoLogic _logic; private readonly IMessageInfoLogic _logic;
private int currentPage = 1; private int currentPage = 1;
private int pageLength = 2; private int pageLength = 2;
public FormMail(ILogger<FormMail> logger, IMessageInfoLogic logic) public FormMail(ILogger<FormMail> logger, IMessageInfoLogic logic)
{ {
InitializeComponent(); InitializeComponent();
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
} }
private void LoadData() private void LoadData()
{ {
try try
{ {
var list = _logic.ReadList(new MessageInfoSearchModel() var list = _logic.ReadList(new MessageInfoSearchModel()
{ {
PageLength = pageLength, PageLength = pageLength,
PageIndex = currentPage PageIndex = currentPage
}); });
numericUpDownPage.Value = pageLength; numericUpDownPage.Value = pageLength;
if (list != null) if (list != null)
{ {
dataGridView.DataSource = list; dataGridView.DataSource = list;
dataGridView.Columns["MessageId"].Visible = false; dataGridView.Columns["MessageId"].Visible = false;
dataGridView.Columns["ClientId"].Visible = false; dataGridView.Columns["ClientId"].Visible = false;
dataGridView.Columns["ReplyMessageId"].Visible = false; dataGridView.Columns["ReplyMessageId"].Visible = false;
dataGridView.Columns["Reply"].Visible = false; dataGridView.Columns["Reply"].Visible = false;
dataGridView.Columns["IsReply"].Visible = false; dataGridView.Columns["IsReply"].Visible = false;
dataGridView.Columns["Body"].AutoSizeMode = dataGridView.Columns["Body"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill; DataGridViewAutoSizeColumnMode.Fill;
} }
_logger.LogInformation("Загрузка почтовых собщений"); _logger.LogInformation("Загрузка почтовых собщений");
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Ошибка загрузки почтовых сообщений"); _logger.LogError(ex, "Ошибка загрузки почтовых сообщений");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
private void FormMail_Load(object sender, EventArgs e) private void FormMail_Load(object sender, EventArgs e)
{ {
LoadData(); LoadData();
} }
private void buttonOpen_Click(object sender, EventArgs e) private void buttonOpen_Click(object sender, EventArgs e)
{ {
if (dataGridView.SelectedRows.Count <= 0) if (dataGridView.SelectedRows.Count <= 0)
return; return;
var service = Program.ServiceProvider?.GetService(typeof(FormLetter)); var service = Program.ServiceProvider?.GetService(typeof(FormLetter));
if (service is FormLetter form) if (service is FormLetter form)
{ {
string? messageId = dataGridView.SelectedRows[0].Cells["MessageId"].Value.ToString(); string? messageId = dataGridView.SelectedRows[0].Cells["MessageId"].Value.ToString();
if (messageId == null) return; if (messageId == null) return;
form.messageId = messageId; form.messageId = messageId;
if (!Convert.ToBoolean(dataGridView.SelectedRows[0].Cells["IsReaded"].Value)) if (!Convert.ToBoolean(dataGridView.SelectedRows[0].Cells["IsReaded"].Value))
{ {
_logic.Update(new MessageInfoBindingModel _logic.Update(new MessageInfoBindingModel
{ {
MessageId = messageId, MessageId = messageId,
IsReaded = true, IsReaded = true,
ReplyMessageId = dataGridView.SelectedRows[0].Cells["ReplyMessageId"].Value?.ToString() ReplyMessageId = dataGridView.SelectedRows[0].Cells["ReplyMessageId"].Value?.ToString()
}); });
} }
form.ShowDialog(); form.ShowDialog();
LoadData(); LoadData();
} }
} }
private void buttonPreveous_Click(object sender, EventArgs e) private void buttonPreveous_Click(object sender, EventArgs e)
{ {
currentPage = Math.Max(1, currentPage - 1); currentPage = Math.Max(1, currentPage - 1);
LoadData(); LoadData();
} }
private void buttonNext_Click(object sender, EventArgs e) private void buttonNext_Click(object sender, EventArgs e)
{ {
currentPage++; currentPage++;
LoadData(); LoadData();
} }
private void numericUpDownPage_ValueChanged(object sender, EventArgs e) private void numericUpDownPage_ValueChanged(object sender, EventArgs e)
{ {
pageLength = Math.Max(1, (int)numericUpDownPage.Value); pageLength = Math.Max(1, (int)numericUpDownPage.Value);
LoadData(); LoadData();
} }
} }
} }

View File

@ -4,112 +4,111 @@ using NLog.Extensions.Logging;
using PizzeriaBusinessLogic.BusinessLogics; using PizzeriaBusinessLogic.BusinessLogics;
using PizzeriaBusinessLogic.MailWorker; using PizzeriaBusinessLogic.MailWorker;
using PizzeriaContracts.BindingModels; using PizzeriaContracts.BindingModels;
using PizzeriaBusinessLogic.OfficePackage.Implements;
using PizzeriaBusinessLogic.OfficePackage;
using PizzeriaContracts.BusinessLogicsContracts; using PizzeriaContracts.BusinessLogicsContracts;
using PizzeriaContracts.StoragesContracts; using PizzeriaContracts.StoragesContracts;
using PizzeriaDatabaseImplement.Implements; using PizzeriaDatabaseImplement.Implements;
using PizzeriaView; using PizzeriaView;
using PizzeriaBusinessLogic.OfficePackage;
using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Design;
using PizzeriaBusinessLogic.OfficePackage.Implements;
namespace Pizzeria namespace Pizzeria
{ {
internal static class Program internal static class Program
{ {
private static ServiceProvider? _serviceProvider; private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider; public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
var services = new ServiceCollection(); var services = new ServiceCollection();
ConfigureServices(services); ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider(); _serviceProvider = services.BuildServiceProvider();
try try
{ {
var mailSender = _serviceProvider.GetService<AbstractMailWorker>(); var mailSender = _serviceProvider.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel mailSender?.MailConfig(new MailConfigBindingModel
{ {
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty, MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty, MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty, SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]), SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]),
PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty, PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty,
PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"]) PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"])
}); });
var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000); var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000);
} }
catch (Exception ex) catch (Exception ex)
{ {
var logger = _serviceProvider.GetService<ILogger>(); var logger = _serviceProvider.GetService<ILogger>();
logger?.LogError(ex, "Mails Problem"); logger?.LogError(ex, "Mails Problem");
} }
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
Application.Run(_serviceProvider.GetRequiredService<FormMain>()); private static void ConfigureServices(ServiceCollection services)
} {
private static void ConfigureServices(ServiceCollection services) services.AddLogging(option =>
{ {
services.AddLogging(option => option.SetMinimumLevel(LogLevel.Information);
{ option.AddNLog("nlog.config");
option.SetMinimumLevel(LogLevel.Information); });
option.AddNLog("nlog.config");
});
services.AddTransient<IClientStorage, ClientStorage>(); services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>(); services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IComponentStorage, ComponentStorage>(); services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>(); services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IPizzaStorage, PizzaStorage>(); services.AddTransient<IPizzaStorage, PizzaStorage>();
services.AddTransient<IMessageInfoStorage, MessageInfoStorage>(); services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IClientLogic, ClientLogic>(); services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IPizzaLogic, PizzaLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<IShopLogic, ShopLogic>(); services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IImplementerLogic, ImplementerLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IPizzaLogic, PizzaLogic>();
services.AddTransient<IReportLogic, ReportLogic>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IWorkProcess, WorkModeling>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>(); services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
services.AddSingleton<AbstractMailWorker, MailKitWorker>(); services.AddSingleton<AbstractMailWorker, MailKitWorker>();
services.AddTransient<FormComponent>(); services.AddTransient<FormMain>();
services.AddTransient<FormComponents>(); services.AddTransient<FormComponent>();
services.AddTransient<FormCreateOrder>(); services.AddTransient<FormComponents>();
services.AddTransient<FormPizza>(); services.AddTransient<FormCreateOrder>();
services.AddTransient<FormPizzaComponent>(); services.AddTransient<FormPizza>();
services.AddTransient<FormPizzas>(); services.AddTransient<FormPizzaComponent>();
services.AddTransient<FormShop>(); services.AddTransient<FormPizzas>();
services.AddTransient<FormShops>(); services.AddTransient<FormShop>();
services.AddTransient<FormCreateSupply>(); services.AddTransient<FormShops>();
services.AddTransient<FormSellPizza>(); services.AddTransient<FormCreateSupply>();
services.AddTransient<FormMain>(); services.AddTransient<FormSellPizza>();
services.AddTransient<FormReportPizzaComponents>(); services.AddTransient<FormReportPizzaComponents>();
services.AddTransient<FormReportOrders>(); services.AddTransient<FormReportOrders>();
services.AddTransient<FormClients>(); services.AddTransient<FormClients>();
services.AddTransient<EntityFrameworkDesignServicesBuilder>(); services.AddTransient<EntityFrameworkDesignServicesBuilder>();
services.AddTransient<FormReportShop>(); services.AddTransient<FormImplementers>();
services.AddTransient<FormReportGroupedOrders>(); services.AddTransient<FormImplementer>();
services.AddTransient<FormImplementers>(); services.AddTransient<FormMail>();
services.AddTransient<FormImplementer>(); services.AddTransient<FormReportShop>();
services.AddTransient<FormMail>(); services.AddTransient<FormReportGroupedOrders>();
services.AddTransient<FormLetter>(); }
}
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck(); private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
} }
} }