ПОСЛЕДНИЙ ли это каммит

This commit is contained in:
m1aksim1 2023-05-09 02:56:52 +04:00
parent 037f9db304
commit 178ea8736e
46 changed files with 1938 additions and 42 deletions

View File

@ -11,7 +11,9 @@ namespace SoftwareInstallationClientApp
public static ClientViewModel? Client { get; set; } = null; public static ClientViewModel? Client { get; set; } = null;
public static void Connect(IConfiguration configuration) public static int CurrentPage { get; set; } = 0;
public static void Connect(IConfiguration configuration)
{ {
_client.BaseAddress = new Uri(configuration["IPAddress"]); _client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Accept.Clear();

View File

@ -4,6 +4,10 @@ using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationContracts.ViewModels;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using System.Diagnostics; using System.Diagnostics;
using System.Text;
using SoftwareInstallationContracts.SearchModels;
using Microsoft.AspNetCore.Mvc.Rendering;
using SoftwareInstallationContracts.ViewModels;
namespace SoftwareInstallationClientApp.Controllers namespace SoftwareInstallationClientApp.Controllers
{ {
@ -144,5 +148,55 @@ namespace SoftwareInstallationClientApp.Controllers
var prod = APIClient.GetRequest<PackageViewModel>($"api/main/getpackage?packageId={package}"); var prod = APIClient.GetRequest<PackageViewModel>($"api/main/getpackage?packageId={package}");
return count * (prod?.Price ?? 1); return count * (prod?.Price ?? 1);
} }
[HttpGet]
public IActionResult Mails()
{
if (APIClient.Client == null)
{
return Redirect("~/Home/Enter");
}
return View();
}
/// <summary>
/// Switches the page.
/// </summary>
/// <returns>Возвращает кортеж с таблицой в html, текущей страницей писем, выключать ли кнопку пред. страницы, выключать ли кнопку след. страницы</returns>
[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

@ -28,6 +28,9 @@
<li class="nav-item"> <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Личные данные</a>
</li> </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"> <li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Вход</a> <a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Enter">Вход</a>
</li> </li>

View File

@ -3,6 +3,8 @@ using SoftwareInstallationContracts.BusinessLogicsContracts;
using SoftwareInstallationContracts.SearchModels; using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationContracts.ViewModels;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using SoftwareInstallationContracts.BusinessLogicsContracts;
using SoftwareInstallationContracts.ViewModels;
namespace SoftwareInstallationRestApi.Controllers namespace SoftwareInstallationRestApi.Controllers
{ {
@ -14,13 +16,17 @@ namespace SoftwareInstallationRestApi.Controllers
private readonly IClientLogic _logic; private readonly IClientLogic _logic;
public ClientController(IClientLogic logic, ILogger<ClientController> logger) private readonly IMessageInfoLogic _mailLogic;
{ public int pageSize = 3;
public ClientController(IClientLogic logic, IMessageInfoLogic mailLogic, ILogger<ClientController> logger)
{
_logger = logger; _logger = logger;
_logic = logic; _logic = logic;
} _mailLogic = mailLogic;
}
[HttpGet] [HttpGet]
public ClientViewModel? Login(string login, string password) public ClientViewModel? Login(string login, string password)
{ {
try try
@ -66,5 +72,23 @@ namespace SoftwareInstallationRestApi.Controllers
throw; 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

@ -5,6 +5,13 @@ using SoftwareInstallationDatabaseImplement;
using SoftwareInstallationDatabaseImplement.Implements; using SoftwareInstallationDatabaseImplement.Implements;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.StoragesContracts;
using SoftwareInstallationBusinessLogic.MailWorker;
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationBusinessLogic.MailWorker;
using SoftwareInstallationBusinessLogic;
using SoftwareInstallationContracts.BusinessLogicsContracts;
using SoftwareInstallationContracts.StoragesContract;
using SoftwareInstallationContracts.BindingModels;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -15,11 +22,13 @@ builder.Services.AddTransient<IClientStorage, ClientStorage>();
builder.Services.AddTransient<IOrderStorage, OrderStorage>(); builder.Services.AddTransient<IOrderStorage, OrderStorage>();
builder.Services.AddTransient<IPackageStorage, PackageStorage>(); builder.Services.AddTransient<IPackageStorage, PackageStorage>();
builder.Services.AddTransient<IShopStorage, ShopStorage>(); builder.Services.AddTransient<IShopStorage, ShopStorage>();
builder.Services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
builder.Services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
builder.Services.AddTransient<IOrderLogic, OrderLogic>(); builder.Services.AddTransient<IOrderLogic, OrderLogic>();
builder.Services.AddTransient<IClientLogic, ClientLogic>(); builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IPackageLogic, PackageLogic>(); builder.Services.AddTransient<IPackageLogic, PackageLogic>();
builder.Services.AddTransient<IShopLogic, ShopLogic>(); builder.Services.AddTransient<IShopLogic, ShopLogic>();
builder.Services.AddSingleton<AbstractMailWorker, MailKitWorker>();
builder.Services.AddControllers(); builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at // Learn more about configuring Swagger/OpenAPI at
@ -34,6 +43,18 @@ builder.Services.AddSwaggerGen(c =>
}); });
}); });
var app = builder.Build(); var app = builder.Build();
var mailSender = app.Services.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = builder.Configuration?.GetSection("MailLogin")?.Value?.ToString() ?? string.Empty,
MailPassword = builder.Configuration?.GetSection("MailPassword")?.Value?.ToString() ?? string.Empty,
SmtpClientHost = builder.Configuration?.GetSection("SmtpClientHost")?.Value?.ToString() ?? string.Empty,
SmtpClientPort = Convert.ToInt32(builder.Configuration?.GetSection("SmtpClientPort")?.Value?.ToString()),
PopHost = builder.Configuration?.GetSection("PopHost")?.Value?.ToString() ?? string.Empty,
PopPort = Convert.ToInt32(builder.Configuration?.GetSection("PopPort")?.Value?.ToString())
});
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) if (app.Environment.IsDevelopment())
{ {

View File

@ -6,5 +6,11 @@
} }
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"PasswordToAccessShop": "12345" "PasswordToAccessShop": "12345",
"SmtpClientHost": "smtp.mail.ru",
"SmtpClientPort": "587",
"PopHost": "pop.mail.ru",
"PopPort": "995",
"MailLogin": "ordersender228@mail.ru",
"MailPassword": "v8czsQ8zztJc5wEHxKPN"
} }

View File

@ -22,7 +22,10 @@ namespace SoftwareInstallationDatabaseImplement.Models
[ForeignKey("ClientId")] [ForeignKey("ClientId")]
public virtual List<Order> Orders { get; set; } = new(); public virtual List<Order> Orders { get; set; } = new();
public static Client? Create(ClientBindingModel model) [ForeignKey("ClientId")]
public virtual List<MessageInfo> Messages { get; set; } = new();
public static Client? Create(ClientBindingModel model)
{ {
if (model == null) if (model == null)
{ {

View File

@ -0,0 +1,72 @@
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels;
using System.ComponentModel.DataAnnotations;
namespace SoftwareInstallationDatabaseImplement.Models
{
// Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма
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

@ -0,0 +1,68 @@
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationContracts.StoragesContract;
using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDatabaseImplement.Models;
namespace SoftwareInstallationDatabaseImplement
{
public class MessageInfoStorage : IMessageInfoStorage
{
public MessageInfoViewModel? GetElement(MessageInfoSearchModel model)
{
using var context = new SoftwareInstallationDatabase();
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 SoftwareInstallationDatabase();
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 SoftwareInstallationDatabase();
return context.Messages
.Select(x => x.GetViewModel)
.ToList();
}
public MessageInfoViewModel? Insert(MessageInfoBindingModel model)
{
using var context = new SoftwareInstallationDatabase();
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 SoftwareInstallationDatabase();
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,7 +12,7 @@ using SoftwareInstallationDatabaseImplement;
namespace SoftWareInstallationDatabaseImplement.Migrations namespace SoftWareInstallationDatabaseImplement.Migrations
{ {
[DbContext(typeof(SoftwareInstallationDatabase))] [DbContext(typeof(SoftwareInstallationDatabase))]
[Migration("20230425164115_InitialCreate")] [Migration("20230508225550_InitialCreate")]
partial class InitialCreate partial class InitialCreate
{ {
/// <inheritdoc /> /// <inheritdoc />
@ -97,6 +97,42 @@ namespace SoftWareInstallationDatabaseImplement.Migrations
b.ToTable("Implementers"); b.ToTable("Implementers");
}); });
modelBuilder.Entity("SoftwareInstallationDatabaseImplement.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("SoftwareInstallationDatabaseImplement.Models.Order", b => modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -244,6 +280,15 @@ namespace SoftWareInstallationDatabaseImplement.Migrations
b.ToTable("ShopPackages"); b.ToTable("ShopPackages");
}); });
modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("SoftwareInstallationDatabaseImplement.Models.Client", "Client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b => modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b =>
{ {
b.HasOne("SoftwareInstallationDatabaseImplement.Models.Client", "Client") b.HasOne("SoftwareInstallationDatabaseImplement.Models.Client", "Client")
@ -316,6 +361,8 @@ namespace SoftWareInstallationDatabaseImplement.Migrations
modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Client", b => modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Client", b =>
{ {
b.Navigation("Messages");
b.Navigation("Orders"); b.Navigation("Orders");
}); });

View File

@ -70,6 +70,29 @@ namespace SoftWareInstallationDatabaseImplement.Migrations
table.PrimaryKey("PK_Packages", x => x.Id); table.PrimaryKey("PK_Packages", 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( migrationBuilder.CreateTable(
name: "Orders", name: "Orders",
columns: table => new columns: table => new
@ -183,6 +206,11 @@ namespace SoftWareInstallationDatabaseImplement.Migrations
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
}); });
migrationBuilder.CreateIndex(
name: "IX_Messages_ClientId",
table: "Messages",
column: "ClientId");
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_Orders_ClientId", name: "IX_Orders_ClientId",
table: "Orders", table: "Orders",
@ -227,6 +255,9 @@ namespace SoftWareInstallationDatabaseImplement.Migrations
/// <inheritdoc /> /// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder) protected override void Down(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.DropTable(
name: "Messages");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "Orders"); name: "Orders");

View File

@ -94,6 +94,42 @@ namespace SoftWareInstallationDatabaseImplement.Migrations
b.ToTable("Implementers"); b.ToTable("Implementers");
}); });
modelBuilder.Entity("SoftwareInstallationDatabaseImplement.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("SoftwareInstallationDatabaseImplement.Models.Order", b => modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b =>
{ {
b.Property<int>("Id") b.Property<int>("Id")
@ -241,6 +277,15 @@ namespace SoftWareInstallationDatabaseImplement.Migrations
b.ToTable("ShopPackages"); b.ToTable("ShopPackages");
}); });
modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.MessageInfo", b =>
{
b.HasOne("SoftwareInstallationDatabaseImplement.Models.Client", "Client")
.WithMany("Messages")
.HasForeignKey("ClientId");
b.Navigation("Client");
});
modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b => modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Order", b =>
{ {
b.HasOne("SoftwareInstallationDatabaseImplement.Models.Client", "Client") b.HasOne("SoftwareInstallationDatabaseImplement.Models.Client", "Client")
@ -313,6 +358,8 @@ namespace SoftWareInstallationDatabaseImplement.Migrations
modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Client", b => modelBuilder.Entity("SoftwareInstallationDatabaseImplement.Models.Client", b =>
{ {
b.Navigation("Messages");
b.Navigation("Orders"); b.Navigation("Orders");
}); });

View File

@ -20,8 +20,4 @@
<ProjectReference Include="..\SoftwareInstallationDataModels\SoftwareInstallationDataModels.csproj" /> <ProjectReference Include="..\SoftwareInstallationDataModels\SoftwareInstallationDataModels.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Migrations\" />
</ItemGroup>
</Project> </Project>

View File

@ -12,7 +12,7 @@ namespace SoftwareInstallationDatabaseImplement
{ {
optionsBuilder.UseSqlServer(@" optionsBuilder.UseSqlServer(@"
Server = localhost\SQLEXPRESS; Server = localhost\SQLEXPRESS;
Initial Catalog = SoftwareHard6InstallationDatabaseFull; Initial Catalog = SoftwareHard7InstallationDatabaseFull;
Integrated Security = True; Integrated Security = True;
MultipleActiveResultSets = True; MultipleActiveResultSets = True;
TrustServerCertificate = True"); TrustServerCertificate = True");
@ -27,5 +27,6 @@ namespace SoftwareInstallationDatabaseImplement
public virtual DbSet<ShopPackage> ShopPackages { set; get; } public virtual DbSet<ShopPackage> ShopPackages { set; get; }
public virtual DbSet<Client> Clients { set; get; } public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Implementer> Implementers { set; get; } public virtual DbSet<Implementer> Implementers { set; get; }
public virtual DbSet<MessageInfo> Messages { set; get; }
} }
} }

View File

@ -12,12 +12,14 @@ namespace SoftwareInstallationFileImplement
private readonly string ShopFileName = "Shop.xml"; private readonly string ShopFileName = "Shop.xml";
private readonly string ClientFileName = "Client.xml"; private readonly string ClientFileName = "Client.xml";
private readonly string ImplementerFileName = "Implementer.xml"; private readonly string ImplementerFileName = "Implementer.xml";
private readonly string MessageInfoFileName = "MessageInfo.xml";
public List<Component> Components { get; private set; } public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; } public List<Order> Orders { get; private set; }
public List<Package> Packages { get; private set; } public List<Package> Packages { get; private set; }
public List<Client> Clients { get; private set; } public List<Client> Clients { get; private set; }
public List<Shop> Shops { get; private set; } public List<Shop> Shops { get; private set; }
public List<Implementer> Implementers { get; private set; } public List<Implementer> Implementers { get; private set; }
public List<MessageInfo> Messages { get; private set; }
public static DataFileSingleton GetInstance() public static DataFileSingleton GetInstance()
{ {
@ -33,6 +35,7 @@ namespace SoftwareInstallationFileImplement
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement); public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement); public void SaveClients() => SaveData(Clients, OrderFileName, "Clients", x => x.GetXElement);
public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement); public void SaveImplementers() => SaveData(Orders, ImplementerFileName, "Implementers", x => x.GetXElement);
public void SaveMessages() => SaveData(Orders, ImplementerFileName, "Messages", x => x.GetXElement);
private DataFileSingleton() private DataFileSingleton()
{ {
@ -42,6 +45,7 @@ namespace SoftwareInstallationFileImplement
Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!; Clients = LoadData(ClientFileName, "Client", x => Client.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!; Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!; Implementers = LoadData(ImplementerFileName, "Implementer", x => Implementer.Create(x)!)!;
Messages = LoadData(MessageInfoFileName, "MessageInfo", x => MessageInfo.Create(x)!)!;
} }
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction) private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{ {

View File

@ -0,0 +1,102 @@
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace SoftwareInstallationFileImplement.Models
{
// Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма
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

@ -0,0 +1,70 @@
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationContracts.StoragesContract;
using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationFileImplement.Models;
using System.Reflection;
namespace SoftwareInstallationFileImplement
{
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

@ -5,6 +5,7 @@ using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.StoragesContracts;
using SoftwareInstallationContracts.ViewModels; using SoftwareInstallationContracts.ViewModels;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;
namespace SoftwareInstallationBusinessLogic namespace SoftwareInstallationBusinessLogic
{ {
@ -102,7 +103,17 @@ namespace SoftwareInstallationBusinessLogic
{ {
throw new ArgumentNullException("Нет логина клиента", nameof(model.Email)); throw new ArgumentNullException("Нет логина клиента", nameof(model.Email));
} }
_logger.LogInformation("Client. Id: {Id}, FIO: {fio}, email: {email}", model.Id, model.ClientFIO, model.Email ); if (!Regex.IsMatch(model.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
{
throw new ArgumentException("Некорретно введенный email", nameof(model.Email));
}
// Запасной (вероятно более правильный): ^((\w+\d+\W+)|(\w+\W+\d+)|(\d+\w+\W+)|(\d+\W+\w+)|(\W+\w+\d+)|(\W+\d+\w+))+$
// Просматриваем наперед последовательность (де-факто оператор &&) цифр, небуквенных символов и букв (не цифр и не пробельных символов)
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 var element = _clientStorage.GetElement(new ClientSearchModel
{ {
Email = model.Email, Email = model.Email,

View File

@ -0,0 +1,100 @@
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareInstallationBusinessLogic.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,82 @@
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.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 SoftwareInstallationBusinessLogic.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

@ -0,0 +1,70 @@
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.BusinessLogicsContracts;
using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationContracts.StoragesContract;
using SoftwareInstallationContracts.ViewModels;
using DocumentFormat.OpenXml.EMMA;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareInstallationBusinessLogic
{
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 MessageInfoViewModel? ReadElement(MessageInfoSearchModel model)
{
var res = _messageInfoStorage.GetElement(model);
if (res == null)
{
_logger.LogWarning("Read element operation failed");
return null;
}
return res;
}
public bool Update(MessageInfoBindingModel model)
{
if (_messageInfoStorage.Update(model) == null)
{
_logger.LogWarning("Update 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;
}
}
}

View File

@ -6,6 +6,7 @@ using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels.Enums; using SoftwareInstallationDataModels.Enums;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using DocumentFormat.OpenXml.EMMA; using DocumentFormat.OpenXml.EMMA;
using SoftwareInstallationBusinessLogic.MailWorker;
namespace SoftwareInstallationBusinessLogic.BusinessLogics namespace SoftwareInstallationBusinessLogic.BusinessLogics
{ {
@ -15,15 +16,19 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics
private readonly IOrderStorage _orderStorage; private readonly IOrderStorage _orderStorage;
private readonly IPackageStorage _packageStorage; private readonly IPackageStorage _packageStorage;
private readonly IShopLogic _shopLogic; private readonly IShopLogic _shopLogic;
private static bool _finished = false; private readonly AbstractMailWorker _mailWorker;
private readonly IClientLogic _clientLogic;
private static bool _finished = false;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IPackageStorage packageStorage, IShopLogic shopLogic) public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IPackageStorage packageStorage, IShopLogic shopLogic, IClientLogic clientLogic, AbstractMailWorker mailWorker)
{ {
_logger = logger; _logger = logger;
_shopLogic = shopLogic; _shopLogic = shopLogic;
_packageStorage = packageStorage; _packageStorage = packageStorage;
_orderStorage = orderStorage; _orderStorage = orderStorage;
} _mailWorker = mailWorker;
_clientLogic = clientLogic;
}
public bool CreateOrder(OrderBindingModel model) public bool CreateOrder(OrderBindingModel model)
{ {
CheckModel(model); CheckModel(model);
@ -35,12 +40,14 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics
} }
model.Status = OrderStatus.Принят; model.Status = OrderStatus.Принят;
model.DateCreate = DateTime.Now; model.DateCreate = DateTime.Now;
if (_orderStorage.Insert(model) == null) var result = _orderStorage.Insert(model);
{ if (result == null)
{
_logger.LogWarning("Insert operation failed"); _logger.LogWarning("Insert operation failed");
return false; return false;
} }
return true; SendOrderStatusMail(result.ClientId, $"Новый заказ создан. Номер заказа #{result.Id}", $"Заказ #{result.Id} от {result.DateCreate} на сумму {result.Sum:0.00} принят");
return true;
} }
public bool DeliveryOrder(OrderBindingModel model) public bool DeliveryOrder(OrderBindingModel model)
@ -150,12 +157,29 @@ namespace SoftwareInstallationBusinessLogic.BusinessLogics
model.Sum = viewModel.Sum; model.Sum = viewModel.Sum;
model.Count = viewModel.Count; model.Count = viewModel.Count;
model.PackageId = viewModel.PackageId; model.PackageId = viewModel.PackageId;
if (_orderStorage.Update(model) == null) var result = _orderStorage.Update(model);
{ if (result == null)
{
_logger.LogWarning("Ошибка операции обновления"); _logger.LogWarning("Ошибка операции обновления");
return false; return false;
} }
return true; SendOrderStatusMail(result.ClientId, $"Изменен статус заказа #{result.Id}", $"Заказ #{model.Id} изменен статус на {result.Status}");
return true;
} }
} 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

@ -8,6 +8,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" /> <PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="MailKit" Version="4.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="PDFsharp-MigraDoc-GDI" Version="1.50.5147" /> <PackageReference Include="PDFsharp-MigraDoc-GDI" Version="1.50.5147" />
</ItemGroup> </ItemGroup>

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareInstallationContracts.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 SoftwareInstallationContracts.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,27 @@
using SoftwareInstallationDataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareInstallationContracts.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,22 @@
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareInstallationContracts.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,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareInstallationContracts.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 SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareInstallationContracts.StoragesContract
{
public interface IMessageInfoStorage
{
List<MessageInfoViewModel> GetFullList();
List<MessageInfoViewModel> GetFilteredList(MessageInfoSearchModel model);
MessageInfoViewModel? GetElement(MessageInfoSearchModel model);
MessageInfoViewModel? Insert(MessageInfoBindingModel model);
MessageInfoViewModel? Update(MessageInfoBindingModel model);
}
}

View File

@ -0,0 +1,35 @@
using SoftwareInstallationDataModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareInstallationContracts.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,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareInstallationDataModels
{
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

@ -11,6 +11,8 @@ namespace SoftwareInstallationListImplement
public List<Client> Clients { get; set; } public List<Client> Clients { get; set; }
public List<Shop> Shops { get; set; } public List<Shop> Shops { get; set; }
public List<Implementer> Implementers { get; set; } public List<Implementer> Implementers { get; set; }
public List<MessageInfo> Messages { get; set; }
private DataListSingleton() private DataListSingleton()
{ {
Components = new List<Component>(); Components = new List<Component>();
@ -19,8 +21,9 @@ namespace SoftwareInstallationListImplement
Clients = new List<Client>(); Clients = new List<Client>();
Shops = new List<Shop>(); Shops = new List<Shop>();
Implementers = new List<Implementer>(); Implementers = new List<Implementer>();
Messages = new List<MessageInfo>();
} }
public static DataListSingleton GetInstance() public static DataListSingleton GetInstance()
{ {
if (_instance == null) if (_instance == null)
{ {

View File

@ -0,0 +1,72 @@
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationDataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SoftwareInstallationListImplement.Models
{
// Update в этой сущности не нужен, поскольку в логике мы не изменяем никакие поля после создания письма
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

@ -0,0 +1,89 @@
using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationContracts.SearchModels;
using SoftwareInstallationContracts.StoragesContract;
using SoftwareInstallationContracts.ViewModels;
using SoftwareInstallationListImplement.Models;
using System.Collections.Generic;
namespace SoftwareInstallationListImplement
{
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,11 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="SmtpClientHost" value="smtp.mail.ru" />
<add key="SmtpClientPort" value="587" />
<add key="PopHost" value="pop.mail.ru" />
<add key="PopPort" value="995" />
<add key="MailLogin" value="ordersender228@mail.ru" />
<add key="MailPassword" value="v8czsQ8zztJc5wEHxKPN" />
</appSettings>
</configuration>

View File

@ -49,13 +49,14 @@
buttonAddPackageInShop = new Button(); buttonAddPackageInShop = new Button();
buttonSellPackage = new Button(); buttonSellPackage = new Button();
ButtonIssuedOrder = new Button(); ButtonIssuedOrder = new Button();
mailToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout(); menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout(); SuspendLayout();
// //
// menuStrip1 // menuStrip1
// //
menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, reportsToolStripMenuItem, DoWorkToolStripMenuItem }); menuStrip1.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, reportsToolStripMenuItem, DoWorkToolStripMenuItem, mailToolStripMenuItem });
menuStrip1.Location = new Point(0, 0); menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1"; menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1125, 24); menuStrip1.Size = new Size(1125, 24);
@ -72,35 +73,35 @@
// packageToolStripMenuItem // packageToolStripMenuItem
// //
packageToolStripMenuItem.Name = "packageToolStripMenuItem"; packageToolStripMenuItem.Name = "packageToolStripMenuItem";
packageToolStripMenuItem.Size = new Size(180, 22); packageToolStripMenuItem.Size = new Size(149, 22);
packageToolStripMenuItem.Text = "Изделия"; packageToolStripMenuItem.Text = "Изделия";
packageToolStripMenuItem.Click += PackageToolStripMenuItem_Click; packageToolStripMenuItem.Click += PackageToolStripMenuItem_Click;
// //
// componentToolStripMenuItem // componentToolStripMenuItem
// //
componentToolStripMenuItem.Name = "componentToolStripMenuItem"; componentToolStripMenuItem.Name = "componentToolStripMenuItem";
componentToolStripMenuItem.Size = new Size(180, 22); componentToolStripMenuItem.Size = new Size(149, 22);
componentToolStripMenuItem.Text = "Компоненты"; componentToolStripMenuItem.Text = "Компоненты";
componentToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click; componentToolStripMenuItem.Click += ComponentsToolStripMenuItem_Click;
// //
// магазиныToolStripMenuItem // магазиныToolStripMenuItem
// //
магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem"; магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
магазиныToolStripMenuItem.Size = new Size(180, 22); магазиныToolStripMenuItem.Size = new Size(149, 22);
магазиныToolStripMenuItem.Text = "Магазины"; магазиныToolStripMenuItem.Text = "Магазины";
магазиныToolStripMenuItem.Click += ShopsToolStripMenuItem_Click; магазиныToolStripMenuItem.Click += ShopsToolStripMenuItem_Click;
// //
// ClientsToolStripMenuItem // ClientsToolStripMenuItem
// //
ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem"; ClientsToolStripMenuItem.Name = "ClientsToolStripMenuItem";
ClientsToolStripMenuItem.Size = new Size(180, 22); ClientsToolStripMenuItem.Size = new Size(149, 22);
ClientsToolStripMenuItem.Text = "Клиенты"; ClientsToolStripMenuItem.Text = "Клиенты";
ClientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click; ClientsToolStripMenuItem.Click += ClientsToolStripMenuItem_Click;
// //
// ImplementersToolStripMenuItem // ImplementersToolStripMenuItem
// //
ImplementersToolStripMenuItem.Name = "ImplementersToolStripMenuItem"; ImplementersToolStripMenuItem.Name = "ImplementersToolStripMenuItem";
ImplementersToolStripMenuItem.Size = new Size(180, 22); ImplementersToolStripMenuItem.Size = new Size(149, 22);
ImplementersToolStripMenuItem.Text = "Исполнители"; ImplementersToolStripMenuItem.Text = "Исполнители";
ImplementersToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click; ImplementersToolStripMenuItem.Click += ImplementersToolStripMenuItem_Click;
// //
@ -226,6 +227,13 @@
ButtonIssuedOrder.UseVisualStyleBackColor = true; ButtonIssuedOrder.UseVisualStyleBackColor = true;
ButtonIssuedOrder.Click += ButtonIssuedOrder_Click; ButtonIssuedOrder.Click += ButtonIssuedOrder_Click;
// //
// mailToolStripMenuItem
//
mailToolStripMenuItem.Name = "mailToolStripMenuItem";
mailToolStripMenuItem.Size = new Size(62, 20);
mailToolStripMenuItem.Text = "Письма";
mailToolStripMenuItem.Click += MailToolStripMenuItem_Click;
//
// FormMain // FormMain
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
@ -271,5 +279,6 @@
private ToolStripMenuItem ImplementersToolStripMenuItem; private ToolStripMenuItem ImplementersToolStripMenuItem;
private ToolStripMenuItem DoWorkToolStripMenuItem; private ToolStripMenuItem DoWorkToolStripMenuItem;
private Button ButtonIssuedOrder; private Button ButtonIssuedOrder;
private ToolStripMenuItem mailToolStripMenuItem;
} }
} }

View File

@ -3,6 +3,7 @@ using SoftwareInstallationContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.BusinessLogicsContracts;
using SoftwareInstallationView; using SoftwareInstallationView;
using SoftwareInstallationView;
namespace SoftwareInstallationView namespace SoftwareInstallationView
{ {
@ -254,5 +255,13 @@ namespace SoftwareInstallationView
form.ShowDialog(); form.ShowDialog();
} }
} }
private void MailToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormViewMail));
if (service is FormViewMail form)
{
form.ShowDialog();
}
}
} }
} }

View File

@ -0,0 +1,149 @@
namespace SoftwareInstallationView
{
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 SoftwareInstallationBusinessLogic.MailWorker;
using SoftwareInstallationContracts.BusinessLogicsContracts;
using SoftwareInstallationContracts.ViewModels;
using Microsoft.Extensions.Logging;
using MimeKit;
namespace SoftwareInstallationView
{
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 SoftwareInstallationView
{
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 SoftwareInstallationBusinessLogic.MailWorker;
using SoftwareInstallationContracts.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 SoftwareInstallationContracts.ViewModels;
namespace SoftwareInstallationView
{
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

@ -1,4 +1,4 @@
using SoftwareInstallationBusinessLogic.BusinessLogics; using SoftwareInstallationBusinessLogic.BusinessLogics;
using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.BusinessLogicsContracts;
using SoftwareInstallationContracts.StoragesContracts; using SoftwareInstallationContracts.StoragesContracts;
using SoftwareInstallationDatabaseImplement.Implements; using SoftwareInstallationDatabaseImplement.Implements;
@ -10,8 +10,8 @@ using NLog.Extensions.Logging;
using SoftwareInstallationBusinessLogic.OfficePackage.Implements; using SoftwareInstallationBusinessLogic.OfficePackage.Implements;
using SoftwareInstallationBusinessLogic.OfficePackage; using SoftwareInstallationBusinessLogic.OfficePackage;
using SoftwareInstallationContracts.StoragesContract; using SoftwareInstallationContracts.StoragesContract;
using SoftwareInstallationBusinessLogic; using SoftwareInstallationBusinessLogic.MailWorker;
using SoftwareInstallationContracts.BusinessLogicsContracts; using SoftwareInstallationContracts.BindingModels;
using SoftwareInstallationView; using SoftwareInstallationView;
namespace SoftwareInstallationView namespace SoftwareInstallationView
@ -32,8 +32,30 @@ namespace SoftwareInstallationView
var services = new ServiceCollection(); var services = new ServiceCollection();
ConfigureServices(services); ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider(); _serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>()); try
} {
var mailSender = _serviceProvider.GetService<AbstractMailWorker>();
mailSender?.MailConfig(new MailConfigBindingModel
{
MailLogin = System.Configuration.ConfigurationManager.AppSettings["MailLogin"] ?? string.Empty,
MailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"] ?? string.Empty,
SmtpClientHost = System.Configuration.ConfigurationManager.AppSettings["SmtpClientHost"] ?? string.Empty,
SmtpClientPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SmtpClientPort"]),
PopHost = System.Configuration.ConfigurationManager.AppSettings["PopHost"] ?? string.Empty,
PopPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PopPort"])
});
// ñîçäàåì òàéìåð
var timer = new System.Threading.Timer(new TimerCallback(MailCheck!), null, 0, 100000);
}
catch (Exception ex)
{
var logger = _serviceProvider.GetService<ILogger>();
logger?.LogError(ex, "Îøèáêà ðàáîòû ñ ïî÷òîé");
}
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
private static void ConfigureServices(ServiceCollection services) private static void ConfigureServices(ServiceCollection services)
{ {
services.AddLogging(option => services.AddLogging(option =>
@ -47,7 +69,9 @@ namespace SoftwareInstallationView
services.AddTransient<IClientStorage, ClientStorage>(); services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IImplementerStorage, ImplementerStorage>(); services.AddTransient<IImplementerStorage, ImplementerStorage>();
services.AddTransient<IShopStorage, ShopStorage>(); services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>(); services.AddTransient<IMessageInfoStorage, MessageInfoStorage>();
services.AddTransient<IMessageInfoLogic, MessageInfoLogic>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>(); services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IPackageLogic, PackageLogic>(); services.AddTransient<IPackageLogic, PackageLogic>();
services.AddTransient<IShopLogic, ShopLogic>(); services.AddTransient<IShopLogic, ShopLogic>();
@ -73,9 +97,13 @@ namespace SoftwareInstallationView
services.AddTransient<FormViewClients>(); services.AddTransient<FormViewClients>();
services.AddTransient<FormViewImplementers>(); services.AddTransient<FormViewImplementers>();
services.AddTransient<FormImplementer>(); services.AddTransient<FormImplementer>();
services.AddTransient<FormViewMail>();
services.AddTransient<FormReplyMail>();
services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
services.AddTransient<AbstractSaveToWord, SaveToWord>(); services.AddTransient<AbstractSaveToWord, SaveToWord>();
services.AddTransient<AbstractSaveToPdf, SaveToPdf>(); services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
} services.AddSingleton<AbstractMailWorker, MailKitWorker>();
} }
private static void MailCheck(object obj) => ServiceProvider?.GetService<AbstractMailWorker>()?.MailCheck();
}
} }

View File

@ -29,6 +29,9 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Update="App.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="ReportGroupOrders.rdlc"> <None Update="ReportGroupOrders.rdlc">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>