PIbd-22. Bulatova K.R. LabWork_02_Hard #9

Closed
bulatova_karina wants to merge 6 commits from LabWork_02_Hard into LabWork_02
51 changed files with 2466 additions and 199 deletions

View File

@ -3,7 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
@ -24,7 +24,7 @@ namespace ComputersShopBusinessLogic.BusinessLogics
public List<ComponentViewModel>? ReadList(ComponentSearchModel? model)
{
_logger.LogInformation("ReadList. ComponentName:{ComponentName}. Id:{Id}", model?.ComponentName, model?.Id);
var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFiltredList(model);
var list = model == null ? _componentStorage.GetFullList() : _componentStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");

View File

@ -4,7 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
@ -23,13 +23,15 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
public List<ComputerViewModel>? ReadList(ComputerSearchModel? model)
{
_logger.LogInformation("ReadList. ComputerName:{ComputerName}. Id:{Id}", model?.ComputerName, model?.Id);
var list = model == null ? _computerStorage.GetFullList() : _computerStorage.GetFiltredList(model);
_logger.LogInformation("ReadList. ComputerName:{ComputerName}.Id:{ Id}", model?.ComputerName, model?.Id);
var list = model == null ? _computerStorage.GetFullList() : _computerStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
@ -39,19 +41,23 @@ namespace ComputersShopBusinessLogic.BusinessLogics
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ComputerName:{ComputerName}. Id:{Id}", model.ComputerName, model.Id);
_logger.LogInformation("ReadElement. ComputerName:{ComputerName}.Id:{ Id}", model.ComputerName, model.Id);
var element = _computerStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ComputerBindingModel model)
{
CheckModel(model);
if (_computerStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
@ -62,6 +68,7 @@ namespace ComputersShopBusinessLogic.BusinessLogics
public bool Update(ComputerBindingModel model)
{
CheckModel(model);
if (_computerStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
@ -73,6 +80,7 @@ namespace ComputersShopBusinessLogic.BusinessLogics
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_computerStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
@ -92,20 +100,20 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
if (string.IsNullOrEmpty(model.ComputerName))
{
throw new ArgumentNullException("Нет названия компьютера", nameof(model.ComputerName));
throw new ArgumentNullException("Нет названия изделия", nameof(model.ComputerName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена должна быть больше 0", nameof(model.Price));
throw new ArgumentNullException("Цена изделия должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Computer. ComputerName:{ComputerName}. Cost:{Cost}. Id:{Id}", model.ComputerName, model.Price, model.Id);
_logger.LogInformation("Computer. ComputerName:{ComputerName}.Price:{ Price}. Id: { Id}", model.ComputerName, model.Price, model.Id);
var element = _computerStorage.GetElement(new ComputerSearchModel
{
ComputerName = model.ComputerName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компьютер с таким названием уже есть");
throw new InvalidOperationException("Изделие с таким названием уже есть");
}
}
}

View File

@ -4,11 +4,12 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Enums;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace ComputersShopBusinessLogic.BusinessLogics
@ -17,20 +18,28 @@ namespace ComputersShopBusinessLogic.BusinessLogics
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage)
private IShopStorage _shopStorage;
private IShopLogic _shopLogic;
private IComputerStorage _computerStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage, IShopStorage shopStorage, IShopLogic shopLogic, IComputerStorage computerStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_shopStorage = shopStorage;
_shopLogic = shopLogic;
_computerStorage = computerStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. Id:{Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFiltredList(model);
_logger.LogInformation("ReadList. Order.Id:{ Id}", model?.Id);
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
@ -39,10 +48,12 @@ namespace ComputersShopBusinessLogic.BusinessLogics
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен)
{
_logger.LogWarning("Wrong order status. Insert operation failed");
_logger.LogWarning("Insert operation failed. Order status incorrect.");
return false;
}
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
@ -50,51 +61,17 @@ namespace ComputersShopBusinessLogic.BusinessLogics
}
return true;
}
public bool ChangeStatus(OrderBindingModel model, OrderStatus newStatus)
{
var viewModel = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (viewModel == null)
{
throw new ArgumentNullException(nameof(viewModel));
}
if (viewModel.Status + 1 != newStatus)
{
_logger.LogWarning("Status change operation failed");
return false;
}
model.Status = newStatus;
model.ComputerId = viewModel.ComputerId;
model.Count = viewModel.Count;
model.Sum = viewModel.Sum;
model.DateCreate = viewModel.DateCreate;
if (model.Status == OrderStatus.Готов)
{
model.DateImplement = DateTime.Now;
}
else
{
model.DateImplement = viewModel.DateImplement;
}
CheckModel(model, false);
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Status change operation failed");
return false;
}
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выполняется);
return StatusUpdate(model, OrderStatus.Выполняется);
}
public bool FinishOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Готов);
return StatusUpdate(model, OrderStatus.Выдан);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выдан);
return StatusUpdate(model, OrderStatus.Готов);
}
private void CheckModel(OrderBindingModel model, bool withParams = true)
{
@ -106,19 +83,135 @@ namespace ComputersShopBusinessLogic.BusinessLogics
{
return;
}
if (model.Sum <= 0)
if (model.ComputerId < 0)
{
throw new ArgumentNullException("Цена должна быть больше 0", nameof(model.Sum));
throw new ArgumentNullException("Некорректный идентификатор изделия", nameof(model.ComputerId));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество изделий должно быть больше 0", nameof(model.Count));
throw new ArgumentNullException("Количество изделий в заказе должно быть больше 0", nameof(model.Count));
}
if (model.DateImplement != null && model.DateImplement < model.DateCreate)
if (model.Sum <= 0)
{
throw new ArithmeticException("Дата завершения не может быть раньше даты начала");
throw new ArgumentNullException("Сумма заказа должна быть больше 0", nameof(model.Sum));
}
_logger.LogInformation("Order. Id:{Id}. Sum:{Sum}. ComputerId:{ComputerId}", model.Id, model.Sum, model.ComputerId);
_logger.LogInformation("Order. OrderID:{Id}.Sum:{ Sum}. ComputerId: { ComputerId}", model.Id, model.Sum, model.ComputerId);
}
private bool StatusUpdate(OrderBindingModel model, OrderStatus newStatus)
{
var element = _orderStorage.GetElement(new OrderSearchModel
{
Id = model.Id
});
if (element == null)
{
throw new ArgumentNullException(nameof(model));
}
if (element.Status + 1 != newStatus)
{
_logger.LogWarning("Change status operation failed");
return false;
}
model.Status = newStatus;
if (newStatus == OrderStatus.Выдан)
{
var computer = _computerStorage.GetElement(new ComputerSearchModel { Id = element.ComputerId });
if (computer == null)
{
_logger.LogWarning("Status change error. Computer not found");
return false;
}
if (!CheckSupply(computer, element.Count))
{
_logger.LogWarning("Status change error. Shop is overflowed");
return false;
}
}
if (model.Status == OrderStatus.Выдан)
{
model.DateImplement = DateTime.Now;
}
else
{
model.DateImplement = element.DateImplement;
}
CheckModel(model, false);
if (_orderStorage.Update(model) == null)
{
_logger.LogWarning("Change status operation failed");
return false;
}
return true;
}
public bool CheckSupply(IComputerModel model, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check supply operation error. Computers count < 0");
return false;
}
int sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxComputers).Sum();
int sumCount = _shopStorage.GetFullList().Select(x => x.ShopComputers.Select(y => y.Value.Item2).Sum()).Sum();
int free = sumCapacity - sumCount;
if (free < count)
{
_logger.LogWarning("Check supply error. No place for new computers");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
free = shop.MaxComputers;
foreach (var computer in shop.ShopComputers)
{
free -= computer.Value.Item2;
}
if (free == 0)
{
continue;
}
if (free >= count)
{
if (_shopLogic.AddComputerInShop(new()
{
Id = shop.Id
}, model, count))
{
count = 0;
}
else
{
_logger.LogWarning("Supply error");
return false;
}
}
else
{
if (_shopLogic.AddComputerInShop(new()
{
Id = shop.Id
}, model, free))
{
count -= free;
}
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
}
}

View File

@ -0,0 +1,184 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace ComputersShopBusinessLogic.BusinessLogics
{
public class ShopLogic : IShopLogic
{
private readonly ILogger _logger;
private readonly IShopStorage _shopStorage;
public ShopLogic(ILogger<ShopLogic> logger, IShopStorage shopStorage)
{
_logger = logger;
_shopStorage = shopStorage;
}
public List<ShopViewModel>? ReadList(ShopSearchModel? model)
{
_logger.LogInformation("ReadList. ShopName:{ShopName}.Id:{ Id}", model?.ShopName, model?.Id);
var list = model == null ? _shopStorage.GetFullList() : _shopStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ShopViewModel? ReadElement(ShopSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id);
var element = _shopStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("ReadElement element not found");
return null;
}
_logger.LogInformation("ReadElement find. Id:{Id}", element.Id);
return element;
}
public bool Create(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ShopBindingModel model)
{
CheckModel(model);
if (_shopStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ShopBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_shopStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
public bool AddComputerInShop(ShopSearchModel model, IComputerModel computer, int count)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (count <= 0)
{
throw new ArgumentException("Количество изделий должно быть больше 0", nameof(count));
}
_logger.LogInformation("AddComputerInShop. ShopName:{ShopName}.Id:{ Id}", model.ShopName, model.Id);
var element = _shopStorage.GetElement(model);
if (element == null)
{
_logger.LogWarning("AddComputerInShop element not found");
return false;
}
_logger.LogInformation("AddComputerInShop find. Id:{Id}", element.Id);
var countComputers = element.ShopComputers.Select(x => x.Value.Item2).Sum();
if (element.MaxComputers - countComputers < count)
{
_logger.LogWarning("Shop is overflowed");
return false;
}
if (element.ShopComputers.TryGetValue(computer.Id, out var pair))
{
element.ShopComputers[computer.Id] = (computer, count + pair.Item2);
_logger.LogInformation("AddComputerInShop. Added {count} {computer} to '{ShopName}' shop", count, computer.ComputerName, element.ShopName);
}
else
{
element.ShopComputers[computer.Id] = (computer, count);
_logger.LogInformation("AddComputerInShop. Added {count} new computer {computer} to '{ShopName}' shop", count, computer.ComputerName, element.ShopName);
}
_shopStorage.Update(new()
{
Id = element.Id,
Address = element.Address,
ShopName = element.ShopName,
DateOpening = element.DateOpening,
ShopComputers = element.ShopComputers,
MaxComputers = element.MaxComputers
});
return true;
}
public bool SellComputers(IComputerModel computer, int count)
{
if (computer == null)
{
throw new ArgumentNullException(nameof(computer));
}
if (count <= 0)
{
throw new ArgumentException("Количество изделий должно быть больше 0", nameof(count));
}
if (_shopStorage.SellComputers(computer, count))
{
_logger.LogInformation("Selling sucsess");
return true;
}
_logger.LogInformation("Selling failed");
return false;
}
private void CheckModel(ShopBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ShopName))
{
throw new ArgumentNullException("Нет названия магазина", nameof(model.ShopName));
}
_logger.LogInformation("Shop. ShopName:{ShopName}.Address:{ Address}. Id:{ Id}", model.ShopName, model.Address, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
ShopName = model.ShopName
});
if (element != null && element.Id != model.Id && element.ShopName == model.ShopName)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
namespace ComputersShopContracts.BindingModels
{
public class ShopBindingModel : IShopModel
{
public int Id { get; set; }
public string ShopName { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public DateTime DateOpening { get; set; } = DateTime.Now;
public Dictionary<int, (IComputerModel, int)> ShopComputers
{
get;
set;
} = new();
public int MaxComputers { get; set; }
}
}

View File

@ -7,7 +7,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.BuisnessLogicsContracts
namespace ComputersShopContracts.BusinessLogicsContracts
{
public interface IComponentLogic
{

View File

@ -7,7 +7,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.BuisnessLogicsContracts
namespace ComputersShopContracts.BusinessLogicsContracts
{
public interface IComputerLogic
{

View File

@ -7,7 +7,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.BuisnessLogicsContracts
namespace ComputersShopContracts.BusinessLogicsContracts
{
public interface IOrderLogic
{

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
namespace ComputersShopContracts.BusinessLogicsContracts
{
public interface IShopLogic
{
List<ShopViewModel>? ReadList(ShopSearchModel? model);
ShopViewModel? ReadElement(ShopSearchModel model);
bool Create(ShopBindingModel model);
bool Update(ShopBindingModel model);
bool Delete(ShopBindingModel model);
bool AddComputerInShop(ShopSearchModel model, IComputerModel computer, int count);
bool SellComputers(IComputerModel computer, int count);
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopContracts.SearchModels
{
public class ShopSearchModel
{
public int? Id { get; set; }
public string? ShopName { get; set; }
}
}

View File

@ -13,7 +13,7 @@ namespace ComputersShopContracts.StoragesContracts
public interface IComponentStorage
{
List<ComponentViewModel> GetFullList();
List<ComponentViewModel> GetFiltredList(ComponentSearchModel model);
List<ComponentViewModel> GetFilteredList(ComponentSearchModel model);
ComponentViewModel? GetElement(ComponentSearchModel model);
ComponentViewModel? Insert(ComponentBindingModel model);
ComponentViewModel? Update(ComponentBindingModel model);

View File

@ -13,7 +13,7 @@ namespace ComputersShopContracts.StoragesContracts
public interface IComputerStorage
{
List<ComputerViewModel> GetFullList();
List<ComputerViewModel> GetFiltredList(ComputerSearchModel model);
List<ComputerViewModel> GetFilteredList(ComputerSearchModel model);
ComputerViewModel? GetElement(ComputerSearchModel model);
ComputerViewModel? Insert(ComputerBindingModel model);
ComputerViewModel? Update(ComputerBindingModel model);

View File

@ -12,7 +12,7 @@ namespace ComputersShopContracts.StoragesContracts
public interface IOrderStorage
{
List<OrderViewModel> GetFullList();
List<OrderViewModel> GetFiltredList(OrderSearchModel model);
List<OrderViewModel> GetFilteredList(OrderSearchModel model);
OrderViewModel? GetElement(OrderSearchModel model);
OrderViewModel? Insert(OrderBindingModel model);
OrderViewModel? Update(OrderBindingModel model);

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
namespace ComputersShopContracts.StoragesContracts
{
public interface IShopStorage
{
List<ShopViewModel> GetFullList();
List<ShopViewModel> GetFilteredList(ShopSearchModel model);
ShopViewModel? GetElement(ShopSearchModel model);
ShopViewModel? Insert(ShopBindingModel model);
ShopViewModel? Update(ShopBindingModel model);
ShopViewModel? Delete(ShopBindingModel model);
bool SellComputers(IComputerModel model, int count);
bool CheckCount(IComputerModel model, int count);
}
}

View File

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
namespace ComputersShopContracts.ViewModels
{
public class ShopViewModel : IShopModel
{
public int Id { get; set; }
[DisplayName("Название магазина")]
public string ShopName { get; set; } = string.Empty;
[DisplayName("Адрес магазина")]
public string Address { get; set; } = string.Empty;
[DisplayName("Дата открытия")]
public DateTime DateOpening { get; set; } = DateTime.Now;
public Dictionary<int, (IComputerModel, int)> ShopComputers
{
get;
set;
} = new();
[DisplayName("Максимальное количество изделий")]
public int MaxComputers { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopDataModels.Models
{
public interface IShopModel : IId
{
string ShopName { get; }
string Address { get; }
DateTime DateOpening { get; }
Dictionary<int, (IComputerModel, int)> ShopComputers { get; }
int MaxComputers { get; }
}
}

View File

@ -11,35 +11,35 @@ namespace ComputersShopFileImplement
{
internal class DataFileSingleton
{
private static DataFileSingleton? instance;
public readonly string ComponentFileName = "Component.xml";
public readonly string OrderFileName = "Order.xml";
public readonly string ComputerFileName = "Computer.xml";
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Computer> Computers { get; private set; }
public static DataFileSingleton GetInstance()
{
if (instance == null)
{
instance = new DataFileSingleton();
}
return instance;
}
public void SaveComponents() => SaveData(Components, ComponentFileName,
"Components", x => x.GetXElement);
public void SaveComputers() => SaveData(Computers, ComputerFileName,
"Computers", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName,
"Orders", x => x.GetXElement);
private static DataFileSingleton? _instance;
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string ComputerFileName = "Computer.xml";
private readonly string ShopFileName = "Shop.xml";
public List<Component> Components { get; set; }
public List<Order> Orders { get; set; }
public List<Computer> Computers { get; set; }
public List<Shop> Shops { get; set; }
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x => Component.Create(x)!)!;
Computers = LoadData(ComputerFileName, "Computer", x => Computer.Create(x)!)!;
Orders = LoadData(OrderFileName, "Order", x => Order.Create(x)!)!;
Shops = LoadData(ShopFileName, "Shop", x => Shop.Create(x)!)!;
}
private static List<T>? LoadData<T>(string filename, string xmlNodeName,
Func<XElement, T> selectFunction)
public static DataFileSingleton GetInstance()
{
if (_instance == null)
{
_instance = new DataFileSingleton();
}
return _instance;
}
public void SaveComponents() => SaveData(Components, ComponentFileName, "Components", x => x.GetXElement);
public void SaveComputers() => SaveData(Computers, ComputerFileName, "Computers", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName, "Orders", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName, "Shops", x => x.GetXElement);
private static List<T>? LoadData<T>(string filename, string xmlNodeName, Func<XElement, T> selectFunction)
{
if (File.Exists(filename))
{
@ -47,8 +47,7 @@ namespace ComputersShopFileImplement
}
return new List<T>();
}
private static void SaveData<T>(List<T> data, string filename,
string xmlNodeName, Func<T, XElement> selectFunction)
private static void SaveData<T>(List<T> data, string filename, string xmlNodeName, Func<T, XElement> selectFunction)
{
if (data != null)
{

View File

@ -14,67 +14,76 @@ namespace ComputersShopFileImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
private readonly DataFileSingleton source;
private readonly DataFileSingleton _source;
public ComponentStorage()
{
source = DataFileSingleton.GetInstance();
_source = DataFileSingleton.GetInstance();
}
public List<ComponentViewModel> GetFullList()
{
return source.Components.Select(x => x.GetViewModel).ToList();
return _source.Components
.Select(x => x.GetViewModel)
.ToList();
}
public List<ComponentViewModel> GetFiltredList(ComponentSearchModel model)
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
return source.Components
return _source.Components
.Where(x => x.ComponentName.Contains(model.ComponentName))
.Select(x => x.GetViewModel)
.ToList();
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (!string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
return source.Components
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComponentName) &&
x.ComponentName == model.ComponentName) || (model.Id.HasValue &&
x.Id == model.Id))?.GetViewModel;
return _source.Components
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ComponentName) &&
x.ComponentName == model.ComponentName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
model.Id = source.Components.Count > 0 ? source.Components.Max(x => x.Id) + 1 : 1;
model.Id = _source.Components.Count > 0 ? _source.Components.Max(x => x.Id) + 1 : 1;
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
source.Components.Add(newComponent);
source.SaveComponents();
_source.Components.Add(newComponent);
_source.SaveComponents();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
var component = source.Components.FirstOrDefault(x => x.Id == model.Id);
var component = _source.Components.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
source.SaveComponents();
_source.SaveComponents();
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
var element = source.Components.FirstOrDefault(x => x.Id == model.Id);
var element = _source.Components.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Components.Remove(element);
source.SaveComponents();
_source.Components.Remove(element);
_source.SaveComponents();
return element.GetViewModel;
}
return null;

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using ComputersShopContracts.BindingModels;
@ -13,67 +14,76 @@ namespace ComputersShopFileImplement.Implements
{
public class ComputerStorage : IComputerStorage
{
private readonly DataFileSingleton source;
private readonly DataFileSingleton _source;
public ComputerStorage()
{
source = DataFileSingleton.GetInstance();
_source = DataFileSingleton.GetInstance();
}
public List<ComputerViewModel> GetFullList()
{
return source.Computers.Select(x => x.GetViewModel).ToList();
return _source.Computers
.Select(x => x.GetViewModel)
.ToList();
}
public List<ComputerViewModel> GetFiltredList(ComputerSearchModel model)
public List<ComputerViewModel> GetFilteredList(ComputerSearchModel model)
{
if (string.IsNullOrEmpty(model.ComputerName))
{
return new();
}
return source.Computers
return _source.Computers
.Where(x => x.ComputerName.Contains(model.ComputerName))
.Select(x => x.GetViewModel)
.ToList();
}
public ComputerViewModel? GetElement(ComputerSearchModel model)
{
if (!string.IsNullOrEmpty(model.ComputerName) && !model.Id.HasValue)
if (string.IsNullOrEmpty(model.ComputerName) && !model.Id.HasValue)
{
return null;
}
return source.Computers
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ComputerName) &&
x.ComputerName == model.ComputerName) || (model.Id.HasValue &&
x.Id == model.Id))?.GetViewModel;
return _source.Computers
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ComputerName) &&
x.ComputerName == model.ComputerName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ComputerViewModel? Insert(ComputerBindingModel model)
{
model.Id = source.Computers.Count > 0 ? source.Components.Max(x => x.Id) + 1 : 1;
model.Id = _source.Computers.Count > 0 ? _source.Computers.Max(x => x.Id) + 1 : 1;
var newComputer = Computer.Create(model);
if (newComputer == null)
{
return null;
}
source.Computers.Add(newComputer);
source.SaveComputers();
_source.Computers.Add(newComputer);
_source.SaveComputers();
return newComputer.GetViewModel;
}
public ComputerViewModel? Update(ComputerBindingModel model)
{
var computer = source.Computers.FirstOrDefault(x => x.Id == model.Id);
var computer = _source.Computers.FirstOrDefault(x => x.Id == model.Id);
if (computer == null)
{
return null;
}
computer.Update(model);
source.SaveComputers();
_source.SaveComputers();
return computer.GetViewModel;
}
public ComputerViewModel? Delete(ComputerBindingModel model)
{
var element = source.Computers.FirstOrDefault(x => x.Id == model.Id);
var element = _source.Computers.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
source.Computers.Remove(element);
source.SaveComputers();
_source.Computers.Remove(element);
_source.SaveComputers();
return element.GetViewModel;
}
return null;

View File

@ -13,22 +13,28 @@ namespace ComputersShopFileImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataFileSingleton source;
private readonly DataFileSingleton _source;
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
_source = DataFileSingleton.GetInstance();
}
public List<OrderViewModel> GetFullList()
{
return source.Orders.Select(x => GetViewModel(x)).ToList();
return _source.Orders
.Select(x => GetViewModel(x))
.ToList();
}
public List<OrderViewModel> GetFiltredList(OrderSearchModel model)
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
return source.Orders.Where(x => x.Id == model.Id).Select(x => GetViewModel(x)).ToList();
return _source.Orders
.Where(x => x.Id.Equals(model.Id))
.Select(x => GetViewModel(x))
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
@ -36,47 +42,55 @@ namespace ComputersShopFileImplement.Implements
{
return null;
}
return GetViewModel(source.Orders.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id));
}
public OrderViewModel? Update(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
source.SaveOrders();
return GetViewModel(order);
return GetViewModel(_source.Orders
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id)));
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = source.Orders.Count > 0 ? source.Orders.Max(x => x.Id) + 1 : 1;
model.Id = _source.Orders.Count > 0 ? _source.Orders.Max(x => x.Id) + 1 : 1;
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
source.Orders.Add(newOrder);
source.SaveOrders();
_source.Orders.Add(newOrder);
_source.SaveOrders();
return GetViewModel(newOrder);
}
public OrderViewModel? Delete(OrderBindingModel model)
public OrderViewModel? Update(OrderBindingModel model)
{
var order = source.Orders.FirstOrDefault(x => x.Id == model.Id);
var order = _source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
source.Orders.Remove(order);
source.SaveOrders();
order.Update(model);
_source.SaveOrders();
return GetViewModel(order);
}
public OrderViewModel? Delete(OrderBindingModel model)
{
var element = _source.Orders.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
_source.Orders.Remove(element);
_source.SaveOrders();
return GetViewModel(element);
}
return null;
}
private OrderViewModel GetViewModel(Order order)
{
var viewModel = order.GetViewModel;
var computer = source.Computers.FirstOrDefault(x => x.Id == order.ComputerId);
viewModel.ComputerName = computer?.ComputerName;
var plane = _source.Computers.FirstOrDefault(x => x.Id == order.ComputerId);
if (plane != null)
{
viewModel.ComputerName = plane.ComputerName;
}
return viewModel;
}
}

View File

@ -0,0 +1,137 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using ComputersShopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputersShopFileImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataFileSingleton _source;
public ShopStorage()
{
_source = DataFileSingleton.GetInstance();
}
public List<ShopViewModel> GetFullList()
{
return _source.Shops
.Select(x => x.GetViewModel)
.ToList();
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
return _source.Shops
.Where(x => x.ShopName.Contains(model.ShopName))
.Select(x => x.GetViewModel)
.ToList();
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
return _source.Shops
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ShopName) &&
x.ShopName == model.ShopName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = _source.Shops.Count > 0 ? _source.Shops.Max(x => x.Id) + 1 : 1;
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
_source.SaveShops();
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
var shop = _source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
shop.Update(model);
_source.SaveShops();
return shop.GetViewModel;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
var element = _source.Shops.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
_source.Shops.Remove(element);
_source.SaveShops();
return element.GetViewModel;
}
return null;
}
public bool SellComputers(IComputerModel model, int count)
{
var computer = _source.Computers.FirstOrDefault(x => x.Id == model.Id);
if (computer == null || !CheckCount(model, count))
{
return false;
}
foreach (var shop in _source.Shops)
{
var computers = shop.ShopComputers;
foreach (var elem in computers.Where(x => x.Value.Item1.Id == computer.Id))
{
var selling = Math.Min(elem.Value.Item2, count);
computers[elem.Value.Item1.Id] = (elem.Value.Item1, elem.Value.Item2 - selling);
count -= selling;
if (count <= 0)
{
break;
}
}
shop.Update(new ShopBindingModel
{
Id = model.Id,
ShopName = shop.ShopName,
Address = shop.Address,
DateOpening = shop.DateOpening,
ShopComputers = computers,
MaxComputers = shop.MaxComputers
});
}
_source.SaveShops();
return true;
}
public bool CheckCount(IComputerModel model, int count)
{
int store = _source.Shops
.Select(x => x.ShopComputers
.Select(y => (y.Value.Item1.Id == model.Id ? y.Value.Item2 : 0))
.Sum()).Sum();
return store >= count;
}
}
}

View File

@ -16,12 +16,13 @@ namespace ComputersShopFileImplement.Models
public int Id { get; private set; }
public string ComponentName { get; private set; } = string.Empty;
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel model)
public static Component? Create(ComponentBindingModel? model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
@ -35,6 +36,7 @@ namespace ComputersShopFileImplement.Models
{
return null;
}
return new Component()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
@ -42,12 +44,13 @@ namespace ComputersShopFileImplement.Models
Cost = Convert.ToDouble(element.Element("Cost")!.Value)
};
}
public void Update(ComponentBindingModel model)
public void Update(ComponentBindingModel? model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
@ -58,8 +61,8 @@ namespace ComputersShopFileImplement.Models
Cost = Cost
};
public XElement GetXElement => new("Component",
new XAttribute("Id", Id),
new XElement("ComponentName", ComponentName),
new XElement("Cost", Cost.ToString()));
new XAttribute("Id", Id),
new XElement("ComponentName", ComponentName),
new XElement("Cost", Cost.ToString()));
}
}

View File

@ -7,6 +7,7 @@ using ComputersShopContracts.BindingModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System.Xml.Linq;
using System.Numerics;
namespace ComputersShopFileImplement.Models
{
@ -24,19 +25,18 @@ namespace ComputersShopFileImplement.Models
if (_computerComponents == null)
{
var source = DataFileSingleton.GetInstance();
_computerComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!,
y.Value));
_computerComponents = Components.ToDictionary(x => x.Key, y => ((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!, y.Value));
}
return _computerComponents;
}
}
public static Computer? Create(ComputerBindingModel model)
public static Computer? Create(ComputerBindingModel? model)
{
if (model == null)
{
return null;
}
return new Computer()
{
Id = model.Id,
@ -51,24 +51,23 @@ namespace ComputersShopFileImplement.Models
{
return null;
}
return new Computer()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ComputerName = element.Element("ComputerName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components =
element.Element("ComputerComponents")!.Elements("ComputerComponent")
.ToDictionary(x =>
Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
Components = element.Element("ComputerComponents")!.Elements("ComputerComponent")
.ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ComputerBindingModel model)
public void Update(ComputerBindingModel? model)
{
if (model == null)
{
return;
}
ComputerName = model.ComputerName;
Price = model.Price;
Components = model.ComputerComponents.ToDictionary(x => x.Key, x => x.Value.Item2);
@ -86,8 +85,10 @@ namespace ComputersShopFileImplement.Models
new XElement("ComputerName", ComputerName),
new XElement("Price", Price.ToString()),
new XElement("ComputerComponents", Components.Select(x =>
new XElement("ComputerComponent", new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
new XElement("ComputerComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value)))
.ToArray()));
}
}

View File

@ -0,0 +1,102 @@
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ComputersShopFileImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public Dictionary<int, int> Computers { get; private set; } = new();
private Dictionary<int, (IComputerModel, int)>? _shopComputers = null;
public Dictionary<int, (IComputerModel, int)> ShopComputers
{
get
{
if (_shopComputers == null)
{
var source = DataFileSingleton.GetInstance();
_shopComputers = Computers.ToDictionary(x => x.Key, y => ((source.Computers.FirstOrDefault(z => z.Id == y.Key) as IComputerModel)!, y.Value));
}
return _shopComputers;
}
}
public int MaxComputers { get; private set; }
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
DateOpening = Convert.ToDateTime(element.Element("DateOpening")!.Value),
Computers = element.Element("ShopComputers")!.Elements("ShopComputers")!
.ToDictionary(x => Convert.ToInt32(x.Element("Key")?.Value), x => Convert.ToInt32(x.Element("Value")?.Value)),
MaxComputers = Convert.ToInt32(element.Element("MaxComputers")!.Value)
};
}
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
Computers = model.ShopComputers.ToDictionary(x => x.Key, x => x.Value.Item2),
MaxComputers = model.MaxComputers
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
Computers = model.ShopComputers.ToDictionary(x => x.Key, x => x.Value.Item2);
MaxComputers = model.MaxComputers;
_shopComputers = null;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
ShopComputers = ShopComputers,
MaxComputers = MaxComputers
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpening", DateOpening.ToString()),
new XElement("ShopComputers", Computers.Select(x =>
new XElement("ShopComputers",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()),
new XElement("MaxComputers", MaxComputers.ToString()));
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using ComputersShopListImplement.Models;
@ -13,11 +14,13 @@ namespace AbstractShopListImplement
public List<Component> Components { get; set; }
public List<Order> Orders { get; set; }
public List<Computer> Computers { get; set; }
public List<Shop> Shops { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Computers = new List<Computer>();
Shops = new List<Shop>();
}
public static DataListSingleton GetInstance()
{

View File

@ -28,7 +28,7 @@ namespace ComputersShopListImplement.Implements
}
return result;
}
public List<ComponentViewModel> GetFiltredList(ComponentSearchModel model)
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel model)
{
var result = new List<ComponentViewModel>();
if (string.IsNullOrEmpty(model.ComponentName))

View File

@ -28,7 +28,7 @@ namespace ComputersShopListImplement.Implements
}
return result;
}
public List<ComputerViewModel> GetFiltredList(ComputerSearchModel model)
public List<ComputerViewModel> GetFilteredList(ComputerSearchModel model)
{
var result = new List<ComputerViewModel>();
if (string.IsNullOrEmpty(model.ComputerName))

View File

@ -24,22 +24,23 @@ namespace ComputersShopListImplement.Implements
var result = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
result.Add(AddComputerName(order.GetViewModel));
result.Add(order.GetViewModel);
}
return result;
}
public List<OrderViewModel> GetFiltredList(OrderSearchModel model)
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var result = new List<OrderViewModel>();
if (model == null || !model.Id.HasValue)
if (!model.Id.HasValue)
{
return result;
}
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
result.Add(AddComputerName(order.GetViewModel));
result.Add(order.GetViewModel);
}
}
return result;
@ -50,11 +51,12 @@ namespace ComputersShopListImplement.Implements
{
return null;
}
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
{
return AddComputerName(order.GetViewModel);
return order.GetViewModel;
}
}
return null;
@ -69,13 +71,15 @@ namespace ComputersShopListImplement.Implements
model.Id = order.Id + 1;
}
}
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
_source.Orders.Add(newOrder);
return AddComputerName(newOrder.GetViewModel);
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
@ -84,7 +88,7 @@ namespace ComputersShopListImplement.Implements
if (order.Id == model.Id)
{
order.Update(model);
return AddComputerName(order.GetViewModel);
return order.GetViewModel;
}
}
return null;
@ -97,20 +101,11 @@ namespace ComputersShopListImplement.Implements
{
var element = _source.Orders[i];
_source.Orders.RemoveAt(i);
return AddComputerName(element.GetViewModel);
return element.GetViewModel;
}
}
return null;
}
private OrderViewModel AddComputerName(OrderViewModel model)
{
var selectedComputer = _source.Computers.Find(computer => computer.Id == model.ComputerId);
if (selectedComputer != null)
{
model.ComputerName = selectedComputer.ComputerName;
}
return model;
}
}
}

View File

@ -0,0 +1,120 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AbstractShopListImplement;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.StoragesContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
using ComputersShopListImplement.Models;
namespace ComputersShopListImplement.Implements
{
public class ShopStorage : IShopStorage
{
private readonly DataListSingleton _source;
public ShopStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ShopViewModel> GetFullList()
{
var result = new List<ShopViewModel>();
foreach (var shop in _source.Shops)
{
result.Add(shop.GetViewModel);
}
return result;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
var result = new List<ShopViewModel>();
if (string.IsNullOrEmpty(model.ShopName))
{
return result;
}
foreach (var shop in _source.Shops)
{
if (shop.ShopName.Contains(model.ShopName))
{
result.Add(shop.GetViewModel);
}
}
return result;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
foreach (var shop in _source.Shops)
{
if ((!string.IsNullOrEmpty(model.ShopName) && shop.ShopName == model.ShopName) || (model.Id.HasValue && shop.Id == model.Id))
{
return shop.GetViewModel;
}
}
return null;
}
public ShopViewModel? Insert(ShopBindingModel model)
{
model.Id = 1;
foreach (var shop in _source.Shops)
{
if (model.Id <= shop.Id)
{
model.Id = shop.Id + 1;
}
}
var newShop = Shop.Create(model);
if (newShop == null)
{
return null;
}
_source.Shops.Add(newShop);
return newShop.GetViewModel;
}
public ShopViewModel? Update(ShopBindingModel model)
{
foreach (var shop in _source.Shops)
{
if (shop.Id == model.Id)
{
shop.Update(model);
return shop.GetViewModel;
}
}
return null;
}
public ShopViewModel? Delete(ShopBindingModel model)
{
for (int i = 0; i < _source.Shops.Count; ++i)
{
if (_source.Shops[i].Id == model.Id)
{
var element = _source.Shops[i];
_source.Shops.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public bool SellComputers(IComputerModel model, int count)
{
throw new NotImplementedException();
}
public bool CheckCount(IComputerModel model, int count)
{
throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
namespace ComputersShopListImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
public string ShopName { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public DateTime DateOpening { get; private set; }
public Dictionary<int, (IComputerModel, int)> ShopComputers
{
get;
private set;
} = new Dictionary<int, (IComputerModel, int)>();
public int MaxComputers { get; private set; }
public static Shop? Create(ShopBindingModel? model)
{
if (model == null)
{
return null;
}
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
DateOpening = model.DateOpening,
ShopComputers = model.ShopComputers,
MaxComputers = model.MaxComputers
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
DateOpening = model.DateOpening;
ShopComputers = model.ShopComputers;
MaxComputers = model.MaxComputers;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
DateOpening = DateOpening,
ShopComputers = ShopComputers,
MaxComputers = MaxComputers
};
}
}

View File

@ -8,7 +8,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using Microsoft.Extensions.Logging;

View File

@ -8,7 +8,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;

View File

@ -8,7 +8,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;

View File

@ -7,7 +7,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels.Models;

View File

@ -9,7 +9,7 @@ using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
namespace ComputersShopView
{

View File

@ -8,7 +8,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using Microsoft.Extensions.Logging;

View File

@ -32,6 +32,9 @@
this.справочникиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.компонентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.изделияToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.магазиныToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.поставкиToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.продажаИзделийToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.buttonCreateOrder = new System.Windows.Forms.Button();
this.buttonTakeOrderInWork = new System.Windows.Forms.Button();
@ -57,7 +60,10 @@
//
this.справочникиToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.компонентыToolStripMenuItem,
this.изделияToolStripMenuItem});
this.изделияToolStripMenuItem,
this.магазиныToolStripMenuItem,
this.поставкиToolStripMenuItem,
this.продажаИзделийToolStripMenuItem});
this.справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
this.справочникиToolStripMenuItem.Size = new System.Drawing.Size(117, 24);
this.справочникиToolStripMenuItem.Text = "Справочники";
@ -65,17 +71,38 @@
// компонентыToolStripMenuItem
//
this.компонентыToolStripMenuItem.Name = омпонентыToolStripMenuItem";
this.компонентыToolStripMenuItem.Size = new System.Drawing.Size(182, 26);
this.компонентыToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.компонентыToolStripMenuItem.Text = "Компоненты";
this.компонентыToolStripMenuItem.Click += new System.EventHandler(this.КомпонентыToolStripMenuItem_Click);
//
// изделияToolStripMenuItem
//
this.изделияToolStripMenuItem.Name = "изделияToolStripMenuItem";
this.изделияToolStripMenuItem.Size = new System.Drawing.Size(182, 26);
this.изделияToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.изделияToolStripMenuItem.Text = "Изделия";
this.изделияToolStripMenuItem.Click += new System.EventHandler(this.ИзделияToolStripMenuItem_Click);
//
// магазиныToolStripMenuItem
//
this.магазиныToolStripMenuItem.Name = агазиныToolStripMenuItem";
this.магазиныToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.магазиныToolStripMenuItem.Text = "Магазины";
this.магазиныToolStripMenuItem.Click += new System.EventHandler(this.МагазиныToolStripMenuItem_Click);
//
// поставкиToolStripMenuItem
//
this.поставкиToolStripMenuItem.Name = "поставкиToolStripMenuItem";
this.поставкиToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.поставкиToolStripMenuItem.Text = "Поставки";
this.поставкиToolStripMenuItem.Click += new System.EventHandler(this.ПоставкиToolStripMenuItem_Click);
//
// продажаИзделийToolStripMenuItem
//
this.продажаИзделийToolStripMenuItem.Name = "продажаИзделийToolStripMenuItem";
this.продажаИзделийToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.продажаИзделийToolStripMenuItem.Text = "Продажа изделий";
this.продажаИзделийToolStripMenuItem.Click += new System.EventHandler(this.ПродажаизделийToolStripMenuItem_Click);
//
// dataGridView
//
this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
@ -175,5 +202,8 @@
private Button buttonRef;
private ToolStripMenuItem компонентыToolStripMenuItem;
private ToolStripMenuItem изделияToolStripMenuItem;
private ToolStripMenuItem магазиныToolStripMenuItem;
private ToolStripMenuItem поставкиToolStripMenuItem;
private ToolStripMenuItem продажаИзделийToolStripMenuItem;
}
}

View File

@ -9,7 +9,7 @@ using System.Threading.Tasks;
using System.Windows.Forms;
using ComputersShopBusinessLogic.BusinessLogics;
using ComputersShopContracts.BindingModels;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace ComputersShopView
@ -64,6 +64,31 @@ namespace ComputersShopView
form.ShowDialog();
}
}
private void МагазиныToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void ПоставкиToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSupply));
if (service is FormSupply form)
{
form.ShowDialog();
}
}
private void ПродажаизделийToolStripMenuItem_Click(object sender, EventArgs
e)
{
var services = Program.ServiceProvider?.GetService(typeof(FormSell));
if (services is FormSell form)
{
form.ShowDialog();
}
}
private void ButtonCreateOrder_Click(object sender, EventArgs e)
{
var service =

View File

@ -0,0 +1,120 @@
namespace ComputersShopView
{
partial class FormSell
{
/// <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()
{
this.labelComputer = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.comboBoxComputer = new System.Windows.Forms.ComboBox();
this.textBoxCount = new System.Windows.Forms.TextBox();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// labelComputer
//
this.labelComputer.AutoSize = true;
this.labelComputer.Location = new System.Drawing.Point(12, 50);
this.labelComputer.Name = "labelComputer";
this.labelComputer.Size = new System.Drawing.Size(71, 20);
this.labelComputer.TabIndex = 0;
this.labelComputer.Text = "Изделие:";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(12, 106);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(93, 20);
this.labelCount.TabIndex = 1;
this.labelCount.Text = "Количество:";
//
// comboBoxComputer
//
this.comboBoxComputer.FormattingEnabled = true;
this.comboBoxComputer.Location = new System.Drawing.Point(137, 42);
this.comboBoxComputer.Name = "comboBoxComputer";
this.comboBoxComputer.Size = new System.Drawing.Size(267, 28);
this.comboBoxComputer.TabIndex = 2;
//
// textBoxCount
//
this.textBoxCount.Location = new System.Drawing.Point(137, 99);
this.textBoxCount.Name = "textBoxCount";
this.textBoxCount.Size = new System.Drawing.Size(267, 27);
this.textBoxCount.TabIndex = 3;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(244, 154);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 4;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(368, 154);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 5;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// FormSell
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(474, 199);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.textBoxCount);
this.Controls.Add(this.comboBoxComputer);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelComputer);
this.Name = "FormSell";
this.Text = "Продажа";
this.Load += new System.EventHandler(this.FormSell_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelComputer;
private Label labelCount;
private ComboBox comboBoxComputer;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,107 @@
using ComputersShopContracts.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;
namespace ComputersShopView
{
public partial class FormSell : Form
{
private readonly ILogger _logger;
/// <summary>
/// Бизнес-логика для изделий
/// </summary>
private readonly IComputerLogic _logicC;
/// <summary>
/// Бизнес-логика для магазинов
/// </summary>
private readonly IShopLogic _logicS;
public FormSell(ILogger<FormSell> logger, IComputerLogic planeLogic, IShopLogic shopLogic)
{
InitializeComponent();
_logger = logger;
_logicC = planeLogic;
_logicS = shopLogic;
}
private void FormSell_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка изделий для продажи");
try
{
var list = _logicC.ReadList(null);
if (list != null)
{
comboBoxComputer.DisplayMember = "ComputerName";
comboBoxComputer.ValueMember = "Id";
comboBoxComputer.DataSource = list;
comboBoxComputer.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Кнопка "Сохранить"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxComputer.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Продажа изделий");
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicS.SellComputers(
_logicC.ReadElement(new() { Id = Convert.ToInt32(comboBoxComputer.SelectedValue) }),
Convert.ToInt32(textBoxCount.Text)
);
if (!operationResult)
{
throw new Exception("Ошибка при продаже изделий. Дополнительная информация в логах.");
}
MessageBox.Show("Продажа прошла успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка продажи изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Кнопка "Отмена"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,211 @@
namespace ComputersShopView
{
partial class FormShop
{
/// <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()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.dateTimePicker = new System.Windows.Forms.DateTimePicker();
this.textBoxAddress = new System.Windows.Forms.TextBox();
this.textBoxName = new System.Windows.Forms.TextBox();
this.dataGridViewShop = new System.Windows.Forms.DataGridView();
this.id = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ComputerName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Count = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.labelMaxComputers = new System.Windows.Forms.Label();
this.textBoxMaxComputers = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewShop)).BeginInit();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 22);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 20);
this.label1.TabIndex = 0;
this.label1.Text = "Название:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 61);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(54, 20);
this.label2.TabIndex = 1;
this.label2.Text = "Адрес:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 102);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(44, 20);
this.label3.TabIndex = 2;
this.label3.Text = "Дата:";
//
// dateTimePicker
//
this.dateTimePicker.Location = new System.Drawing.Point(121, 97);
this.dateTimePicker.Name = "dateTimePicker";
this.dateTimePicker.Size = new System.Drawing.Size(386, 27);
this.dateTimePicker.TabIndex = 3;
//
// textBoxAddress
//
this.textBoxAddress.Location = new System.Drawing.Point(121, 61);
this.textBoxAddress.Name = "textBoxAddress";
this.textBoxAddress.Size = new System.Drawing.Size(386, 27);
this.textBoxAddress.TabIndex = 4;
this.textBoxAddress.TextChanged += new System.EventHandler(this.FormShop_Load);
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(121, 22);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(386, 27);
this.textBoxName.TabIndex = 5;
//
// dataGridViewShop
//
this.dataGridViewShop.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridViewShop.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.id,
this.ComputerName,
this.Count});
this.dataGridViewShop.Location = new System.Drawing.Point(23, 197);
this.dataGridViewShop.Name = "dataGridViewShop";
this.dataGridViewShop.RowHeadersWidth = 51;
this.dataGridViewShop.RowTemplate.Height = 29;
this.dataGridViewShop.Size = new System.Drawing.Size(507, 173);
this.dataGridViewShop.TabIndex = 6;
//
// id
//
this.id.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.id.HeaderText = "Id";
this.id.MinimumWidth = 6;
this.id.Name = "id";
this.id.Visible = false;
//
// ComputerName
//
this.ComputerName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.ComputerName.HeaderText = "Название";
this.ComputerName.MinimumWidth = 6;
this.ComputerName.Name = "ComputerName";
//
// Count
//
this.Count.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.Count.HeaderText = "Количество";
this.Count.MinimumWidth = 6;
this.Count.Name = "Count";
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(319, 376);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 7;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(436, 376);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 8;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// labelMaxComputers
//
this.labelMaxComputers.AutoSize = true;
this.labelMaxComputers.Location = new System.Drawing.Point(12, 150);
this.labelMaxComputers.Name = "labelMaxComputers";
this.labelMaxComputers.Size = new System.Drawing.Size(103, 20);
this.labelMaxComputers.TabIndex = 9;
this.labelMaxComputers.Text = "Вместимость:";
//
// textBoxMaxComputers
//
this.textBoxMaxComputers.Location = new System.Drawing.Point(121, 147);
this.textBoxMaxComputers.Name = "textBoxMaxComputers";
this.textBoxMaxComputers.Size = new System.Drawing.Size(386, 27);
this.textBoxMaxComputers.TabIndex = 10;
//
// FormShop
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(546, 417);
this.Controls.Add(this.textBoxMaxComputers);
this.Controls.Add(this.labelMaxComputers);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.dataGridViewShop);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.textBoxAddress);
this.Controls.Add(this.dateTimePicker);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "FormShop";
this.Text = "Магазин";
this.Load += new System.EventHandler(this.FormShop_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridViewShop)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private Label label3;
private DateTimePicker dateTimePicker;
private TextBox textBoxAddress;
private TextBox textBoxName;
private DataGridView dataGridViewShop;
private Button buttonSave;
private Button buttonCancel;
private DataGridViewTextBoxColumn id;
private DataGridViewTextBoxColumn ComputerName;
private DataGridViewTextBoxColumn Count;
private Label labelMaxComputers;
private TextBox textBoxMaxComputers;
}
}

View File

@ -0,0 +1,131 @@
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 ComputersShopContracts.BindingModels;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace ComputersShopView
{
public partial class FormShop : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
private Dictionary<int, (IComputerModel, int)> _shopComputers;
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_shopComputers = new Dictionary<int, (IComputerModel, int)>();
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка магазина");
try
{
var view = _logic.ReadElement(new ShopSearchModel { Id = _id.Value });
if (view != null)
{
textBoxName.Text = view.ShopName;
textBoxAddress.Text = view.Address;
dateTimePicker.Text = view.DateOpening.ToString();
textBoxMaxComputers.Text = view.MaxComputers.ToString();
_shopComputers = view.ShopComputers ?? new Dictionary<int, (IComputerModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка изделий магазина");
try
{
if (_shopComputers != null)
{
dataGridViewShop.Rows.Clear();
foreach (var elem in _shopComputers)
{
dataGridViewShop.Rows.Add(new object[]
{
elem.Key,
elem.Value.Item1.ComputerName,
elem.Value.Item2
});
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделий магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxAddress.Text))
{
MessageBox.Show("Заполните адрес", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение магазина");
try
{
var model = new ShopBindingModel
{
Id = _id ?? 0,
ShopName = textBoxName.Text,
Address = textBoxAddress.Text,
DateOpening = dateTimePicker.Value.Date,
ShopComputers = _shopComputers,
MaxComputers = Convert.ToInt32(textBoxMaxComputers.Text)
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка сохранения магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -0,0 +1,69 @@
<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>
<metadata name="id.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ComputerName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="Count.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,115 @@
namespace ComputersShopView
{
partial class FormShops
{
/// <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()
{
this.dataGridViewShops = new System.Windows.Forms.DataGridView();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonUpdate = new System.Windows.Forms.Button();
this.buttonDelete = new System.Windows.Forms.Button();
this.buttonRefresh = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewShops)).BeginInit();
this.SuspendLayout();
//
// dataGridViewShops
//
this.dataGridViewShops.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridViewShops.Location = new System.Drawing.Point(3, 1);
this.dataGridViewShops.Name = "dataGridViewShops";
this.dataGridViewShops.RowHeadersWidth = 51;
this.dataGridViewShops.RowTemplate.Height = 29;
this.dataGridViewShops.Size = new System.Drawing.Size(572, 453);
this.dataGridViewShops.TabIndex = 0;
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(605, 41);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(94, 29);
this.buttonAdd.TabIndex = 1;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.ButtonAdd_Click);
//
// buttonUpdate
//
this.buttonUpdate.Location = new System.Drawing.Point(605, 96);
this.buttonUpdate.Name = "buttonUpdate";
this.buttonUpdate.Size = new System.Drawing.Size(94, 29);
this.buttonUpdate.TabIndex = 2;
this.buttonUpdate.Text = "Изменить";
this.buttonUpdate.UseVisualStyleBackColor = true;
this.buttonUpdate.Click += new System.EventHandler(this.ButtonUpdate_Click);
//
// buttonDelete
//
this.buttonDelete.Location = new System.Drawing.Point(605, 145);
this.buttonDelete.Name = "buttonDelete";
this.buttonDelete.Size = new System.Drawing.Size(94, 29);
this.buttonDelete.TabIndex = 3;
this.buttonDelete.Text = "Удалить";
this.buttonDelete.UseVisualStyleBackColor = true;
this.buttonDelete.Click += new System.EventHandler(this.ButtonDelete_Click);
//
// buttonRefresh
//
this.buttonRefresh.Location = new System.Drawing.Point(605, 197);
this.buttonRefresh.Name = "buttonRefresh";
this.buttonRefresh.Size = new System.Drawing.Size(94, 29);
this.buttonRefresh.TabIndex = 4;
this.buttonRefresh.Text = "Обновить";
this.buttonRefresh.UseVisualStyleBackColor = true;
this.buttonRefresh.Click += new System.EventHandler(this.ButtonRefresh_Click);
//
// FormShops
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(733, 450);
this.Controls.Add(this.buttonRefresh);
this.Controls.Add(this.buttonDelete);
this.Controls.Add(this.buttonUpdate);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.dataGridViewShops);
this.Name = "FormShops";
this.Text = "Магазины";
this.Load += new System.EventHandler(this.FormShops_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridViewShops)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridViewShops;
private Button buttonAdd;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonRefresh;
}
}

View File

@ -0,0 +1,110 @@
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 ComputersShopContracts.BindingModels;
using ComputersShopContracts.BusinessLogicsContracts;
using Microsoft.Extensions.Logging;
namespace ComputersShopView
{
public partial class FormShops : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public FormShops(ILogger<FormShops> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridViewShops.DataSource = list;
dataGridViewShops.Columns["Id"].Visible = false;
dataGridViewShops.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridViewShops.Columns["ShopComputers"].Visible = false;
}
_logger.LogInformation("Загрузка магазинов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormShops_Load(object sender, EventArgs e)
{
LoadData();
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ButtonUpdate_Click(object sender, EventArgs e)
{
if (dataGridViewShops.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
form.Id = Convert.ToInt32(dataGridViewShops.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void ButtonRefresh_Click(object sender, EventArgs e)
{
LoadData();
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (dataGridViewShops.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridViewShops.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление магазина");
try
{
if (!_logic.Delete(new ShopBindingModel { Id = id }))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
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,150 @@
namespace ComputersShopView
{
partial class FormSupply
{
/// <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()
{
this.labelShop = new System.Windows.Forms.Label();
this.labelComputer = new System.Windows.Forms.Label();
this.labelCount = new System.Windows.Forms.Label();
this.comboBoxComputer = new System.Windows.Forms.ComboBox();
this.comboBoxShop = new System.Windows.Forms.ComboBox();
this.buttonSave = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.numericUpDownCount = new System.Windows.Forms.NumericUpDown();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).BeginInit();
this.SuspendLayout();
//
// labelShop
//
this.labelShop.AutoSize = true;
this.labelShop.Location = new System.Drawing.Point(28, 46);
this.labelShop.Name = "labelShop";
this.labelShop.Size = new System.Drawing.Size(72, 20);
this.labelShop.TabIndex = 0;
this.labelShop.Text = "Магазин:";
//
// labelComputer
//
this.labelComputer.AutoSize = true;
this.labelComputer.Location = new System.Drawing.Point(28, 96);
this.labelComputer.Name = "labelComputer";
this.labelComputer.Size = new System.Drawing.Size(93, 20);
this.labelComputer.TabIndex = 1;
this.labelComputer.Text = "Компьютер:";
//
// labelCount
//
this.labelCount.AutoSize = true;
this.labelCount.Location = new System.Drawing.Point(28, 146);
this.labelCount.Name = "labelCount";
this.labelCount.Size = new System.Drawing.Size(93, 20);
this.labelCount.TabIndex = 2;
this.labelCount.Text = "Количество:";
//
// comboBoxComputer
//
this.comboBoxComputer.FormattingEnabled = true;
this.comboBoxComputer.Location = new System.Drawing.Point(142, 88);
this.comboBoxComputer.Name = "comboBoxComputer";
this.comboBoxComputer.Size = new System.Drawing.Size(349, 28);
this.comboBoxComputer.TabIndex = 4;
//
// comboBoxShop
//
this.comboBoxShop.FormattingEnabled = true;
this.comboBoxShop.Location = new System.Drawing.Point(142, 38);
this.comboBoxShop.Name = "comboBoxShop";
this.comboBoxShop.Size = new System.Drawing.Size(349, 28);
this.comboBoxShop.TabIndex = 5;
//
// buttonSave
//
this.buttonSave.Location = new System.Drawing.Point(328, 186);
this.buttonSave.Name = "buttonSave";
this.buttonSave.Size = new System.Drawing.Size(94, 29);
this.buttonSave.TabIndex = 6;
this.buttonSave.Text = "Сохранить";
this.buttonSave.UseVisualStyleBackColor = true;
this.buttonSave.Click += new System.EventHandler(this.ButtonSave_Click);
//
// buttonCancel
//
this.buttonCancel.Location = new System.Drawing.Point(446, 186);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.Size = new System.Drawing.Size(94, 29);
this.buttonCancel.TabIndex = 7;
this.buttonCancel.Text = "Отмена";
this.buttonCancel.UseVisualStyleBackColor = true;
this.buttonCancel.Click += new System.EventHandler(this.ButtonCancel_Click);
//
// numericUpDownCount
//
this.numericUpDownCount.Location = new System.Drawing.Point(142, 139);
this.numericUpDownCount.Maximum = new decimal(new int[] {
1000,
0,
0,
0});
this.numericUpDownCount.Name = "numericUpDownCount";
this.numericUpDownCount.Size = new System.Drawing.Size(348, 27);
this.numericUpDownCount.TabIndex = 8;
//
// FormSupply
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(552, 227);
this.Controls.Add(this.numericUpDownCount);
this.Controls.Add(this.buttonCancel);
this.Controls.Add(this.buttonSave);
this.Controls.Add(this.comboBoxShop);
this.Controls.Add(this.comboBoxComputer);
this.Controls.Add(this.labelCount);
this.Controls.Add(this.labelComputer);
this.Controls.Add(this.labelShop);
this.Name = "FormSupply";
this.Text = "Поставки";
this.Load += new System.EventHandler(this.FormSupply_Load);
((System.ComponentModel.ISupportInitialize)(this.numericUpDownCount)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label labelShop;
private Label labelComputer;
private Label labelCount;
private ComboBox comboBoxComputer;
private ComboBox comboBoxShop;
private Button buttonSave;
private Button buttonCancel;
private NumericUpDown numericUpDownCount;
}
}

View File

@ -0,0 +1,125 @@
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 ComputersShopBusinessLogic.BusinessLogics;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.SearchModels;
using ComputersShopContracts.ViewModels;
using ComputersShopDataModels;
using ComputersShopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace ComputersShopView
{
public partial class FormSupply : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logicS;
private readonly IComputerLogic _logicC;
public FormSupply(ILogger<FormSupply> logger, IShopLogic logicS, IComputerLogic logicC)
{
InitializeComponent();
_logger = logger;
_logicS = logicS;
_logicC = logicC;
}
private void FormSupply_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка магазинов");
try
{
var listShops = _logicS.ReadList(null);
if (listShops != null)
{
comboBoxShop.DisplayMember = "ShopName";
comboBoxShop.ValueMember = "Id";
comboBoxShop.DataSource = listShops;
comboBoxShop.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка магазинов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
_logger.LogInformation("Загрузка изделий");
try
{
var listComputers = _logicC.ReadList(null);
if (listComputers != null)
{
comboBoxComputer.DisplayMember = "ComputerName";
comboBoxComputer.ValueMember = "Id";
comboBoxComputer.DataSource = listComputers;
comboBoxComputer.SelectedItem = null;
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки списка изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (comboBoxShop.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxComputer.SelectedValue == null)
{
MessageBox.Show("Выберите изделие", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Добавление изделия в магазин");
try
{
var computer = _logicC.ReadElement(new()
{
Id = (int)comboBoxComputer.SelectedValue
});
if (computer == null)
{
throw new Exception("Не найдено изделие. Дополнительная информация в логах.");
}
var resultOperation = _logicS.AddComputerInShop(
new ShopSearchModel
{
Id = (int)comboBoxShop.SelectedValue
},
computer,
(int)numericUpDownCount.Value
);
if (!resultOperation)
{
throw new Exception("Ошибка при добавлении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка добавления поступления");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,7 +1,8 @@
using ComputersShopBusinessLogic.BusinessLogics;
using ComputersShopContracts.BuisnessLogicsContracts;
using ComputersShopBusinessLogic.BusinessLogics;
using ComputersShopContracts.BusinessLogicsContracts;
using ComputersShopContracts.StoragesContracts;
using ComputersShopFileImplement.Implements;
using ComputersShopView;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
@ -11,8 +12,12 @@ namespace ComputersShopView
{
internal static class Program
{
/// <summary>
/// IoC-êîíòåéíåð
/// </summary>
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
@ -22,11 +27,18 @@ namespace ComputersShopView
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
/// <summary>
/// Íàñòðîéêà IoC-êîíòåéíåðà è ëîããåðà
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddLogging(option =>
@ -34,13 +46,16 @@ namespace ComputersShopView
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IComputerStorage, ComputerStorage>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IComputerLogic, ComputerLogic>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
@ -49,6 +64,10 @@ namespace ComputersShopView
services.AddTransient<FormComputer>();
services.AddTransient<FormComputerComponent>();
services.AddTransient<FormComputers>();
services.AddTransient<FormShops>();
services.AddTransient<FormShop>();
services.AddTransient<FormSupply>();
services.AddTransient<FormSell>();
}
}
}