Ненавижу сериализацию словарей

This commit is contained in:
Илья Федотов 2024-05-30 20:32:16 +04:00
parent 92b18d3a1a
commit ee3dcbb46e
11 changed files with 218 additions and 143 deletions

View File

@ -12,7 +12,7 @@ namespace ElectronicsShopDataBaseImplement
optionsBuilder)
{
if (optionsBuilder.IsConfigured == false) {
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-E2VPEN3\SQLEXPRESS;Initial Catalog=ElectronicsShopDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-O0N00SH\SQLEXPRESS;Initial Catalog=ElectronicsShopDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}

View File

@ -69,11 +69,18 @@ namespace ElectronicsShopDataBaseImplement.Implements
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.ID.HasValue && (model.DateFrom == null || model.DateTo == null))
using var context = new Database();
if (!model.ID.HasValue && (model.DateFrom == null || model.DateTo == null))
{
return new();
}
using var context = new Database();
else if (model.ClientID.HasValue) {
return context.Orders
.Include (x => x.Products)
.Where(x => x.ClientID == model.ClientID)
.Select(x => x.GetViewModel)
.ToList();
}
return context.Orders
.Include(x => x.Products)
.ThenInclude(x => x._product)

View File

@ -116,7 +116,7 @@ namespace ElectronicsShopEmployeeApp.Controllers {
Price = price,
CostNum = costNum
});
Response.Redirect("CostItem");
}
[HttpGet]

View File

@ -3,6 +3,7 @@ using ElectronicsShopContracts.BusinessLogicContracts;
using ElectronicsShopContracts.SearchModels;
using ElectronicsShopContracts.ViewModels;
using ElectronicsShopDataBaseImplement.Models;
using ElectronicsShopDataModels.Models;
using Microsoft.AspNetCore.Mvc;
namespace ElectronicsShopRestAPI.Controllers {
@ -14,13 +15,15 @@ namespace ElectronicsShopRestAPI.Controllers {
private readonly ILogger _logger;
private readonly IProductLogic _product;
private readonly IOrderLogic _order;
private Dictionary<int, (IProductModel, int)> _ProductList;
private int? _ID;
public MainController(ILogger<MainController> logger, IProductLogic product,
IOrderLogic orderLogic) {
_logger = logger;
_product = product;
_order = orderLogic;
_ProductList = new Dictionary<int, (IProductModel, int)>();
}
[HttpGet]
@ -65,6 +68,17 @@ namespace ElectronicsShopRestAPI.Controllers {
}
}
[HttpGet]
public OrderViewModel? GetOrder(int _clientID) {
try {
return _order.ReadElement(new OrderSearchModel { ClientID = _clientID });
}
catch (Exception ex) {
_logger.LogError(ex, $"Ошибка получения данных clientid = {_clientID}");
throw;
}
}
[HttpPost]
public void CreateOrder(OrderBindingModel model) {
@ -78,43 +92,10 @@ namespace ElectronicsShopRestAPI.Controllers {
throw;
}
}
[HttpGet]
public List<OrderViewModel>? GetAddProduct(int _clientID,int _orderID)
{
try
{
return _order.ReadList(new OrderSearchModel
{
ID = _orderID,
ClientID = _clientID
});
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка получения списка заказов клиента id = {Id} ", _clientID);
throw;
}
}
[HttpPost]
public void AddProduct(OrderBindingModel model)
{
try
{
var order=_order.ReadElement(new OrderSearchModel { ID = model.ID });//возвращает null
if (model != null&& order!=null)
{
order.ProductList = model.ProductList;
order.Sum += model.Sum;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка создания заказа");
throw;
}
}
[HttpPost]
public void SaveOrder(Dictionary<int, (IProductModel, int)> list) {
}
}
}

View File

@ -1,5 +1,7 @@
using ElectronicsShopContracts.ViewModels;
using ElectronicsShopContracts.BindingModels;
using ElectronicsShopContracts.ViewModels;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Text;
@ -20,7 +22,7 @@ namespace ElectronicsShopUserApp {
var result = response.Result.Content.ReadAsStringAsync().Result;
if (response.Result.IsSuccessStatusCode) {
return JsonConvert.DeserializeObject<T>(result);
}
}
else {
throw new Exception(result);
}
@ -37,5 +39,26 @@ namespace ElectronicsShopUserApp {
throw new Exception(result);
}
}
public static void PostDictRequest<T>(string requstUrl, OrderBindingModel model) {
var dict = new Dictionary<string, (string, string)>();
foreach (var item in model.ProductList) {
var key = item.Key.ToString();
var item1 = JsonConvert.SerializeObject(item.Value.Item1);
var item2 = item.Value.Item2.ToString();
dict.Add(key, (item1, item2));
}
var dictjs = JsonConvert.SerializeObject(dict);
var data = new StringContent(dictjs, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requstUrl, data,);
var result = response.Result.Content.ReadAsStringAsync().Result;
if (!response.Result.IsSuccessStatusCode) {
throw new Exception(result);
}
}
}
}

View File

@ -12,11 +12,12 @@ using System.Runtime.Serialization;
namespace ElectronicsShopUserApp.Controllers {
public class HomeController : Controller {
private readonly ILogger<HomeController> _logger;
//private readonly IOrderLogic _order;
private Dictionary<int, (IProductModel, int)> _productList;
//private readonly IOrderLogic _order;
public HomeController(ILogger<HomeController> logger/*, IOrderLogic orderLogic*/) {
public HomeController(ILogger<HomeController> logger/*, IOrderLogic orderLogic*/) {
_logger = logger;
//_order = orderLogic;
_productList = new Dictionary<int, (IProductModel, int)>();
}
public IActionResult Index() {
@ -95,26 +96,56 @@ namespace ElectronicsShopUserApp.Controllers {
return;
}
[HttpGet]
public IActionResult CreateOrders() {
public IActionResult Orders() {
if (APIClient.Client == null) {
return Redirect("~/Home/Enter");
}
return View(APIClient.GetRequset<List<OrderViewModel>>($"api/main/getorders?_clientid={APIClient.Client.ID}"));
}
ViewBag.Products =APIClient.GetRequset<List<ProductViewModel>>("api/main/getproducts");
return View();
[HttpGet]
public IActionResult CreateOrder() {
var view = APIClient.GetRequset<OrderViewModel>($"api/main/getorder?_clientid={APIClient.Client?.ID}") ?? new OrderViewModel {
ProductList = _productList
};
return View(view);
}
[HttpGet]
public IActionResult AddProduct() {
ViewBag.Products = APIClient.GetRequset<List<ProductViewModel>>($"api/main/getproducts");
return View();
}
[HttpPost]
public void CreateOrders(OrderBindingModel order) {
if (APIClient.Client == null)
{
throw new Exception("Âû êàê ñóäà ïîïàëè? Ñóäà âõîä òîëüêî àâòîðèçîâàííûì");
[HttpPost]
public void AddProduct(double sum, int product, int count) {
if (APIClient.Client == null) {
throw new Exception("Òîëüêî äëÿ àâòîðèçîâàíûõ");
}
if (sum <= 0) {
throw new Exception("Ñóììà çàòðàò äîëæíà áûòü áîëüøå 0");
}
var _product = APIClient.GetRequset<ProductViewModel>($"api/main/getproduct?_productid={product}");
_product.Price = sum;
if (_productList.ContainsKey(product)) {
_productList[product] = (_product, count);
}
if (order.ProductList.Count > 0)
{
throw new Exception("Êîëè÷åñòâî è ñóììà äîëæíû áûòü áîëüøå 0");
else {
_productList.Add(product, (_product, count));
}
Response.Redirect("Index");
}
APIClient.PostDictRequest<OrderBindingModel>($"api/main/saveorder", new OrderBindingModel {
ProductList = _productList,
Sum = CalcAll(_productList),
ClientID = APIClient.Client.ID,
});
Response.Redirect("CreateOrder");
}
[HttpPost]
private double CalcAll(Dictionary<int, (IProductModel, int)> ProductList)
private double CalcAll(Dictionary<int, (IProductModel, int)> ProductList)
{
Double Sum = 0;
foreach (var ProductItem in ProductList)
@ -126,30 +157,8 @@ namespace ElectronicsShopUserApp.Controllers {
[HttpPost]
public double Calc(int count, int product)
{
var prod =
APIClient.GetRequset<ProductViewModel>($"api/main/getproduct?_productid={product}"
);
var prod = APIClient.GetRequset<ProductViewModel>($"api/main/getproduct?_productid={product}");
return count * (prod?.Price ?? 1);
}
[HttpGet]
public IActionResult AddProduct()
{
ViewBag.Products = APIClient.GetRequset<List<ProductViewModel>>("api/main/getproducts");
return View();
}
[HttpPost]
public void AddProduct(int count/*, int product*/)
{
if (APIClient.Client == null)
{
throw new Exception("Âû êàê ñóäà ïîïàëè? Ñóäà âõîä òîëüêî àâòîðèçîâàííûì");
}
if (count <= 0)
{
throw new Exception("Êîëè÷åñòâî è ñóììà äîëæíû áûòü áîëüøå 0");
}
Response.Redirect("CreateOrder");
}
}
}

View File

@ -8,12 +8,7 @@
<div class="row">
<div class="col-4">Продукты:</div>
<div class="col-8">
<select id="product" name="product" class="form-control">
@foreach (var product in ViewBag.Products)
{
<option value="@product.ID">@product.ProductName</option>
}
</select>
<select id="product" name="product" class="form-control" asp-items="@(new SelectList(ViewBag.Products, "ID", "ProductName"))"> </select>
</div>
</div>
<div class="row">
@ -52,9 +47,8 @@
method: "POST",
url: "/Home/Calc",
data: { count: count, product: product },
success: function (result) {
var roundedResult = parseFloat(result).toFixed(2);
$("#sum").val(roundedResult);
success: function (result) {
$("#sum").val(result);
}
});
};

View File

@ -0,0 +1,50 @@
@using ElectronicsShopContracts.ViewModels
@model OrderViewModel
@{
ViewData["Title"] = "CreateOrder";
}
<div class="text-center">
<h1 class="display-4">Создание корзины</h1>
</div>
<div class=" text-center">
<p>
<a asp-action="AddProduct">Добавить товар</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Продукт
</th>
<th>
Количество
</th>
<th>
Сумма
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.ProductList) {
<tr>
<th>
@Html.DisplayFor(modelItem => item.Value.Item1.ProductName);
</th>
<th>
@Html.DisplayFor(modelItem => item.Value.Item2);
</th>
<th>
@Html.DisplayFor(modelItem => (item.Value.Item1.Price * item.Value.Item2));
</th>
<td>
<a class="btn btn-primary btn-sm" asp-action="DeleteProductOrder" asp-></a>
</td>
</tr>
}
</tbody>
</table>
</div>

View File

@ -1,45 +0,0 @@
@using ElectronicsShopContracts.ViewModels
@model OrderViewModel
@{
ViewData["Title"] = "CreateOrders";
}
<div class="text-center">
<h1 class="display-4">Корзина</h1>
@{
<table class="table">
<thead>
<th>
<th>
Продукт
</th>
<th>
Количество
</th>
<th>
Сумма
</th>
</th>
</thead>
<tbody>
@if(Model!=null){
@foreach (var item in Model.ProductList)
{
<th>
<th>
@Html.DisplayFor(modelItem => item.Value.Item1.ProductName)
</th>
<th>
@Html.DisplayFor(modelItem => item.Value.Item2)
</th>
<th>
@Html.DisplayFor(modelItem => item.Value.Item1.Price*item.Value.Item2)
</th>
</th>
}
}
</tbody>
</table>
}
</div>

View File

@ -0,0 +1,59 @@
@using ElectronicsShopContracts.ViewModels
@model List<OrderViewModel>
@{
ViewData["Title"] = "Orders";
}
<div class="text-center">
<h1 class="display-4">Корзины</h1>
</div>
<div class="text-center">
@{
if (Model == null) {
<h3 class="display-4">Авторизируйтесь</h3>
return;
}
<p>
<a asp-action="CreateOrder">Добавить корзину</a>
</p>
<table class="table">
<thead>
<tr>
<th>
Номер
</th>
<th>
Дата создания
</th>
<th>
Сумма
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<th>
@Html.DisplayFor(modelItem => item.ID)
</th>
<th>
@Html.DisplayFor(modelItem => item.DateCreate)
</th>
<th>
@Html.DisplayFor(modelItem => item.Sum)
</th>
<td>
<a class="btn btn-primary btn-sm" asp-action="EditCostItem" asp-route-ID="@item.ID">Изменить</a>
<a class="btn btn-primary btn-sm" asp-action="DeleteCostItem" asp-route-ID="@item.ID">Удалить</a>
</td>
</tr>
}
</tbody>
</table>
}
</div>

View File

@ -32,10 +32,7 @@
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Register">Регистрация</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="CreateOrders">Создание корзин</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="AddProduct">Каталог</a>
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Orders">Корзины</a>
</li>
</ul>
</div>