Compare commits

..

15 Commits

Author SHA1 Message Date
a17eb83522 зафиксировать 2024-05-03 21:07:15 +04:00
3133183539 зафиксировать 2024-05-01 20:06:58 +04:00
7080f68e36 зафиксировать 2024-03-29 10:06:27 +04:00
f49b585567 зафиксировать 2024-03-24 19:18:14 +04:00
afb9661cb5 зафиксировать комментарии 2024-03-01 10:29:49 +04:00
bc2dcc7757 зафиксировать 2024-02-25 21:27:59 +04:00
83ab6be753 недоделанно 2024-02-25 20:49:20 +04:00
4190bcd82b pfabrcbhjdfnm 2024-02-25 16:27:55 +04:00
cebc200ceb зафиксировать 2024-02-23 23:53:32 +04:00
0c8c16fafa зафиксировать 2024-02-16 11:12:56 +04:00
3a497e7a0b ошибки 2024-02-16 00:01:29 +04:00
4ada37b36c зафиксить 2024-02-15 23:56:24 +04:00
81976018e3 pfabrcbhjdfnm 2024-02-15 23:14:05 +04:00
008e33ed7d зафиксировать 2024-02-15 23:12:33 +04:00
9c092cc2b9 недоделанно 2024-02-15 20:12:03 +04:00
105 changed files with 8915 additions and 0 deletions

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopDataModels\BlacksmithWorkshopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,64 @@
using BlacksmithWorkshopFileImplement.Models;
using System.Xml.Linq;
namespace BlackcmithWorkshopFileImplement
{
internal class DataFileSingleton
{
private static DataFileSingleton? instance;
private readonly string ComponentFileName = "Component.xml";
private readonly string OrderFileName = "Order.xml";
private readonly string ManufactureFileName = "Manufacture.xml";
private readonly string ShopFileName = "Shops.xml";
public List<Shop> Shops { get; private set; }
public List<Component> Components { get; private set; }
public List<Order> Orders { get; private set; }
public List<Manufacture> Manufactures { 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 SaveManufactures() => SaveData(Manufactures, ManufactureFileName,
"Manufactures", x => x.GetXElement);
public void SaveOrders() => SaveData(Orders, OrderFileName,
"Orders", x => x.GetXElement);
public void SaveShops() => SaveData(Shops, ShopFileName,
"Shops", x => x.GetXElement);
private DataFileSingleton()
{
Components = LoadData(ComponentFileName, "Component", x =>
Component.Create(x)!)!;
Manufactures = LoadData(ManufactureFileName, "Manufacture", x =>
Manufacture.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)
{
if (File.Exists(filename))
{
return
XDocument.Load(filename)?.Root?.Elements(xmlNodeName)?.Select(selectFunction)?.ToList();
}
return new List<T>();
}
private static void SaveData<T>(List<T> data, string filename, string
xmlNodeName, Func<T, XElement> selectFunction)
{
if (data != null)
{
new XDocument(new XElement(xmlNodeName,
data.Select(selectFunction).ToArray())).Save(filename);
}
}
}
}

View File

@ -0,0 +1,91 @@
using BlackcmithWorkshopFileImplement;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopFileImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
private readonly DataFileSingleton source;
public ComponentStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ComponentViewModel> GetFullList()
{
return source.Components
.Select(x => x.GetViewModel)
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel
model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
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)
{
return null;
}
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;
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
source.Components.Add(newComponent);
source.SaveComponents();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
var component = source.Components.FirstOrDefault(x => x.Id ==
model.Id);
if (component == null)
{
return null;
}
component.Update(model);
source.SaveComponents();
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
var element = source.Components.FirstOrDefault(x => x.Id ==
model.Id);
if (element != null)
{
source.Components.Remove(element);
source.SaveComponents();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,91 @@
using BlackcmithWorkshopFileImplement;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopFileImplement.Implements
{
public class ManufactureStorage : IManufactureStorage
{
private readonly DataFileSingleton source;
public ManufactureStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<ManufactureViewModel> GetFullList()
{
return source.Manufactures
.Select(x => x.GetViewModel)
.ToList();
}
public List<ManufactureViewModel> GetFilteredList(ManufactureSearchModel model)
{
if (string.IsNullOrEmpty(model.ManufactureName))
{
return new();
}
return source.Manufactures
.Where(x => x.ManufactureName.Contains(model.ManufactureName))
.Select(x => x.GetViewModel)
.ToList();
}
public ManufactureViewModel? GetElement(ManufactureSearchModel model)
{
if (string.IsNullOrEmpty(model.ManufactureName) && !model.Id.HasValue)
{
return null;
}
return source.Manufactures
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ManufactureName) && x.ManufactureName ==
model.ManufactureName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ManufactureViewModel? Insert(ManufactureBindingModel model)
{
model.Id = source.Manufactures.Count > 0 ? source.Manufactures.Max(x =>
x.Id) + 1 : 1;
var newManufacture = Manufacture.Create(model);
if (newManufacture == null)
{
return null;
}
source.Manufactures.Add(newManufacture);
source.SaveManufactures();
return newManufacture.GetViewModel;
}
public ManufactureViewModel? Update(ManufactureBindingModel model)
{
var Manufacture = source.Manufactures.FirstOrDefault(x => x.Id ==
model.Id);
if (Manufacture == null)
{
return null;
}
Manufacture.Update(model);
source.SaveManufactures();
return Manufacture.GetViewModel;
}
public ManufactureViewModel? Delete(ManufactureBindingModel model)
{
var Manufacture = source.Manufactures.FirstOrDefault(x => x.Id ==
model.Id);
if (Manufacture != null)
{
source.Manufactures.Remove(Manufacture);
source.SaveManufactures();
return Manufacture.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,99 @@
using BlackcmithWorkshopFileImplement;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopFileImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataFileSingleton source;
public OrderStorage()
{
source = DataFileSingleton.GetInstance();
}
public List<OrderViewModel> GetFullList()
{
return source.Orders
.Select(x => AccessManufactureStorage(x.GetViewModel))
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
return source.Orders
.Where(x => x.Id == model.Id)
.Select(x => AccessManufactureStorage(x.GetViewModel))
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
return AccessManufactureStorage(source.Orders.FirstOrDefault(
x => (model.Id.HasValue && x.Id == model.Id))?.GetViewModel
);
}
public OrderViewModel? Insert(OrderBindingModel model)
{
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();
return AccessManufactureStorage(newOrder.GetViewModel);
}
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 AccessManufactureStorage(order.GetViewModel);
}
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 AccessManufactureStorage(element.GetViewModel);
}
return null;
}
public OrderViewModel? AccessManufactureStorage(OrderViewModel model)
{
if (model == null)
return null;
foreach (var Manufacture in source.Manufactures)
{
if (Manufacture.Id == model.ManufactureId)
{
model.ManufactureName = Manufacture.ManufactureName;
break;
}
}
return model;
}
}
}

View File

@ -0,0 +1,129 @@
using BlackcmithWorkshopFileImplement;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using BlacksmithWorkshopFileImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopFileImplement.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 component = _source.Shops.FirstOrDefault(x => x.Id ==
model.Id);
if (component == null)
{
return null;
}
component.Update(model);
_source.SaveShops();
return component.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;
}
private bool CheckSell(int ManufactureId, int count)
{
count -= _source.Shops.Select(x => x.ShopManufactures.Select(y =>
(y.Value.Item1.Id == ManufactureId ? y.Value.Item2 : 0)).Sum()).Sum();
return count <= 0;
}
public bool SellManufactures(IManufactureModel model, int count)
{
var neededManufacture = _source.Manufactures.FirstOrDefault(x => x.Id == model.Id);
if (neededManufacture == null || !CheckSell(neededManufacture.Id, count))
{
return false;
}
for (int i = 0; i < _source.Shops.Count; i++)
{
var shop = _source.Shops[i];
var assortment = shop.ShopManufactures;
foreach (var manufacture in assortment.Where(x => x.Value.Item1.Id == neededManufacture.Id))
{
var min = Math.Min(manufacture.Value.Item2, count);
assortment[manufacture.Value.Item1.Id] = (manufacture.Value.Item1, manufacture.Value.Item2 - min);
count -= min;
if (count <= 0)
{
break;
}
}
shop.Update(new ShopBindingModel
{
Id = shop.Id,
ShopName = shop.ShopName,
Address = shop.Address,
OpeningDate = shop.OpeningDate,
MaxCapacity = shop.MaxCapacity,
ShopManufactures = assortment
});
}
_source.SaveShops();
return true;
}
}
}

View File

@ -0,0 +1,64 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace BlacksmithWorkshopFileImplement.Models
{
public class Component : IComponentModel
{
public int Id { get; set; }
public string ComponentName { get; set; } = string.Empty;
public double Cost { get; set; }
public static Component? Create(ComponentBindingModel model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost,
};
}
public static Component? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Component()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ComponentName = element.Element("ComponentName")!.Value,
Cost = Convert.ToDouble(element.Element("Cost")!.Value),
};
}
public void Update(ComponentBindingModel model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
public XElement GetXElement => new("Component",
new XAttribute("Id", Id),
new XElement("ComponentName", ComponentName),
new XElement("Cost", Cost.ToString()));
}
}

View File

@ -0,0 +1,96 @@
using BlackcmithWorkshopFileImplement;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace BlacksmithWorkshopFileImplement.Models
{
public class Manufacture : IManufactureModel
{
public int Id { get; private set; }
public string ManufactureName { get; private set; } = string.Empty;
public double Price { get; private set; }
public Dictionary<int, int> Components { get; private set; } = new();
private Dictionary<int, (IComponentModel, int)>? _ManufactureComponents = null;
public Dictionary<int, (IComponentModel, int)> ManufactureComponents
{
get
{
if (_ManufactureComponents == null)
{
var source = DataFileSingleton.GetInstance();
_ManufactureComponents = Components.ToDictionary(x => x.Key, y =>
((source.Components.FirstOrDefault(z => z.Id == y.Key) as IComponentModel)!,
y.Value));
}
return _ManufactureComponents;
}
}
public static Manufacture? Create(ManufactureBindingModel model)
{
if (model == null)
{
return null;
}
return new Manufacture()
{
Id = model.Id,
ManufactureName = model.ManufactureName,
Price = model.Price,
Components = model.ManufactureComponents.ToDictionary(x => x.Key, x
=> x.Value.Item2)
};
}
public static Manufacture? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Manufacture()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ManufactureName = element.Element("ManufactureName")!.Value,
Price = Convert.ToDouble(element.Element("Price")!.Value),
Components =
element.Element("ManufactureComponents")!.Elements("ManufactureComponent")
.ToDictionary(x =>
Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ManufactureBindingModel model)
{
if (model == null)
{
return;
}
ManufactureName = model.ManufactureName;
Price = model.Price;
Components = model.ManufactureComponents.ToDictionary(x => x.Key, x =>
x.Value.Item2);
_ManufactureComponents = null;
}
public ManufactureViewModel GetViewModel => new()
{
Id = Id,
ManufactureName = ManufactureName,
Price = Price,
ManufactureComponents = ManufactureComponents
};
public XElement GetXElement => new("Manufacture",
new XAttribute("Id", Id),
new XElement("ManufactureName", ManufactureName),
new XElement("Price", Price.ToString()),
new XElement("ManufactureComponents", Components.Select(x =>
new XElement("ManufactureComponent",
new XElement("Key", x.Key),
new XElement("Value", x.Value))).ToArray()));
}
}

View File

@ -0,0 +1,87 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Enums;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace BlacksmithWorkshopFileImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
public int ManufactureId { get; private set; }
public int Count { get; private set; }
public double Sum { get; private set; }
public OrderStatus Status { get; private set; }
public DateTime DateCreate { get; private set; }
public DateTime? DateImplement { get; private set; }
public static Order? Create(OrderBindingModel model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
ManufactureId = model.ManufactureId,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
};
}
public static Order? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Order()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ManufactureId = Convert.ToInt32(element.Element("ManufactureId")!.Value),
Count = Convert.ToInt32(element.Element("Count")!.Value),
Sum = Convert.ToDouble(element.Element("Sum")!.Value),
Status = (OrderStatus)Enum.Parse(typeof(OrderStatus), element.Element("Status")!.Value.ToString()),
DateCreate = Convert.ToDateTime(element.Element("DateCreate")!.Value),
DateImplement = string.IsNullOrEmpty(element.Element("DateImplement")!.Value) ? null : Convert.ToDateTime(element.Element("DateImplement")!.Value)
};
}
public void Update(OrderBindingModel model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
ManufactureId = ManufactureId,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
};
public XElement GetXElement => new("Order",
new XAttribute("Id", Id),
new XElement("ManufactureId", ManufactureId),
new XElement("Sum", Sum.ToString()),
new XElement("Count", Count),
new XElement("Status", Status.ToString()),
new XElement("DateCreate", DateCreate.ToString()),
new XElement("DateImplement", DateImplement.ToString())
);
}
}

View File

@ -0,0 +1,107 @@
using BlackcmithWorkshopFileImplement;
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace BlacksmithWorkshopFileImplement.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 OpeningDate { get; private set; }
public int MaxCapacity { get; private set; }
public Dictionary<int, int> Manufactures { get; private set; } = new();
private Dictionary<int, (IManufactureModel, int)>? _shopManufactures = null;
public Dictionary<int, (IManufactureModel, int)> ShopManufactures
{
get
{
if (_shopManufactures == null)
{
var source = DataFileSingleton.GetInstance();
_shopManufactures = Manufactures.ToDictionary(x => x.Key, y =>
((source.Manufactures.FirstOrDefault(z => z.Id == y.Key) as IManufactureModel)!,
y.Value));
}
return _shopManufactures;
}
}
public static Shop? Create(ShopBindingModel model)
{
if (model == null)
return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
OpeningDate = model.OpeningDate,
MaxCapacity = model.MaxCapacity,
Manufactures = model.ShopManufactures.ToDictionary(x => x.Key, x => x.Value.Item2)
};
}
public static Shop? Create(XElement element)
{
if (element == null)
{
return null;
}
return new Shop()
{
Id = Convert.ToInt32(element.Attribute("Id")!.Value),
ShopName = element.Element("ShopName")!.Value,
Address = element.Element("Address")!.Value,
MaxCapacity = Convert.ToInt32(element.Element("MaxCapacity")!.Value),
OpeningDate = Convert.ToDateTime(element.Element("DateOpen")!.Value),
Manufactures = element.Element("ShopManufactures")!.Elements("ShopManufacture")
.ToDictionary(x =>
Convert.ToInt32(x.Element("Key")?.Value), x =>
Convert.ToInt32(x.Element("Value")?.Value))
};
}
public void Update(ShopBindingModel model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
OpeningDate = model.OpeningDate;
MaxCapacity = model.MaxCapacity;
if (model.ShopManufactures.Count > 0)
{
Manufactures = model.ShopManufactures.ToDictionary(x => x.Key, x => x.Value.Item2);
_shopManufactures = null;
}
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
OpeningDate = OpeningDate,
MaxCapacity = MaxCapacity,
ShopManufactures = ShopManufactures
};
public XElement GetXElement => new("Shop",
new XAttribute("Id", Id),
new XElement("ShopName", ShopName),
new XElement("Address", Address),
new XElement("DateOpen", OpeningDate),
new XElement("MaxCapacity", MaxCapacity),
new XElement("ShopManufactures", Manufactures
.Select(x => new XElement("ShopManufacture",
new XElement("Key", x.Key),
new XElement("Value", x.Value))
).ToArray()));
}
}

View File

@ -0,0 +1,65 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshop", "BlacksmithWorkshop\BlacksmithWorkshop.csproj", "{54575961-6705-47D3-8063-416A45518BED}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopDataModels", "BlacksmithWorkshopDataModels\BlacksmithWorkshopDataModels.csproj", "{96E8CFC7-A9D8-438B-AE8C-184ED25D5AAC}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopContracts", "BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj", "{40A50297-20F6-4F73-834D-0902F6F7965B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopBusinessLogic", "BlacksmithWorkshopBusinessLogic\BlacksmithWorkshopBusinessLogic.csproj", "{81DD48F2-F58D-4C86-AC0C-74E447366DFA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopListImplement", "BlacksmithWorkshopListImplement\BlacksmithWorkshopListImplement.csproj", "{F6B2AA66-2A89-4DEA-AE90-84991C1EE424}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlacksmithWorkshopFileImplement", "BlackcmithWorkshopFileImplement\BlacksmithWorkshopFileImplement.csproj", "{63C0A1A4-FA76-4F7C-8144-A33085F7DF08}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlacksmithWorkshopDatabaseImplement", "BlacksmithWorkshopDatabaseImplement\BlacksmithWorkshopDatabaseImplement.csproj", "{07550D11-E516-44E1-88A4-5B21E3EE72CC}"
ProjectSection(ProjectDependencies) = postProject
{40A50297-20F6-4F73-834D-0902F6F7965B} = {40A50297-20F6-4F73-834D-0902F6F7965B}
{96E8CFC7-A9D8-438B-AE8C-184ED25D5AAC} = {96E8CFC7-A9D8-438B-AE8C-184ED25D5AAC}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{54575961-6705-47D3-8063-416A45518BED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{54575961-6705-47D3-8063-416A45518BED}.Debug|Any CPU.Build.0 = Debug|Any CPU
{54575961-6705-47D3-8063-416A45518BED}.Release|Any CPU.ActiveCfg = Release|Any CPU
{54575961-6705-47D3-8063-416A45518BED}.Release|Any CPU.Build.0 = Release|Any CPU
{96E8CFC7-A9D8-438B-AE8C-184ED25D5AAC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{96E8CFC7-A9D8-438B-AE8C-184ED25D5AAC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{96E8CFC7-A9D8-438B-AE8C-184ED25D5AAC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{96E8CFC7-A9D8-438B-AE8C-184ED25D5AAC}.Release|Any CPU.Build.0 = Release|Any CPU
{40A50297-20F6-4F73-834D-0902F6F7965B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{40A50297-20F6-4F73-834D-0902F6F7965B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{40A50297-20F6-4F73-834D-0902F6F7965B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{40A50297-20F6-4F73-834D-0902F6F7965B}.Release|Any CPU.Build.0 = Release|Any CPU
{81DD48F2-F58D-4C86-AC0C-74E447366DFA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{81DD48F2-F58D-4C86-AC0C-74E447366DFA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{81DD48F2-F58D-4C86-AC0C-74E447366DFA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{81DD48F2-F58D-4C86-AC0C-74E447366DFA}.Release|Any CPU.Build.0 = Release|Any CPU
{F6B2AA66-2A89-4DEA-AE90-84991C1EE424}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F6B2AA66-2A89-4DEA-AE90-84991C1EE424}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F6B2AA66-2A89-4DEA-AE90-84991C1EE424}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F6B2AA66-2A89-4DEA-AE90-84991C1EE424}.Release|Any CPU.Build.0 = Release|Any CPU
{63C0A1A4-FA76-4F7C-8144-A33085F7DF08}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{63C0A1A4-FA76-4F7C-8144-A33085F7DF08}.Debug|Any CPU.Build.0 = Debug|Any CPU
{63C0A1A4-FA76-4F7C-8144-A33085F7DF08}.Release|Any CPU.ActiveCfg = Release|Any CPU
{63C0A1A4-FA76-4F7C-8144-A33085F7DF08}.Release|Any CPU.Build.0 = Release|Any CPU
{07550D11-E516-44E1-88A4-5B21E3EE72CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{07550D11-E516-44E1-88A4-5B21E3EE72CC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{07550D11-E516-44E1-88A4-5B21E3EE72CC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{07550D11-E516-44E1-88A4-5B21E3EE72CC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8DF79FEE-7448-48A9-BF6C-BC36C78CDC16}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.16">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlackcmithWorkshopFileImplement\BlacksmithWorkshopFileImplement.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopBusinessLogic\BlacksmithWorkshopBusinessLogic.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopDatabaseImplement\BlacksmithWorkshopDatabaseImplement.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopListImplement\BlacksmithWorkshopListImplement.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.2.8" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.8" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,119 @@
namespace BlacksmithWorkshop
{
partial class FormComponent
{
/// <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()
{
labelName = new Label();
labelCost = new Label();
textBoxName = new TextBox();
textBoxCost = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(18, 9);
labelName.Name = "labelName";
labelName.Size = new Size(62, 15);
labelName.TabIndex = 0;
labelName.Text = "Название:";
//
// labelCost
//
labelCost.AutoSize = true;
labelCost.Location = new Point(18, 39);
labelCost.Name = "labelCost";
labelCost.Size = new Size(38, 15);
labelCost.TabIndex = 1;
labelCost.Text = "Цена:";
//
// textBoxName
//
textBoxName.Location = new Point(86, 6);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(393, 23);
textBoxName.TabIndex = 2;
//
// textBoxCost
//
textBoxCost.Location = new Point(86, 36);
textBoxCost.Name = "textBoxCost";
textBoxCost.Size = new Size(393, 23);
textBoxCost.TabIndex = 3;
//
// buttonSave
//
buttonSave.Location = new Point(108, 65);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(76, 24);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(314, 65);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(76, 24);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormComponent
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(503, 103);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxCost);
Controls.Add(textBoxName);
Controls.Add(labelCost);
Controls.Add(labelName);
Name = "FormComponent";
StartPosition = FormStartPosition.CenterParent;
Text = "Компонент";
Load += FormComponent_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelName;
private Label labelCost;
private TextBox textBoxName;
private TextBox textBoxCost;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,89 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using Microsoft.Extensions.Logging;
namespace BlacksmithWorkshop
{
public partial class FormComponent : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
private int? _id;
public int Id { set { _id = value; } }
public FormComponent(ILogger<FormComponent> logger, IComponentLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormComponent_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
try
{
_logger.LogInformation("Ïîëó÷åíèå êîìïîíåíòà");
var view = _logic.ReadElement(new ComponentSearchModel
{
Id =
_id.Value
});
if (view != null)
{
textBoxName.Text = view.ComponentName;
textBoxCost.Text = view.Cost.ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Îøèáêà ïîëó÷åíèÿ êîìïîíåíòà");
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Çàïîëíèòå íàçâàíèå", "Îøèáêà",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Ñîõðàíåíèå êîìïîíåíòà");
try
{
var model = new ComponentBindingModel
{
Id = _id ?? 0,
ComponentName = textBoxName.Text,
Cost = Convert.ToDouble(textBoxCost.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);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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,113 @@
namespace BlacksmithWorkshop
{
partial class FormComponents
{
/// <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()
{
buttonAdd = new Button();
buttonChange = new Button();
buttonDelete = new Button();
buttonRefresh = new Button();
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// buttonAdd
//
buttonAdd.Location = new Point(474, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(118, 29);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += AddButton_Click;
//
// buttonChange
//
buttonChange.Location = new Point(474, 47);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(118, 29);
buttonChange.TabIndex = 2;
buttonChange.Text = "Изменить";
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ChangeButton_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(474, 82);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(118, 29);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += DeleteButton_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(474, 117);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(118, 29);
buttonRefresh.TabIndex = 4;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += RefreshButton_Click;
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 0);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(468, 450);
dataGridView.TabIndex = 5;
//
// FormComponents
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(600, 450);
Controls.Add(dataGridView);
Controls.Add(buttonRefresh);
Controls.Add(buttonDelete);
Controls.Add(buttonChange);
Controls.Add(buttonAdd);
Name = "FormComponents";
StartPosition = FormStartPosition.CenterParent;
Text = "Компоненты";
Load += ComponentsForm_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonAdd;
private Button buttonChange;
private Button buttonDelete;
private Button buttonRefresh;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,117 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.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 BlacksmithWorkshop
{
public partial class FormComponents : Form
{
private readonly ILogger _logger;
private readonly IComponentLogic _logic;
public FormComponents(ILogger<FormComponents> logger, IComponentLogic
logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void ComponentsForm_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ComponentName"].AutoSizeMode =
DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка компонентов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void AddButton_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponent));
if (service is FormComponent form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void ChangeButton_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service =
Program.ServiceProvider?.GetService(typeof(FormComponent));
if (service is FormComponent form)
{
form.Id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление компонента");
try
{
if (!_logic.Delete(new ComponentBindingModel
{
Id = id
}))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления компонента");
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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,147 @@
namespace BlacksmithWorkshop
{
partial class FormCreateOrder
{
/// <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()
{
labelName = new Label();
labelCount = new Label();
labelSum = new Label();
TextBoxCount = new TextBox();
ComboBoxManufacture = new ComboBox();
TextBoxSum = new TextBox();
buttonCancel = new Button();
buttonSave = new Button();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(22, 17);
labelName.Name = "labelName";
labelName.Size = new Size(56, 15);
labelName.TabIndex = 0;
labelName.Text = "Изделие:";
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(22, 46);
labelCount.Name = "labelCount";
labelCount.Size = new Size(75, 15);
labelCount.TabIndex = 1;
labelCount.Text = "Количество:";
//
// labelSum
//
labelSum.AutoSize = true;
labelSum.Location = new Point(22, 75);
labelSum.Name = "labelSum";
labelSum.Size = new Size(48, 15);
labelSum.TabIndex = 2;
labelSum.Text = "Сумма:";
//
// TextBoxCount
//
TextBoxCount.Location = new Point(125, 43);
TextBoxCount.Name = "TextBoxCount";
TextBoxCount.Size = new Size(214, 23);
TextBoxCount.TabIndex = 3;
TextBoxCount.TextChanged += TextBoxCount_TextChanged;
//
// ComboBoxManufacture
//
ComboBoxManufacture.DropDownStyle = ComboBoxStyle.DropDownList;
ComboBoxManufacture.FormattingEnabled = true;
ComboBoxManufacture.Location = new Point(125, 14);
ComboBoxManufacture.Name = "ComboBoxManufacture";
ComboBoxManufacture.Size = new Size(214, 23);
ComboBoxManufacture.TabIndex = 4;
ComboBoxManufacture.SelectedIndexChanged += ComboBoxManufacture_SelectedIndexChanged;
//
// TextBoxSum
//
TextBoxSum.Location = new Point(125, 72);
TextBoxSum.Name = "TextBoxSum";
TextBoxSum.ReadOnly = true;
TextBoxSum.Size = new Size(214, 23);
TextBoxSum.TabIndex = 5;
TextBoxSum.TextChanged += TextBoxSum_TextChanged;
//
// buttonCancel
//
buttonCancel.Location = new Point(247, 104);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(77, 24);
buttonCancel.TabIndex = 6;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += CancelButton_Click;
//
// buttonSave
//
buttonSave.Location = new Point(164, 104);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(77, 24);
buttonSave.TabIndex = 7;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += SaveButton_Click;
//
// FormCreateOrder
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(349, 139);
Controls.Add(buttonSave);
Controls.Add(buttonCancel);
Controls.Add(TextBoxSum);
Controls.Add(ComboBoxManufacture);
Controls.Add(TextBoxCount);
Controls.Add(labelSum);
Controls.Add(labelCount);
Controls.Add(labelName);
Name = "FormCreateOrder";
StartPosition = FormStartPosition.CenterParent;
Text = "Заказ";
Load += FormCreateOrder_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelName;
private Label labelCount;
private Label labelSum;
private TextBox TextBoxCount;
private ComboBox ComboBoxManufacture;
private TextBox TextBoxSum;
private Button buttonCancel;
private Button buttonSave;
}
}

View File

@ -0,0 +1,134 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
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 BlacksmithWorkshop
{
public partial class FormCreateOrder : Form
{
private readonly ILogger _logger;
private readonly IManufactureLogic _logicI;
private readonly IOrderLogic _logicO;
public FormCreateOrder(ILogger<FormCreateOrder> logger, IManufactureLogic
logicI, IOrderLogic logicO)
{
InitializeComponent();
_logger = logger;
_logicI = logicI;
_logicO = logicO;
}
private void FormCreateOrder_Load(object sender, EventArgs e)
{
_logger.LogInformation("Загрузка кузнечных изделий для заказа");
try
{
var list = _logicI.ReadList(null);
if (list != null)
{
ComboBoxManufacture.DisplayMember = "ManufactureName";
ComboBoxManufacture.ValueMember = "Id";
ComboBoxManufacture.DataSource = list;
ComboBoxManufacture.SelectedItem = null;
}
_logger.LogInformation("Кузнечные изделия загружены");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки кузнечных изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void CalcSum()
{
if (ComboBoxManufacture.SelectedValue != null &&
!string.IsNullOrEmpty(TextBoxCount.Text))
{
try
{
int id = Convert.ToInt32(ComboBoxManufacture.SelectedValue);
var Manufacture = _logicI.ReadElement(new ManufactureSearchModel
{
Id = id
});
int count = Convert.ToInt32(TextBoxCount.Text);
TextBoxSum.Text = Math.Round(count * (Manufacture?.Price ?? 0),
2).ToString();
_logger.LogInformation("Расчет суммы заказа");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка расчета суммы заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void TextBoxCount_TextChanged(object sender, EventArgs e)
{
CalcSum();
}
private void TextBoxSum_TextChanged(object sender, EventArgs e)
{
CalcSum();
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(TextBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (ComboBoxManufacture.SelectedValue == null)
{
MessageBox.Show("Выберите кузнечное изделие", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Создание заказа");
try
{
var operationResult = _logicO.CreateOrder(new OrderBindingModel
{
ManufactureId = Convert.ToInt32(ComboBoxManufacture.SelectedValue),
Count = Convert.ToInt32(TextBoxCount.Text),
Sum = Convert.ToDouble(TextBoxSum.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);
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void ComboBoxManufacture_SelectedIndexChanged(object sender, EventArgs e)
{
CalcSum();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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,198 @@
namespace BlacksmithWorkshop
{
partial class FormMain
{
/// <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()
{
menuStrip = new MenuStrip();
GuidesToolStripMenuItem = new ToolStripMenuItem();
ComponentsToolStripMenuItem = new ToolStripMenuItem();
ManufacturesToolStripMenuItem = new ToolStripMenuItem();
ShopsToolStripMenuItem = new ToolStripMenuItem();
SupplyToolStripMenuItem = new ToolStripMenuItem();
SalesToolStripMenuItem = new ToolStripMenuItem();
dataGridView = new DataGridView();
buttonCreateOrder = new Button();
buttonRefresh = new Button();
buttonIssued = new Button();
buttonReady = new Button();
buttonTakeInWork = new Button();
menuStrip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { GuidesToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1011, 24);
menuStrip.TabIndex = 0;
menuStrip.Text = "Меню";
//
// GuidesToolStripMenuItem
//
GuidesToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { ComponentsToolStripMenuItem, ManufacturesToolStripMenuItem, ShopsToolStripMenuItem, SupplyToolStripMenuItem, SalesToolStripMenuItem });
GuidesToolStripMenuItem.Name = "GuidesToolStripMenuItem";
GuidesToolStripMenuItem.Size = new Size(94, 20);
GuidesToolStripMenuItem.Text = "Справочники";
//
// ComponentsToolStripMenuItem
//
ComponentsToolStripMenuItem.Name = "ComponentsToolStripMenuItem";
ComponentsToolStripMenuItem.Size = new Size(198, 22);
ComponentsToolStripMenuItem.Text = "Компоненты";
ComponentsToolStripMenuItem.Click += ComponentsStripMenuItem_Click;
//
// ManufacturesToolStripMenuItem
//
ManufacturesToolStripMenuItem.Name = "ManufacturesToolStripMenuItem";
ManufacturesToolStripMenuItem.Size = new Size(198, 22);
ManufacturesToolStripMenuItem.Text = "Кузнечные изделия";
ManufacturesToolStripMenuItem.Click += ManufacturesStripMenuItem_Click;
//
// ShopsToolStripMenuItem
//
ShopsToolStripMenuItem.Name = "ShopsToolStripMenuItem";
ShopsToolStripMenuItem.Size = new Size(198, 22);
ShopsToolStripMenuItem.Text = "Магазины";
ShopsToolStripMenuItem.Click += ShopsToolStripMenuItem_Click;
//
// SupplyToolStripMenuItem
//
SupplyToolStripMenuItem.Name = "SupplyToolStripMenuItem";
SupplyToolStripMenuItem.Size = new Size(198, 22);
SupplyToolStripMenuItem.Text = "Пополнение магазина";
SupplyToolStripMenuItem.Click += SupplyToolStripMenuItem_Click;
//
// SalesToolStripMenuItem
//
SalesToolStripMenuItem.Name = "SalesToolStripMenuItem";
SalesToolStripMenuItem.Size = new Size(198, 22);
SalesToolStripMenuItem.Text = "Продажи";
SalesToolStripMenuItem.Click += SalesToolStripMenuItem_Click;
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 23);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(847, 427);
dataGridView.TabIndex = 1;
//
// buttonCreateOrder
//
buttonCreateOrder.Location = new Point(853, 38);
buttonCreateOrder.Name = "buttonCreateOrder";
buttonCreateOrder.Size = new Size(148, 31);
buttonCreateOrder.TabIndex = 2;
buttonCreateOrder.Text = "Создать заказ";
buttonCreateOrder.UseVisualStyleBackColor = true;
buttonCreateOrder.Click += CreateOrderButton_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(853, 186);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(148, 31);
buttonRefresh.TabIndex = 3;
buttonRefresh.Text = "Обновить список";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += RefreshButton_Click;
//
// buttonIssued
//
buttonIssued.Location = new Point(853, 149);
buttonIssued.Name = "buttonIssued";
buttonIssued.Size = new Size(148, 31);
buttonIssued.TabIndex = 4;
buttonIssued.Text = "Заказ выдан";
buttonIssued.UseVisualStyleBackColor = true;
buttonIssued.Click += IssuedButton_Click;
//
// buttonReady
//
buttonReady.Location = new Point(853, 112);
buttonReady.Name = "buttonReady";
buttonReady.Size = new Size(148, 31);
buttonReady.TabIndex = 5;
buttonReady.Text = "Заказ готов";
buttonReady.UseVisualStyleBackColor = true;
buttonReady.Click += ReadyButton_Click;
//
// buttonTakeInWork
//
buttonTakeInWork.Location = new Point(853, 75);
buttonTakeInWork.Name = "buttonTakeInWork";
buttonTakeInWork.Size = new Size(148, 31);
buttonTakeInWork.TabIndex = 6;
buttonTakeInWork.Text = "Отдать на выполнение";
buttonTakeInWork.UseVisualStyleBackColor = true;
buttonTakeInWork.Click += TakeInWorkButton_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1011, 450);
Controls.Add(buttonTakeInWork);
Controls.Add(buttonReady);
Controls.Add(buttonIssued);
Controls.Add(buttonRefresh);
Controls.Add(buttonCreateOrder);
Controls.Add(dataGridView);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormMain";
StartPosition = FormStartPosition.CenterParent;
Text = "Кузница";
Load += FormMain_Load;
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private MenuStrip menuStrip;
private ToolStripMenuItem GuidesToolStripMenuItem;
private ToolStripMenuItem ComponentsToolStripMenuItem;
private ToolStripMenuItem ManufacturesToolStripMenuItem;
private DataGridView dataGridView;
private Button buttonCreateOrder;
private Button buttonRefresh;
private Button buttonIssued;
private Button buttonReady;
private Button buttonTakeInWork;
private ToolStripMenuItem ShopsToolStripMenuItem;
private ToolStripMenuItem SupplyToolStripMenuItem;
private ToolStripMenuItem SalesToolStripMenuItem;
}
}

View File

@ -0,0 +1,191 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopDataModels.Enums;
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 BlacksmithWorkshop
{
public partial class FormMain : Form
{
private readonly ILogger _logger;
private readonly IOrderLogic _orderLogic;
public FormMain(ILogger<FormMain> logger, IOrderLogic orderLogic)
{
InitializeComponent();
_logger = logger;
_orderLogic = orderLogic;
}
private void ComponentsStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormComponents));
if (service is FormComponents form)
{
form.ShowDialog();
}
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
_logger.LogInformation("Загрузка заказов");
try
{
var list = _orderLogic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["ManufactureId"].Visible = false;
dataGridView.Columns["ManufactureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
_logger.LogInformation("Загрузка заказов");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки заказов");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ManufacturesStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufactures));
if (service is FormManufactures form)
{
form.ShowDialog();
}
}
private void CreateOrderButton_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormCreateOrder));
if (service is FormCreateOrder form)
{
form.ShowDialog();
LoadData();
}
}
private OrderBindingModel CreateBindingModel(int id, bool isDone = false)
{
return new OrderBindingModel
{
Id = id,
ManufactureId = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ManufactureId"].Value),
Status = Enum.Parse<OrderStatus>(dataGridView.SelectedRows[0].Cells["Status"].Value.ToString()),
Count = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Count"].Value),
Sum = double.Parse(dataGridView.SelectedRows[0].Cells["Sum"].Value.ToString()),
DateCreate = DateTime.Parse(dataGridView.SelectedRows[0].Cells["DateCreate"].Value.ToString()),
};
}
private void TakeInWorkButton_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'В работе'", id);
try
{
var operationResult = _orderLogic.TakeOrderInWork(CreateBindingModel(id));
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка передачи заказа в работу");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void ReadyButton_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Готов'",
id);
try
{
var operationResult = _orderLogic.FinishOrder(CreateBindingModel(id));
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о готовности заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void IssuedButton_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
int id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Заказ №{id}. Меняется статус на 'Выдан'",
id);
try
{
var operationResult = _orderLogic.DeliveryOrder(CreateBindingModel(id));
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
_logger.LogInformation("Заказ №{id} выдан", id);
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка отметки о выдачи заказа");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
private void ShopsToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShops));
if (service is FormShops form)
{
form.ShowDialog();
}
}
private void SupplyToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSupply));
if (service is FormSupply form)
{
form.ShowDialog();
}
}
private void SalesToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormSell));
if (service is FormSell form)
{
form.ShowDialog();
}
}
}
}

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,225 @@
namespace BlacksmithWorkshop
{
partial class FormManufacture
{
/// <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()
{
labelName = new Label();
labelCost = new Label();
textBoxName = new TextBox();
textBoxPrice = new TextBox();
groupBoxComponents = new GroupBox();
dataGridView = new DataGridView();
ColumnId = new DataGridViewTextBoxColumn();
ColumnName = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
buttonRefresh = new Button();
buttonDelete = new Button();
buttonChange = new Button();
buttonAdd = new Button();
buttonSave = new Button();
buttonCancel = new Button();
groupBoxComponents.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(15, 10);
labelName.Name = "labelName";
labelName.Size = new Size(62, 15);
labelName.TabIndex = 0;
labelName.Text = "Название:";
//
// labelCost
//
labelCost.AutoSize = true;
labelCost.Location = new Point(15, 41);
labelCost.Name = "labelCost";
labelCost.Size = new Size(70, 15);
labelCost.TabIndex = 1;
labelCost.Text = "Стоимость:";
//
// textBoxName
//
textBoxName.Location = new Point(106, 7);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(289, 23);
textBoxName.TabIndex = 2;
//
// textBoxPrice
//
textBoxPrice.Location = new Point(106, 38);
textBoxPrice.Name = "textBoxPrice";
textBoxPrice.ReadOnly = true;
textBoxPrice.Size = new Size(289, 23);
textBoxPrice.TabIndex = 3;
//
// groupBoxComponents
//
groupBoxComponents.Controls.Add(dataGridView);
groupBoxComponents.Controls.Add(buttonRefresh);
groupBoxComponents.Controls.Add(buttonDelete);
groupBoxComponents.Controls.Add(buttonChange);
groupBoxComponents.Controls.Add(buttonAdd);
groupBoxComponents.Location = new Point(15, 67);
groupBoxComponents.Name = "groupBoxComponents";
groupBoxComponents.Size = new Size(596, 285);
groupBoxComponents.TabIndex = 4;
groupBoxComponents.TabStop = false;
groupBoxComponents.Text = "Компоненты";
//
// dataGridView
//
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnId, ColumnName, ColumnCount });
dataGridView.Location = new Point(11, 23);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(439, 256);
dataGridView.TabIndex = 5;
//
// ColumnId
//
ColumnId.HeaderText = "Идентификатор";
ColumnId.Name = "ColumnId";
ColumnId.Visible = false;
//
// ColumnName
//
ColumnName.FillWeight = 200F;
ColumnName.HeaderText = "Компонент";
ColumnName.Name = "ColumnName";
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.Name = "ColumnCount";
//
// buttonRefresh
//
buttonRefresh.Location = new Point(470, 137);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(106, 29);
buttonRefresh.TabIndex = 4;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRef_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(470, 102);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(106, 29);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDel_Click;
//
// buttonChange
//
buttonChange.Location = new Point(470, 67);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(106, 29);
buttonChange.TabIndex = 2;
buttonChange.Text = "Изменить";
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ButtonUpd_Click;
//
// buttonAdd
//
buttonAdd.Location = new Point(470, 32);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(106, 29);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// buttonSave
//
buttonSave.Location = new Point(373, 358);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(106, 29);
buttonSave.TabIndex = 5;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(485, 358);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(106, 29);
buttonCancel.TabIndex = 6;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormManufacture
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(626, 401);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(groupBoxComponents);
Controls.Add(textBoxPrice);
Controls.Add(textBoxName);
Controls.Add(labelCost);
Controls.Add(labelName);
Name = "FormManufacture";
StartPosition = FormStartPosition.CenterParent;
Text = "Изделие";
Load += FormManufacture_Load;
groupBoxComponents.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelName;
private Label labelCost;
private TextBox textBoxName;
private TextBox textBoxPrice;
private GroupBox groupBoxComponents;
private Button buttonRefresh;
private Button buttonDelete;
private Button buttonChange;
private Button buttonAdd;
private Button buttonSave;
private Button buttonCancel;
private DataGridView dataGridView;
private DataGridViewTextBoxColumn ColumnId;
private DataGridViewTextBoxColumn ColumnName;
private DataGridViewTextBoxColumn ColumnCount;
}
}

View File

@ -0,0 +1,214 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopDataModels.Models;
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 BlacksmithWorkshop
{
public partial class FormManufacture : Form
{
private readonly ILogger _logger;
private readonly IManufactureLogic _logic;
private int? _id;
private Dictionary<int, (IComponentModel, int)> _manufactureComponents;
public int Id { set { _id = value; } }
public FormManufacture(ILogger<FormManufacture> logger, IManufactureLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_manufactureComponents = new Dictionary<int, (IComponentModel, int)>();
}
private void FormManufacture_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка кузнечного изделия");
try
{
var view = _logic.ReadElement(new ManufactureSearchModel { Id = _id.Value });
if (view != null)
{
textBoxName.Text = view.ManufactureName;
textBoxPrice.Text = view.Price.ToString();
_manufactureComponents = view.ManufactureComponents ?? new
Dictionary<int, (IComponentModel, int)>();
LoadData();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки кузнечного изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка компонентов кузнечного изделия");
try
{
if (_manufactureComponents != null)
{
dataGridView.Rows.Clear();
foreach (var pc in _manufactureComponents)
{
dataGridView.Rows.Add(new object[] { pc.Key,
pc.Value.Item1.ComponentName, pc.Value.Item2 });
}
textBoxPrice.Text = CalcPrice().ToString();
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки компонентов кузнечного изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufactureComponent));
if (service is FormManufactureComponent form)
{
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Добавление нового компонента:{ ComponentName} - { Count}", form.ComponentModel.ComponentName, form.Count);
if (_manufactureComponents.ContainsKey(form.Id))
{
_manufactureComponents[form.Id] = (form.ComponentModel, form.Count);
}
else
{
_manufactureComponents.Add(form.Id, (form.ComponentModel, form.Count));
}
LoadData();
}
}
}
private void ButtonUpd_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufactureComponent));
if (service is FormManufactureComponent form)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value);
form.Id = id;
form.Count = _manufactureComponents[id].Item2;
if (form.ShowDialog() == DialogResult.OK)
{
if (form.ComponentModel == null)
{
return;
}
_logger.LogInformation("Изменение компонента:{ ComponentName}- { Count}", form.ComponentModel.ComponentName, form.Count);
_manufactureComponents[form.Id] = (form.ComponentModel, form.Count);
LoadData();
}
}
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
_logger.LogInformation("Удаление компонента:{ ComponentName}- { Count} ", dataGridView.SelectedRows[0].Cells[1].Value);
_manufactureComponents?.Remove(Convert.ToInt32(dataGridView.SelectedRows[0].Cells[0].Value));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}
private void ButtonRef_Click(object sender, EventArgs e)
{
LoadData();
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните название", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(textBoxPrice.Text))
{
MessageBox.Show("Заполните цену", "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
if (_manufactureComponents == null || _manufactureComponents.Count == 0)
{
MessageBox.Show("Заполните компоненты", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_logger.LogInformation("Сохранение кузнечного изделия");
try
{
var model = new ManufactureBindingModel
{
Id = _id ?? 0,
ManufactureName = textBoxName.Text,
Price = Convert.ToDouble(textBoxPrice.Text),
ManufactureComponents = _manufactureComponents
};
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);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private double CalcPrice()
{
double price = 0;
foreach (var elem in _manufactureComponents)
{
price += ((elem.Value.Item1?.Cost ?? 0) * elem.Value.Item2);
}
return Math.Round(price * 1.1, 2);
}
}
}

View File

@ -0,0 +1,129 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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="ColumnId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,120 @@
namespace BlacksmithWorkshop
{
partial class FormManufactureComponent
{
/// <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()
{
labelComponent = new Label();
comboBoxComponent = new ComboBox();
labelCount = new Label();
textBoxCount = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelComponent
//
labelComponent.AutoSize = true;
labelComponent.Location = new Point(12, 9);
labelComponent.Name = "labelComponent";
labelComponent.Size = new Size(72, 15);
labelComponent.TabIndex = 0;
labelComponent.Text = "Компонент:";
//
// comboBoxComponent
//
comboBoxComponent.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxComponent.FormattingEnabled = true;
comboBoxComponent.Location = new Point(93, 6);
comboBoxComponent.Name = "comboBoxComponent";
comboBoxComponent.Size = new Size(285, 23);
comboBoxComponent.TabIndex = 1;
//
// labelCount
//
labelCount.AutoSize = true;
labelCount.Location = new Point(12, 34);
labelCount.Name = "labelCount";
labelCount.Size = new Size(75, 15);
labelCount.TabIndex = 2;
labelCount.Text = "Количество:";
//
// textBoxCount
//
textBoxCount.Location = new Point(93, 31);
textBoxCount.Name = "textBoxCount";
textBoxCount.Size = new Size(285, 23);
textBoxCount.TabIndex = 3;
//
// buttonSave
//
buttonSave.Location = new Point(64, 60);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(107, 29);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(228, 60);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(107, 29);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormManufactureComponent
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(394, 98);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxCount);
Controls.Add(labelCount);
Controls.Add(comboBoxComponent);
Controls.Add(labelComponent);
Name = "FormManufactureComponent";
StartPosition = FormStartPosition.CenterParent;
Text = "Компонент изделия";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelComponent;
private ComboBox comboBoxComponent;
private Label labelCount;
private TextBox textBoxCount;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,90 @@
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
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 BlacksmithWorkshop
{
public partial class FormManufactureComponent : Form
{
private readonly List<ComponentViewModel>? _list;
public int Id
{
get
{
return
Convert.ToInt32(comboBoxComponent.SelectedValue);
}
set
{
comboBoxComponent.SelectedValue = value;
}
}
public IComponentModel? ComponentModel
{
get
{
if (_list == null)
{
return null;
}
foreach (var elem in _list)
{
if (elem.Id == Id)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(textBoxCount.Text); }
set
{ textBoxCount.Text = value.ToString(); }
}
public FormManufactureComponent(IComponentLogic logic)
{
InitializeComponent();
_list = logic.ReadList(null);
if (_list != null)
{
comboBoxComponent.DisplayMember = "ComponentName";
comboBoxComponent.ValueMember = "Id";
comboBoxComponent.DataSource = _list;
comboBoxComponent.SelectedItem = null;
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCount.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (comboBoxComponent.SelectedValue == null)
{
MessageBox.Show("Выберите компонент", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
DialogResult = DialogResult.OK;
Close();
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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,114 @@
namespace BlacksmithWorkshop
{
partial class FormManufactures
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
buttonAdd = new Button();
buttonChange = new Button();
buttonDelete = new Button();
buttonRefresh = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 0);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(468, 450);
dataGridView.TabIndex = 6;
//
// buttonAdd
//
buttonAdd.Location = new Point(474, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(118, 29);
buttonAdd.TabIndex = 7;
buttonAdd.Text = "Добавить";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += AddButton_Click;
//
// buttonChange
//
buttonChange.Location = new Point(474, 47);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(118, 29);
buttonChange.TabIndex = 8;
buttonChange.Text = "Изменить";
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += UpdateButton_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(474, 82);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(118, 29);
buttonDelete.TabIndex = 9;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += DeleteButton_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(474, 117);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(118, 29);
buttonRefresh.TabIndex = 10;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += RefreshButton_Click;
//
// FormManufactures
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(600, 450);
Controls.Add(buttonRefresh);
Controls.Add(buttonDelete);
Controls.Add(buttonChange);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormManufactures";
StartPosition = FormStartPosition.CenterParent;
Text = "Изделия";
Load += FormManufactures_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonChange;
private Button buttonDelete;
private Button buttonRefresh;
}
}

View File

@ -0,0 +1,106 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.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 BlacksmithWorkshop
{
public partial class FormManufactures : Form
{
private readonly ILogger _logger;
private readonly IManufactureLogic _logic;
public FormManufactures(ILogger<FormManufactures> logger, IManufactureLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
}
private void FormManufactures_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _logic.ReadList(null);
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ManufactureName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ManufactureComponents"].Visible = false;
}
_logger.LogInformation("Загрузка кузнечных изделий");
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки кузнечных изделий");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AddButton_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufacture));
if (service is FormManufacture form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void UpdateButton_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormManufacture));
if (service is FormManufacture form)
{
var tmp = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
form.Id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
_logger.LogInformation("Удаление кузнечного изделия");
try
{
if (!_logic.Delete(new ManufactureBindingModel { Id = id }))
{
throw new Exception("Ошибка при удалении. Дополнительная информация в логах.");
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка удаления кузнечного изделия");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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,120 @@
namespace BlacksmithWorkshop
{
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()
{
ManufactureComboBox = new ComboBox();
ManufactureLabel = new Label();
CountLabel = new Label();
CountTextBox = new TextBox();
ButtonSave = new Button();
ButtonCancel = new Button();
SuspendLayout();
//
// ManufactureComboBox
//
ManufactureComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
ManufactureComboBox.FormattingEnabled = true;
ManufactureComboBox.Location = new Point(99, 12);
ManufactureComboBox.Name = "ManufactureComboBox";
ManufactureComboBox.Size = new Size(121, 23);
ManufactureComboBox.TabIndex = 0;
//
// ManufactureLabel
//
ManufactureLabel.AutoSize = true;
ManufactureLabel.Location = new Point(12, 20);
ManufactureLabel.Name = "ManufactureLabel";
ManufactureLabel.Size = new Size(53, 15);
ManufactureLabel.TabIndex = 1;
ManufactureLabel.Text = "Изделие";
//
// CountLabel
//
CountLabel.AutoSize = true;
CountLabel.Location = new Point(21, 49);
CountLabel.Name = "CountLabel";
CountLabel.Size = new Size(72, 15);
CountLabel.TabIndex = 2;
CountLabel.Text = "Количество";
//
// CountTextBox
//
CountTextBox.Location = new Point(99, 41);
CountTextBox.Name = "CountTextBox";
CountTextBox.Size = new Size(121, 23);
CountTextBox.TabIndex = 3;
//
// ButtonSave
//
ButtonSave.Location = new Point(64, 73);
ButtonSave.Name = "ButtonSave";
ButtonSave.Size = new Size(75, 23);
ButtonSave.TabIndex = 4;
ButtonSave.Text = "Сохранить";
ButtonSave.UseVisualStyleBackColor = true;
ButtonSave.Click += ButtonSave_Click;
//
// ButtonCancel
//
ButtonCancel.Location = new Point(145, 73);
ButtonCancel.Name = "ButtonCancel";
ButtonCancel.Size = new Size(75, 23);
ButtonCancel.TabIndex = 5;
ButtonCancel.Text = "Отмена";
ButtonCancel.UseVisualStyleBackColor = true;
ButtonCancel.Click += ButtonCancel_Click;
//
// FormSell
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(224, 108);
Controls.Add(ButtonCancel);
Controls.Add(ButtonSave);
Controls.Add(CountTextBox);
Controls.Add(CountLabel);
Controls.Add(ManufactureLabel);
Controls.Add(ManufactureComboBox);
Name = "FormSell";
StartPosition = FormStartPosition.CenterParent;
Text = "Форма продажи";
ResumeLayout(false);
PerformLayout();
}
#endregion
private ComboBox ManufactureComboBox;
private Label ManufactureLabel;
private Label CountLabel;
private TextBox CountTextBox;
private Button ButtonSave;
private Button ButtonCancel;
}
}

View File

@ -0,0 +1,113 @@
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
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 BlacksmithWorkshop
{
public partial class FormSell : Form
{
private readonly List<ManufactureViewModel>? _manufactureList;
IShopLogic _shopLogic;
IManufactureLogic _manufactureLogic;
public FormSell(IManufactureLogic manufactureLogic, IShopLogic shopLogic)
{
InitializeComponent();
_shopLogic = shopLogic;
_manufactureLogic = manufactureLogic;
_manufactureList = manufactureLogic.ReadList(null);
if (_manufactureList != null)
{
ManufactureComboBox.DisplayMember = "ManufactureName";
ManufactureComboBox.ValueMember = "Id";
ManufactureComboBox.DataSource = _manufactureList;
ManufactureComboBox.SelectedItem = null;
}
}
public int ManufactureId
{
get
{
return Convert.ToInt32(ManufactureComboBox.SelectedValue);
}
set
{
ManufactureComboBox.SelectedValue = value;
}
}
public IManufactureModel? ManufactureModel
{
get
{
if (_manufactureList == null)
{
return null;
}
foreach (var elem in _manufactureList)
{
if (elem.Id == ManufactureId)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(CountTextBox.Text); }
set
{ CountTextBox.Text = value.ToString(); }
}
private void ButtonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(CountTextBox.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (ManufactureComboBox.SelectedValue == null)
{
MessageBox.Show("Выберите кузнечное изделие", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
int count = Convert.ToInt32(CountTextBox.Text);
var manufacture = _manufactureLogic.ReadElement(new() { Id = Convert.ToInt32(ManufactureComboBox.SelectedValue) });
if (manufacture == null)
{
throw new ApplicationException("Ошибка при продаже. Ошибка получения данных об элементе.");
}
if (!_shopLogic.SellManufactures(manufacture, count))
{
throw new ApplicationException("Ошибка при продаже. Недостаточно изделий данного типа в магазинах.");
}
MessageBox.Show("Продажа прошла успешно");
DialogResult = DialogResult.OK;
Close();
}
catch (Exception)
{
MessageBox.Show("Ошибка при продаже.");
return;
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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 BlacksmithWorkshop
{
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()
{
dataGridView = new DataGridView();
ColumnId = new DataGridViewTextBoxColumn();
ColumnName = new DataGridViewTextBoxColumn();
ColumnPrice = new DataGridViewTextBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
dateTimePicker = new DateTimePicker();
labelName = new Label();
labelAddress = new Label();
labelDate = new Label();
textBoxName = new TextBox();
textBoxAddress = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
CapacityUpDown = new NumericUpDown();
CapacityLabel = new Label();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
((System.ComponentModel.ISupportInitialize)CapacityUpDown).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnId, ColumnName, ColumnPrice, ColumnCount });
dataGridView.Location = new Point(12, 128);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(553, 254);
dataGridView.TabIndex = 0;
//
// ColumnId
//
ColumnId.HeaderText = "";
ColumnId.Name = "ColumnId";
ColumnId.Visible = false;
//
// ColumnName
//
ColumnName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
ColumnName.HeaderText = "Изделие";
ColumnName.Name = "ColumnName";
//
// ColumnPrice
//
ColumnPrice.HeaderText = "Цена";
ColumnPrice.Name = "ColumnPrice";
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.Name = "ColumnCount";
//
// dateTimePicker
//
dateTimePicker.Location = new Point(150, 63);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(166, 23);
dateTimePicker.TabIndex = 1;
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(12, 9);
labelName.Name = "labelName";
labelName.Size = new Size(62, 15);
labelName.TabIndex = 2;
labelName.Text = "Название:";
//
// labelAddress
//
labelAddress.AutoSize = true;
labelAddress.Location = new Point(12, 38);
labelAddress.Name = "labelAddress";
labelAddress.Size = new Size(43, 15);
labelAddress.TabIndex = 3;
labelAddress.Text = "Адрес:";
//
// labelDate
//
labelDate.AutoSize = true;
labelDate.Location = new Point(12, 69);
labelDate.Name = "labelDate";
labelDate.Size = new Size(90, 15);
labelDate.TabIndex = 4;
labelDate.Text = "Дата открытия:";
//
// textBoxName
//
textBoxName.Location = new Point(150, 6);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(166, 23);
textBoxName.TabIndex = 5;
//
// textBoxAddress
//
textBoxAddress.Location = new Point(150, 35);
textBoxAddress.Name = "textBoxAddress";
textBoxAddress.Size = new Size(166, 23);
textBoxAddress.TabIndex = 6;
//
// buttonSave
//
buttonSave.Location = new Point(12, 401);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(123, 25);
buttonSave.TabIndex = 7;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += SaveButton_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(150, 401);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(123, 25);
buttonCancel.TabIndex = 8;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += CancelButton_Click;
//
// CapacityUpDown
//
CapacityUpDown.Location = new Point(150, 92);
CapacityUpDown.Maximum = new decimal(new int[] { 10000, 0, 0, 0 });
CapacityUpDown.Name = "CapacityUpDown";
CapacityUpDown.Size = new Size(166, 23);
CapacityUpDown.TabIndex = 9;
//
// CapacityLabel
//
CapacityLabel.AutoSize = true;
CapacityLabel.Location = new Point(12, 94);
CapacityLabel.Name = "CapacityLabel";
CapacityLabel.Size = new Size(80, 15);
CapacityLabel.TabIndex = 10;
CapacityLabel.Text = "Вместимость";
//
// FormShop
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(585, 450);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxAddress);
Controls.Add(textBoxName);
Controls.Add(labelDate);
Controls.Add(labelAddress);
Controls.Add(labelName);
Controls.Add(dateTimePicker);
Controls.Add(dataGridView);
Controls.Add(CapacityLabel);
Controls.Add(CapacityUpDown);
Name = "FormShop";
StartPosition = FormStartPosition.CenterParent;
Text = "Магазин";
Load += FormShop_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
((System.ComponentModel.ISupportInitialize)CapacityUpDown).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private DataGridView dataGridView;
private DateTimePicker dateTimePicker;
private Label labelName;
private Label labelAddress;
private Label labelDate;
private TextBox textBoxName;
private TextBox textBoxAddress;
private DataGridViewTextBoxColumn ColumnId;
private DataGridViewTextBoxColumn ColumnName;
private DataGridViewTextBoxColumn ColumnPrice;
private DataGridViewTextBoxColumn ColumnCount;
private Button buttonSave;
private Button buttonCancel;
private NumericUpDown CapacityUpDown;
private Label CapacityLabel;
}
}

View File

@ -0,0 +1,123 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic.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 BlacksmithWorkshop
{
public partial class FormShop : Form
{
private readonly ILogger _logger;
private readonly IShopLogic _logic;
public int? _id;
private Dictionary<int, (IManufactureModel, int)> _manufactures;
public FormShop(ILogger<FormShop> logger, IShopLogic logic)
{
InitializeComponent();
_logger = logger;
_logic = logic;
_manufactures = new();
}
private void FormShop_Load(object sender, EventArgs e)
{
if (_id.HasValue)
{
_logger.LogInformation("Загрузка магазина");
try
{
var shop = _logic.ReadElement(new ShopSearchModel { Id = _id });
if (shop != null)
{
textBoxName.Text = shop.ShopName;
textBoxAddress.Text = shop.Address;
dateTimePicker.Text = shop.OpeningDate.ToString();
_manufactures = shop.ShopManufactures ?? new Dictionary<int, (IManufactureModel, int)>();
CapacityUpDown.Value = shop.MaxCapacity;
}
LoadData();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
private void LoadData()
{
_logger.LogInformation("Загрузка товаров магазина");
try
{
if (_manufactures != null)
{
foreach (var manufactures in _manufactures)
{
dataGridView.Rows.Add(new object[] { manufactures.Key, manufactures.Value.Item1.ManufactureName,
manufactures.Value.Item1.Price, manufactures.Value.Item2 });
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка загрузки изделий магазина");
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void SaveButton_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,
OpeningDate = dateTimePicker.Value.Date,
MaxCapacity = Convert.ToInt32(CapacityUpDown.Value)
};
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,132 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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="ColumnId.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnName.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnPrice.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ColumnCount.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,114 @@
namespace BlacksmithWorkshop
{
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()
{
dataGridView = new DataGridView();
buttonAdd = new Button();
buttonUpdate = new Button();
buttonDelete = new Button();
buttonRefresh = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(0, 0);
dataGridView.Name = "dataGridView";
dataGridView.RowTemplate.Height = 25;
dataGridView.Size = new Size(567, 450);
dataGridView.TabIndex = 0;
//
// buttonAdd
//
buttonAdd.Location = new Point(617, 22);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(152, 33);
buttonAdd.TabIndex = 1;
buttonAdd.Text = "Создать";
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += AddButton_Click;
//
// buttonUpdate
//
buttonUpdate.Location = new Point(617, 61);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(152, 33);
buttonUpdate.TabIndex = 2;
buttonUpdate.Text = "Изменить";
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += UpdateButton_Click;
//
// buttonDelete
//
buttonDelete.Location = new Point(617, 100);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(152, 33);
buttonDelete.TabIndex = 3;
buttonDelete.Text = "Удалить";
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += DeleteButton_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(617, 139);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(152, 33);
buttonRefresh.TabIndex = 4;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += RefreshButton_Click;
//
// FormShops
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(buttonRefresh);
Controls.Add(buttonDelete);
Controls.Add(buttonUpdate);
Controls.Add(buttonAdd);
Controls.Add(dataGridView);
Name = "FormShops";
StartPosition = FormStartPosition.CenterParent;
Text = "Магазины";
Load += FormShops_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private Button buttonAdd;
private Button buttonUpdate;
private Button buttonDelete;
private Button buttonRefresh;
}
}

View File

@ -0,0 +1,110 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.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 BlacksmithWorkshop
{
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)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["ShopName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["Address"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["OpeningDate"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView.Columns["ShopManufactures"].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 AddButton_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 UpdateButton_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
var service = Program.ServiceProvider?.GetService(typeof(FormShop));
if (service is FormShop form)
{
form._id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
}
private void RefreshButton_Click(object sender, EventArgs e)
{
LoadData();
}
private void DeleteButton_Click(object sender, EventArgs e)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.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,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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,108 @@
namespace BlacksmithWorkshop
{
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()
{
ShopComboBox = new ComboBox();
ManufactureComboBox = new ComboBox();
CountTextBox = new TextBox();
buttonSave = new Button();
buttonCansel = new Button();
SuspendLayout();
//
// ShopComboBox
//
ShopComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
ShopComboBox.FormattingEnabled = true;
ShopComboBox.Location = new Point(12, 12);
ShopComboBox.Name = "ShopComboBox";
ShopComboBox.Size = new Size(224, 23);
ShopComboBox.TabIndex = 0;
//
// ManufactureComboBox
//
ManufactureComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
ManufactureComboBox.FormattingEnabled = true;
ManufactureComboBox.Location = new Point(242, 12);
ManufactureComboBox.Name = "ManufactureComboBox";
ManufactureComboBox.Size = new Size(224, 23);
ManufactureComboBox.TabIndex = 1;
//
// CountTextBox
//
CountTextBox.Location = new Point(472, 12);
CountTextBox.Name = "CountTextBox";
CountTextBox.Size = new Size(224, 23);
CountTextBox.TabIndex = 2;
//
// buttonSave
//
buttonSave.Location = new Point(162, 47);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(157, 28);
buttonSave.TabIndex = 3;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += SaveButton_Click;
//
// buttonCansel
//
buttonCansel.Location = new Point(394, 47);
buttonCansel.Name = "buttonCansel";
buttonCansel.Size = new Size(157, 28);
buttonCansel.TabIndex = 4;
buttonCansel.Text = "Отмена";
buttonCansel.UseVisualStyleBackColor = true;
buttonCansel.Click += CancelButton_Click;
//
// FormSupply
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(707, 87);
Controls.Add(buttonCansel);
Controls.Add(buttonSave);
Controls.Add(CountTextBox);
Controls.Add(ManufactureComboBox);
Controls.Add(ShopComboBox);
Name = "FormSupply";
StartPosition = FormStartPosition.CenterParent;
Text = "Пополнение магазина";
ResumeLayout(false);
PerformLayout();
}
#endregion
private ComboBox ShopComboBox;
private ComboBox ManufactureComboBox;
private TextBox CountTextBox;
private Button buttonSave;
private Button buttonCansel;
}
}

View File

@ -0,0 +1,139 @@
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
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 BlacksmithWorkshop
{
public partial class FormSupply : Form
{
private readonly List<ManufactureViewModel>? _manufactureList;
private readonly List<ShopViewModel>? _shopsList;
IShopLogic _shopLogic;
IManufactureLogic _manufactureLogic;
public int ShopId
{
get
{
return Convert.ToInt32(ShopComboBox.SelectedValue);
}
set
{
ShopComboBox.SelectedValue = value;
}
}
public int ManufactureId
{
get
{
return Convert.ToInt32(ManufactureComboBox.SelectedValue);
}
set
{
ManufactureComboBox.SelectedValue = value;
}
}
public IManufactureModel? ManufactureModel
{
get
{
if (_manufactureList == null)
{
return null;
}
foreach (var elem in _manufactureList)
{
if (elem.Id == ManufactureId)
{
return elem;
}
}
return null;
}
}
public int Count
{
get { return Convert.ToInt32(CountTextBox.Text); }
set { CountTextBox.Text = value.ToString(); }
}
public FormSupply(IManufactureLogic ManufactureLogic, IShopLogic shopLogic)
{
InitializeComponent();
_shopLogic = shopLogic;
_manufactureLogic = ManufactureLogic;
_manufactureList = ManufactureLogic.ReadList(null);
_shopsList = shopLogic.ReadList(null);
if (_manufactureList != null)
{
ManufactureComboBox.DisplayMember = "ManufactureName";
ManufactureComboBox.ValueMember = "Id";
ManufactureComboBox.DataSource = _manufactureList;
ManufactureComboBox.SelectedItem = null;
}
if (_shopsList != null)
{
ShopComboBox.DisplayMember = "ShopName";
ShopComboBox.ValueMember = "Id";
ShopComboBox.DataSource = _shopsList;
ShopComboBox.SelectedItem = null;
}
}
private void SaveButton_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(CountTextBox.Text))
{
MessageBox.Show("Заполните поле Количество", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (ManufactureComboBox.SelectedValue == null)
{
MessageBox.Show("Выберите кузнечное изделие", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (ShopComboBox.SelectedValue == null)
{
MessageBox.Show("Выберите магазин", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
int count = Convert.ToInt32(CountTextBox.Text);
bool res = _shopLogic.ReplenishManufactures(
new ShopSearchModel() { Id = Convert.ToInt32(ShopComboBox.SelectedValue) },
_manufactureLogic.ReadElement(new() { Id = Convert.ToInt32(ManufactureComboBox.SelectedValue) }),
count
);
if (!res)
{
throw new Exception("Ошибка при пополнении. Дополнительная информация в логах");
}
MessageBox.Show("Пополнение прошло успешно");
DialogResult = DialogResult.OK;
Close();
}
catch (Exception)
{
MessageBox.Show("Ошибка пополнения");
return;
}
}
private void CancelButton_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<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,58 @@
using BlacksmithWorkshopBusinessLogic.BusinessLogics;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;
namespace BlacksmithWorkshop
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// 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>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
services.AddTransient<IComponentStorage, ComponentStorage>();
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IManufactureStorage, ManufactureStorage>();
services.AddTransient<IComponentLogic, ComponentLogic>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IManufactureLogic, ManufactureLogic>();
services.AddTransient<IShopStorage, ShopStorage>();
services.AddTransient<IShopLogic, ShopLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormComponent>();
services.AddTransient<FormComponents>();
services.AddTransient<FormCreateOrder>();
services.AddTransient<FormManufacture>();
services.AddTransient<FormManufactures>();
services.AddTransient<FormManufactureComponent>();
services.AddTransient<FormShop>();
services.AddTransient<FormShops>();
services.AddTransient<FormSupply>();
services.AddTransient<FormSell>();
}
}
}

View File

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,112 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogics
{
public class ComponentLogic : IComponentLogic
{
private readonly ILogger _logger;
private readonly IComponentStorage _componentStorage;
public ComponentLogic(ILogger<ComponentLogic> logger, IComponentStorage
componentStorage)
{
_logger = logger;
_componentStorage = componentStorage;
}
public List<ComponentViewModel>? ReadList(ComponentSearchModel? model)
{
_logger.LogInformation("ReadList. ComponentName:{ComponentName}.Id:{ Id}", model?.ComponentName, model?.Id);
var list = model == null ? _componentStorage.GetFullList() :
_componentStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ComponentViewModel? ReadElement(ComponentSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ComponentName:{ComponentName}. Id:{ Id}", model.ComponentName, model.Id);
var element = _componentStorage.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(ComponentBindingModel model)
{
CheckModel(model);
if (_componentStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ComponentBindingModel model)
{
CheckModel(model);
if (_componentStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ComponentBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_componentStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ComponentBindingModel model, bool withParams =
true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ComponentName))
{
throw new ArgumentNullException("Нет названия компонента",
nameof(model.ComponentName));
}
if (model.Cost <= 0)
{
throw new ArgumentNullException("Цена компонента должна быть больше 0", nameof(model.Cost));
}
_logger.LogInformation("Component. ComponentName:{ComponentName}. Cost:{ Cost}. Id: { Id} ", model.ComponentName, model.Cost, model.Id);
var element = _componentStorage.GetElement(new ComponentSearchModel
{
ComponentName = model.ComponentName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компонент с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,114 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using Microsoft.Extensions.Logging;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogics
{
public class ManufactureLogic : IManufactureLogic
{
private readonly ILogger _logger;
private readonly IManufactureStorage _ManufactureStorage;
public ManufactureLogic(ILogger<ManufactureLogic> logger, IManufactureStorage ManufactureStorage)
{
_logger = logger;
_ManufactureStorage = ManufactureStorage;
}
public List<ManufactureViewModel>? ReadList(ManufactureSearchModel? model)
{
_logger.LogInformation("ReadList. ManufactureName:{ManufactureName}. Id:{ Id}", model?.ManufactureName, model?.Id);
var list = model == null ? _ManufactureStorage.GetFullList() :
_ManufactureStorage.GetFilteredList(model);
if (list == null)
{
_logger.LogWarning("ReadList return null list");
return null;
}
_logger.LogInformation("ReadList. Count:{Count}", list.Count);
return list;
}
public ManufactureViewModel? ReadElement(ManufactureSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
_logger.LogInformation("ReadElement. ManufactureName:{ManufactureName}.Id:{ Id}", model.ManufactureName, model.Id);
var element = _ManufactureStorage.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(ManufactureBindingModel model)
{
CheckModel(model);
if (_ManufactureStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
public bool Update(ManufactureBindingModel model)
{
CheckModel(model);
if (_ManufactureStorage.Update(model) == null)
{
_logger.LogWarning("Update operation failed");
return false;
}
return true;
}
public bool Delete(ManufactureBindingModel model)
{
CheckModel(model, false);
_logger.LogInformation("Delete. Id:{Id}", model.Id);
if (_ManufactureStorage.Delete(model) == null)
{
_logger.LogWarning("Delete operation failed");
return false;
}
return true;
}
private void CheckModel(ManufactureBindingModel model, bool withParams =
true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.ManufactureName))
{
throw new ArgumentNullException("Нет названия кузнечного изделия",
nameof(model.ManufactureName));
}
if (model.Price <= 0)
{
throw new ArgumentNullException("Цена кузнечных изделий должна быть больше 0", nameof(model.Price));
}
_logger.LogInformation("Manufacture. Manufacture:{Manufacture}. Price:{ Price }. Id: { Id}", model.ManufactureName, model.Price, model.Id);
var element = _ManufactureStorage.GetElement(new ManufactureSearchModel
{
ManufactureName = model.ManufactureName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Компонент с таким названием уже есть");
}
}
}
}

View File

@ -0,0 +1,188 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Enums;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopBusinessLogic.BusinessLogics
{
public class OrderLogic : IOrderLogic
{
private readonly ILogger _logger;
private readonly IOrderStorage _orderStorage;
private readonly IShopLogic _shopLogic;
private readonly IManufactureStorage _manufactureStorage;
private readonly IShopStorage _shopStorage;
public OrderLogic(ILogger<OrderLogic> logger, IOrderStorage orderStorage,
IManufactureStorage manufactureStorage, IShopLogic shopLogic, IShopStorage shopStorage)
{
_logger = logger;
_orderStorage = orderStorage;
_manufactureStorage = manufactureStorage;
_shopLogic = shopLogic;
_shopStorage = shopStorage;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
_logger.LogInformation("ReadList. 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;
}
public bool CreateOrder(OrderBindingModel model)
{
CheckModel(model);
if (model.Status != OrderStatus.Неизвестен) return false;
model.Status = OrderStatus.Принят;
if (_orderStorage.Insert(model) == null)
{
_logger.LogWarning("Insert operation failed");
return false;
}
return true;
}
private bool ChangeStatus(OrderBindingModel model, OrderStatus status)
{
CheckModel(model);
var element = _orderStorage.GetElement(new OrderSearchModel { Id = model.Id });
if (element == null)
{
_logger.LogWarning("Read operation failed");
return false;
}
if (element.Status != status - 1)
{
_logger.LogWarning("Status change operation failed");
throw new InvalidOperationException("Текущий статус заказа не может быть переведен в выбранный");
}
if (element.Status == OrderStatus.Готов)
{
var manufacture = _manufactureStorage.GetElement(new ManufactureSearchModel() { Id = model.ManufactureId });
if (manufacture == null)
{
_logger.LogWarning("Status update to " + status.ToString() + " operation failed. Document not found.");
return false;
}
if (CheckSupply(manufacture, model.Count) == false)
{
_logger.LogWarning("Status update to " + status.ToString() + " operation failed. Shop supply error.");
return false;
}
}
model.Status = status;
if (model.Status == OrderStatus.Выдан)
model.DateImplement = DateTime.Now;
_orderStorage.Update(model);
return true;
}
public bool TakeOrderInWork(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выполняется);
}
public bool FinishOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Готов);
}
public bool DeliveryOrder(OrderBindingModel model)
{
return ChangeStatus(model, OrderStatus.Выдан);
}
private void CheckModel(OrderBindingModel model, bool withParams =
true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (model.Sum <= 0)
{
throw new ArgumentNullException("Цена заказа должна быть больше 0", nameof(model.Sum));
}
if (model.Count <= 0)
{
throw new ArgumentNullException("Количество элементов в заказе должно быть больше 0", nameof(model.Count));
}
_logger.LogInformation("Order. Sum:{ Cost}. Id: { Id}", model.Sum, model.Id);
}
private bool CheckSupply(IManufactureModel manufacture, int count)
{
if (count <= 0)
{
_logger.LogWarning("Check then supply operation error. Manufacture count < 0.");
return false;
}
int sumCapacity = 0;
int sumCount = 0;
sumCapacity = _shopStorage.GetFullList().Select(x => x.MaxCapacity).Sum();
sumCount = _shopStorage.GetFullList().Select(x => x.ShopManufactures.Select(y => y.Value.Item2).Sum()).Sum();
int freeSpace = sumCapacity - sumCount;
if (freeSpace - count < 0)
{
_logger.LogWarning("Check then supply operation error. There's no place for new Manufacture in shops.");
return false;
}
foreach (var shop in _shopStorage.GetFullList())
{
freeSpace = shop.MaxCapacity;
foreach (var doc in shop.ShopManufactures)
{
freeSpace -= doc.Value.Item2;
}
if (freeSpace == 0)
{
continue;
}
if (freeSpace - count >= 0)
{
if (_shopLogic.ReplenishManufactures(new() { Id = shop.Id }, manufacture, count))
count = 0;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (freeSpace - count < 0)
{
if (_shopLogic.ReplenishManufactures(new() { Id = shop.Id }, manufacture, freeSpace))
count -= freeSpace;
else
{
_logger.LogWarning("Supply error");
return false;
}
}
if (count <= 0)
{
return true;
}
}
return false;
}
}
}

View File

@ -0,0 +1,168 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.BusinessLogicsContracts;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.Extensions.Logging;
namespace BlacksmithWorkshopBusinessLogic.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 ReplenishManufactures(ShopSearchModel model, IManufactureModel manufacture, int count)
{
_logger.LogInformation("Try to replenish manufactures. ShopName:{ShopName}. Id:{Id}", model.ShopName, model.Id);
if (model == null)
{
_logger.LogWarning("Read operation failed");
throw new ArgumentNullException(nameof(model));
}
ShopViewModel? curModel = ReadElement(model);
if (curModel == null)
{
_logger.LogWarning("Read operation failed");
throw new ArgumentNullException(nameof(curModel));
}
if (manufacture == null)
{
_logger.LogWarning("Read operation failed");
throw new ArgumentNullException(nameof(manufacture));
}
if (count <= 0)
{
_logger.LogWarning("Read operation failed");
throw new ArgumentException("Количество должно быть положительным");
}
int countItems = curModel.ShopManufactures.Select(x => x.Value.Item2).Sum();
if (curModel.MaxCapacity - countItems >= count)
{
if (curModel.ShopManufactures.TryGetValue(manufacture.Id, out var sameDocument))
{
curModel.ShopManufactures[manufacture.Id] = (manufacture, sameDocument.Item2 + count);
_logger.LogInformation("Same manufacture found by supply. Added {0} of {1} in {2} shop", count, manufacture.ManufactureName, curModel.ShopName);
}
else
{
curModel.ShopManufactures[manufacture.Id] = (manufacture, count);
_logger.LogInformation("New manufacture added by supply. Added {0} of {1} in {2} shop", count, manufacture.ManufactureName, curModel.ShopName);
}
_shopStorage.Update(new()
{
Id = curModel.Id,
ShopName = curModel.ShopName,
Address = curModel.Address,
OpeningDate = curModel.OpeningDate,
ShopManufactures = curModel.ShopManufactures,
MaxCapacity = curModel.MaxCapacity
});
}
else
{
_logger.LogWarning("Required shop is overflowed");
return false;
}
return true;
}
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));
}
if (string.IsNullOrEmpty(model.Address))
{
throw new ArgumentNullException("Нет адреса магазина", nameof(model.Address));
}
_logger.LogInformation("Shop. ShopName:{ShopName}.Address:{Address}. DateOpen:{DateOpen}. Id: { Id}",
model.ShopName, model.Address, model.OpeningDate, model.Id);
var element = _shopStorage.GetElement(new ShopSearchModel
{
ShopName = model.ShopName
});
if (element != null && element.Id != model.Id)
{
throw new InvalidOperationException("Магазин с таким названием уже есть");
}
}
public bool SellManufactures(IManufactureModel manufacture, int count)
{
return _shopStorage.SellManufactures(manufacture, count);
}
}
}

View File

@ -0,0 +1,12 @@
using BlacksmithWorkshopDataModels.Models;
namespace BlacksmithWorkshopContracts.BindingModels
{
public class ComponentBindingModel : IComponentModel
{
public int Id { get; set; }
public string ComponentName { get; set; } = string.Empty;
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,21 @@
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BindingModels
{
public class ManufactureBindingModel : IManufactureModel
{
public int Id { get; set; }
public string ManufactureName { get; set; } = string.Empty;
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> ManufactureComponents
{
get;
set;
} = new();
}
}

View File

@ -0,0 +1,27 @@
using BlacksmithWorkshopDataModels.Enums;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BindingModels
{
public class OrderBindingModel : IOrderModel
{
public int Id { get; set; }
public int ManufactureId { get; set; }
public int Count { get; set; }
public double Sum { get; set; }
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
public DateTime DateCreate { get; set; } = DateTime.Now;
public DateTime? DateImplement { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BlacksmithWorkshopDataModels.Models;
namespace BlacksmithWorkshopContracts.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 OpeningDate { get; set; }
public int MaxCapacity { get; set; }
public Dictionary<int, (IManufactureModel, int)> ShopManufactures { get; set; } = new();
}
}

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\BlacksmithWorkshopDataModels\BlacksmithWorkshopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,20 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BusinessLogicsContracts
{
public interface IComponentLogic
{
List<ComponentViewModel>? ReadList(ComponentSearchModel? model);
ComponentViewModel? ReadElement(ComponentSearchModel model);
bool Create(ComponentBindingModel model);
bool Update(ComponentBindingModel model);
bool Delete(ComponentBindingModel model);
}
}

View File

@ -0,0 +1,20 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BusinessLogicsContracts
{
public interface IManufactureLogic
{
List<ManufactureViewModel>? ReadList(ManufactureSearchModel? model);
ManufactureViewModel? ReadElement(ManufactureSearchModel model);
bool Create(ManufactureBindingModel model);
bool Update(ManufactureBindingModel model);
bool Delete(ManufactureBindingModel model);
}
}

View File

@ -0,0 +1,20 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.BusinessLogicsContracts
{
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
bool CreateOrder(OrderBindingModel model);
bool TakeOrderInWork(OrderBindingModel model);
bool FinishOrder(OrderBindingModel model);
bool DeliveryOrder(OrderBindingModel model);
}
}

View File

@ -0,0 +1,23 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.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 ReplenishManufactures(ShopSearchModel shop, IManufactureModel manufacture, int count);
bool SellManufactures(IManufactureModel manufacture, 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 BlacksmithWorkshopContracts.SearchModels
{
public class ComponentSearchModel
{
public int? Id { get; set; }
public string? ComponentName { get; set; }
}
}

View File

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

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.SearchModels
{
public class OrderSearchModel
{
public int? Id { get; set; }
}
}

View File

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

View File

@ -0,0 +1,21 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.StoragesContracts
{
public interface IComponentStorage
{
List<ComponentViewModel> GetFullList();
List<ComponentViewModel> GetFilteredList(ComponentSearchModel model);
ComponentViewModel? GetElement(ComponentSearchModel model);
ComponentViewModel? Insert(ComponentBindingModel model);
ComponentViewModel? Update(ComponentBindingModel model);
ComponentViewModel? Delete(ComponentBindingModel model);
}
}

View File

@ -0,0 +1,21 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.StoragesContracts
{
public interface IManufactureStorage
{
List<ManufactureViewModel> GetFullList();
List<ManufactureViewModel> GetFilteredList(ManufactureSearchModel model);
ManufactureViewModel? GetElement(ManufactureSearchModel model);
ManufactureViewModel? Insert(ManufactureBindingModel model);
ManufactureViewModel? Update(ManufactureBindingModel model);
ManufactureViewModel? Delete(ManufactureBindingModel model);
}
}

View File

@ -0,0 +1,21 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.StoragesContracts
{
public interface IOrderStorage
{
List<OrderViewModel> GetFullList();
List<OrderViewModel> GetFilteredList(OrderSearchModel model);
OrderViewModel? GetElement(OrderSearchModel model);
OrderViewModel? Insert(OrderBindingModel model);
OrderViewModel? Update(OrderBindingModel model);
OrderViewModel? Delete(OrderBindingModel model);
}
}

View File

@ -0,0 +1,23 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.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);
public bool SellManufactures(IManufactureModel model, int count);
}
}

View File

@ -0,0 +1,19 @@
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.ViewModels
{
public class ComponentViewModel : IComponentModel
{
public int Id { get; set; }
[DisplayName("Название компонента")]
public string ComponentName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Cost { get; set; }
}
}

View File

@ -0,0 +1,24 @@
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.ViewModels
{
public class ManufactureViewModel : IManufactureModel
{
public int Id { get; set; }
[DisplayName("Название кузнечного изделия")]
public string ManufactureName { get; set; } = string.Empty;
[DisplayName("Цена")]
public double Price { get; set; }
public Dictionary<int, (IComponentModel, int)> ManufactureComponents
{
get;
set;
} = new();
}
}

View File

@ -0,0 +1,30 @@
using BlacksmithWorkshopDataModels.Enums;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
[DisplayName("Номер")]
public int Id { get; set; }
public int ManufactureId { get; set; }
[DisplayName("Кузнечное изделие")]
public string ManufactureName { get; set; } = string.Empty;
[DisplayName("Количество")]
public int Count { get; set; }
[DisplayName("Сумма")]
public double Sum { get; set; }
[DisplayName("Статус")]
public OrderStatus Status { get; set; } = OrderStatus.Неизвестен;
[DisplayName("Дата создания")]
public DateTime DateCreate { get; set; } = DateTime.Now;
[DisplayName("Дата выполнения")]
public DateTime? DateImplement { get; set; }
}
}

View File

@ -0,0 +1,24 @@
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopContracts.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 OpeningDate { get; set; }
[DisplayName("Вместимость")]
public int MaxCapacity { get; set; }
public Dictionary<int, (IManufactureModel, int)> ShopManufactures { get; set; } = new();
}
}

View File

@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@ -0,0 +1,15 @@
namespace BlacksmithWorkshopDataModels.Enums
{
public enum OrderStatus
{
Неизвестен = -1,
Принят = 0,
Выполняется = 1,
Готов = 2,
Выдан = 3
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDataModels
{
public interface IId
{
int Id { get; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDataModels.Models
{
public interface IComponentModel : IId
{
string ComponentName { get; }
double Cost { get; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDataModels.Models
{
public interface IManufactureModel : IId
{
string ManufactureName { get; }
double Price { get; }
Dictionary<int, (IComponentModel, int)> ManufactureComponents { get; }
}
}

View File

@ -0,0 +1,19 @@
using BlacksmithWorkshopDataModels.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDataModels.Models
{
public interface IOrderModel : IId
{
int ManufactureId { get; }
int Count { get; }
double Sum { get; }
OrderStatus Status { get; }
DateTime DateCreate { get; }
DateTime? DateImplement { get; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDataModels.Models
{
public interface IShopModel : IId
{
string ShopName { get; }
string Address { get; }
DateTime OpeningDate { get; }
int MaxCapacity { get; }
Dictionary<int, (IManufactureModel, int)> ShopManufactures { get; }
}
}

View File

@ -0,0 +1,28 @@
using BlacksmithWorkshopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement
{
public class BlacksmithWorkshopDataBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=BlacksmithWorkshopDataBaseHard;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Component> Components { set; get; }
public virtual DbSet<Manufacture> Manufactures { set; get; }
public virtual DbSet<ManufactureComponent> ManufactureComponents { set; get; }
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<Shop> Shops { set; get; }
public virtual DbSet<ShopManufacture> ShopManufactures { set; get; }
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.16" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.16">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopDataModels\BlacksmithWorkshopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,89 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDatabaseImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
public List<ComponentViewModel> GetFullList()
{
using var context = new BlacksmithWorkshopDataBase();
return context.Components
.Select(x => x.GetViewModel)
.ToList();
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel
model)
{
if (string.IsNullOrEmpty(model.ComponentName))
{
return new();
}
using var context = new BlacksmithWorkshopDataBase();
return context.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)
{
return null;
}
using var context = new BlacksmithWorkshopDataBase();
return context.Components
.FirstOrDefault(x =>
(!string.IsNullOrEmpty(model.ComponentName) && x.ComponentName ==
model.ComponentName) ||
(model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
using var context = new BlacksmithWorkshopDataBase();
context.Components.Add(newComponent);
context.SaveChanges();
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var component = context.Components.FirstOrDefault(x => x.Id ==
model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var element = context.Components.FirstOrDefault(rec => rec.Id ==
model.Id);
if (element != null)
{
context.Components.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,109 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Implements
{
public class ManufactureStorage : IManufactureStorage
{
public List<ManufactureViewModel> GetFullList()
{
using var context = new BlacksmithWorkshopDataBase();
return context.Manufactures
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<ManufactureViewModel> GetFilteredList(ManufactureSearchModel model)
{
if (string.IsNullOrEmpty(model.ManufactureName))
{
return new();
}
using var context = new BlacksmithWorkshopDataBase();
return context.Manufactures.Include(x => x.Components)
.ThenInclude(x => x.Component)
.Where(x => x.ManufactureName.Contains(model.ManufactureName))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public ManufactureViewModel? GetElement(ManufactureSearchModel model)
{
if (string.IsNullOrEmpty(model.ManufactureName) &&
!model.Id.HasValue)
{
return null;
}
using var context = new BlacksmithWorkshopDataBase();
return context.Manufactures
.Include(x => x.Components)
.ThenInclude(x => x.Component)
.FirstOrDefault(x => (!string.IsNullOrEmpty(model.ManufactureName) &&
x.ManufactureName == model.ManufactureName) ||
(model.Id.HasValue && x.Id ==
model.Id))
?.GetViewModel;
}
public ManufactureViewModel? Insert(ManufactureBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var newManufacture = Manufacture.Create(context, model);
if (newManufacture == null)
{
return null;
}
context.Manufactures.Add(newManufacture);
context.SaveChanges();
return newManufacture.GetViewModel;
}
public ManufactureViewModel? Update(ManufactureBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
using var transaction = context.Database.BeginTransaction();
try
{
var manufacture = context.Manufactures.FirstOrDefault(rec =>
rec.Id == model.Id);
if (manufacture == null)
{
return null;
}
manufacture.Update(model);
context.SaveChanges();
manufacture.UpdateComponents(context, model);
transaction.Commit();
return manufacture.GetViewModel;
}
catch
{
transaction.Rollback();
throw;
}
}
public ManufactureViewModel? Delete(ManufactureBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var element = context.Manufactures
.Include(x => x.Components)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Manufactures.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,90 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Implements
{
public class OrderStorage : IOrderStorage
{
public List<OrderViewModel> GetFullList()
{
using var context = new BlacksmithWorkshopDataBase();
return context.Orders
.Include(x => x.Manufacture)
.Select(x => x.GetViewModel)
.ToList();
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new BlacksmithWorkshopDataBase();
return context.Orders
.Include(x => x.Manufacture)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new BlacksmithWorkshopDataBase();
return context.Orders
.Include(x => x.Manufacture)
.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
context.Orders.Add(newOrder);
context.SaveChanges();
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var order = context.Orders
.Include(x => x.Manufacture)
.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
return null;
}
order.Update(model);
context.SaveChanges();
return order.GetViewModel;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var element = context.Orders
.Include(x => x.Manufacture)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,148 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDatabaseImplement.Models;
using BlacksmithWorkshopDataModels.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Implements
{
public class ShopStorage : IShopStorage
{
public ShopViewModel? Delete(ShopBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var element = context.Shops.FirstOrDefault(x => x.Id == model.Id);
if (element != null)
{
context.Shops.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
public ShopViewModel? GetElement(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName) && !model.Id.HasValue)
{
return null;
}
using var context = new BlacksmithWorkshopDataBase();
return context.Shops
.Include(x => x.Manufactures)
.ThenInclude(x => x.Manufacture)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public List<ShopViewModel> GetFilteredList(ShopSearchModel model)
{
if (string.IsNullOrEmpty(model.ShopName))
{
return new();
}
using var context = new BlacksmithWorkshopDataBase();
return context.Shops
.Include(x => x.Manufactures)
.ThenInclude(x => x.Manufacture)
.Select(x => x.GetViewModel)
.Where(x => x.ShopName.Contains(model.ShopName ?? string.Empty))
.ToList();
}
public List<ShopViewModel> GetFullList()
{
using var context = new BlacksmithWorkshopDataBase();
return context.Shops
.Include(x => x.Manufactures)
.ThenInclude(x => x.Manufacture)
.Select(x => x.GetViewModel)
.ToList();
}
public ShopViewModel? Insert(ShopBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
try
{
var newShop = Shop.Create(context, model);
if (newShop == null)
{
return null;
}
if (context.Shops.Any(x => x.ShopName == newShop.ShopName))
{
throw new Exception("Не должно быть два магазина с одним названием");
}
context.Shops.Add(newShop);
context.SaveChanges();
return newShop.GetViewModel;
}
catch
{
throw;
}
}
public ShopViewModel? Update(ShopBindingModel model)
{
using var context = new BlacksmithWorkshopDataBase();
var shop = context.Shops.FirstOrDefault(x => x.Id == model.Id);
if (shop == null)
{
return null;
}
try
{
if (context.Shops.Any(x => (x.ShopName == model.ShopName && x.Id != model.Id)))
{
throw new Exception("Не должно быть два магазина с одним названием");
}
shop.Update(model);
shop.UpdateManufactures(context, model);
context.SaveChanges();
return shop.GetViewModel;
}
catch
{
throw;
}
}
public bool SellManufactures(IManufactureModel model, int count)
{
if (model == null)
return false;
using var context = new BlacksmithWorkshopDataBase();
using var transaction = context.Database.BeginTransaction();
List<ShopManufacture> lst = new List<ShopManufacture>();
foreach (var el in context.ShopManufactures.Where(x => x.ManufactureId == model.Id))
{
int dif = count;
if (el.Count < dif)
dif = el.Count;
el.Count -= dif;
count -= dif;
if (el.Count == 0)
{
lst.Add(el);
}
if (count == 0)
break;
}
if (count > 0)
{
transaction.Rollback();
return false;
}
foreach (var el in lst)
{
context.ShopManufactures.Remove(el);
}
context.SaveChanges();
transaction.Commit();
return true;
}
}
}

View File

@ -0,0 +1,250 @@
// <auto-generated />
using System;
using BlacksmithWorkshopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(BlacksmithWorkshopDataBase))]
[Migration("20240325175852_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.16")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ManufactureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ManufactureId");
b.ToTable("ManufactureComponents");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.ToTable("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("MaxCapacity")
.HasColumnType("int");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("ShopId");
b.ToTable("ShopManufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Component", "Component")
.WithMany("ManufactureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Components")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Orders")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("ShopManufactures")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Manufactures")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("Shop");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b =>
{
b.Navigation("ManufactureComponents");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
b.Navigation("ShopManufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Manufactures");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,184 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Components",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ComponentName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Cost = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Components", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Manufactures",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ManufactureName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Manufactures", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Shops",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ShopName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Address = table.Column<string>(type: "nvarchar(max)", nullable: false),
OpeningDate = table.Column<DateTime>(type: "datetime2", nullable: false),
MaxCapacity = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Shops", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ManufactureComponents",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ManufactureId = table.Column<int>(type: "int", nullable: false),
ComponentId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ManufactureComponents", x => x.Id);
table.ForeignKey(
name: "FK_ManufactureComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ManufactureComponents_Manufactures_ManufactureId",
column: x => x.ManufactureId,
principalTable: "Manufactures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
DateCreate = table.Column<DateTime>(type: "datetime2", nullable: false),
DateImplement = table.Column<DateTime>(type: "datetime2", nullable: true),
ManufactureId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Manufactures_ManufactureId",
column: x => x.ManufactureId,
principalTable: "Manufactures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ShopManufactures",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ManufactureId = table.Column<int>(type: "int", nullable: false),
ShopId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ShopManufactures", x => x.Id);
table.ForeignKey(
name: "FK_ShopManufactures_Manufactures_ManufactureId",
column: x => x.ManufactureId,
principalTable: "Manufactures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ShopManufactures_Shops_ShopId",
column: x => x.ShopId,
principalTable: "Shops",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ManufactureComponents_ComponentId",
table: "ManufactureComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_ManufactureComponents_ManufactureId",
table: "ManufactureComponents",
column: "ManufactureId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ManufactureId",
table: "Orders",
column: "ManufactureId");
migrationBuilder.CreateIndex(
name: "IX_ShopManufactures_ManufactureId",
table: "ShopManufactures",
column: "ManufactureId");
migrationBuilder.CreateIndex(
name: "IX_ShopManufactures_ShopId",
table: "ShopManufactures",
column: "ShopId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ManufactureComponents");
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "ShopManufactures");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Manufactures");
migrationBuilder.DropTable(
name: "Shops");
}
}
}

View File

@ -0,0 +1,250 @@
// <auto-generated />
using System;
using BlacksmithWorkshopDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
[DbContext(typeof(BlacksmithWorkshopDataBase))]
[Migration("20240503170222_BlacksmithWorkshopDataBaseModelSnapshot")]
partial class BlacksmithWorkshopDataBaseModelSnapshot
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.16")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ComponentName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Cost")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Components");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("ManufactureName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<double>("Price")
.HasColumnType("float");
b.HasKey("Id");
b.ToTable("Manufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("ComponentId")
.HasColumnType("int");
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ComponentId");
b.HasIndex("ManufactureId");
b.ToTable("ManufactureComponents");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<DateTime>("DateCreate")
.HasColumnType("datetime2");
b.Property<DateTime?>("DateImplement")
.HasColumnType("datetime2");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<double>("Sum")
.HasColumnType("float");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.ToTable("Orders");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("MaxCapacity")
.HasColumnType("int");
b.Property<DateTime>("OpeningDate")
.HasColumnType("datetime2");
b.Property<string>("ShopName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Shops");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Count")
.HasColumnType("int");
b.Property<int>("ManufactureId")
.HasColumnType("int");
b.Property<int>("ShopId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ManufactureId");
b.HasIndex("ShopId");
b.ToTable("ShopManufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ManufactureComponent", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Component", "Component")
.WithMany("ManufactureComponents")
.HasForeignKey("ComponentId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Components")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Component");
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Order", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("Orders")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.ShopManufacture", b =>
{
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", "Manufacture")
.WithMany("ShopManufactures")
.HasForeignKey("ManufactureId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("BlacksmithWorkshopDatabaseImplement.Models.Shop", "Shop")
.WithMany("Manufactures")
.HasForeignKey("ShopId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Manufacture");
b.Navigation("Shop");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Component", b =>
{
b.Navigation("ManufactureComponents");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Manufacture", b =>
{
b.Navigation("Components");
b.Navigation("Orders");
b.Navigation("ShopManufactures");
});
modelBuilder.Entity("BlacksmithWorkshopDatabaseImplement.Models.Shop", b =>
{
b.Navigation("Manufactures");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,184 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace BlacksmithWorkshopDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class BlacksmithWorkshopDataBaseModelSnapshot : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Components",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ComponentName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Cost = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Components", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Manufactures",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ManufactureName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Price = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Manufactures", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Shops",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ShopName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Address = table.Column<string>(type: "nvarchar(max)", nullable: false),
OpeningDate = table.Column<DateTime>(type: "datetime2", nullable: false),
MaxCapacity = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Shops", x => x.Id);
});
migrationBuilder.CreateTable(
name: "ManufactureComponents",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ManufactureId = table.Column<int>(type: "int", nullable: false),
ComponentId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ManufactureComponents", x => x.Id);
table.ForeignKey(
name: "FK_ManufactureComponents_Components_ComponentId",
column: x => x.ComponentId,
principalTable: "Components",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ManufactureComponents_Manufactures_ManufactureId",
column: x => x.ManufactureId,
principalTable: "Manufactures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Count = table.Column<int>(type: "int", nullable: false),
Sum = table.Column<double>(type: "float", nullable: false),
Status = table.Column<int>(type: "int", nullable: false),
DateCreate = table.Column<DateTime>(type: "datetime2", nullable: false),
DateImplement = table.Column<DateTime>(type: "datetime2", nullable: true),
ManufactureId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
table.ForeignKey(
name: "FK_Orders_Manufactures_ManufactureId",
column: x => x.ManufactureId,
principalTable: "Manufactures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "ShopManufactures",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ManufactureId = table.Column<int>(type: "int", nullable: false),
ShopId = table.Column<int>(type: "int", nullable: false),
Count = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ShopManufactures", x => x.Id);
table.ForeignKey(
name: "FK_ShopManufactures_Manufactures_ManufactureId",
column: x => x.ManufactureId,
principalTable: "Manufactures",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_ShopManufactures_Shops_ShopId",
column: x => x.ShopId,
principalTable: "Shops",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_ManufactureComponents_ComponentId",
table: "ManufactureComponents",
column: "ComponentId");
migrationBuilder.CreateIndex(
name: "IX_ManufactureComponents_ManufactureId",
table: "ManufactureComponents",
column: "ManufactureId");
migrationBuilder.CreateIndex(
name: "IX_Orders_ManufactureId",
table: "Orders",
column: "ManufactureId");
migrationBuilder.CreateIndex(
name: "IX_ShopManufactures_ManufactureId",
table: "ShopManufactures",
column: "ManufactureId");
migrationBuilder.CreateIndex(
name: "IX_ShopManufactures_ShopId",
table: "ShopManufactures",
column: "ShopId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ManufactureComponents");
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "ShopManufactures");
migrationBuilder.DropTable(
name: "Components");
migrationBuilder.DropTable(
name: "Manufactures");
migrationBuilder.DropTable(
name: "Shops");
}
}
}

View File

@ -0,0 +1,62 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class Component : IComponentModel
{
public int Id { get; private set; }
[Required]
public string ComponentName { get; private set; } = string.Empty;
[Required]
public double Cost { get; set; }
[ForeignKey("ComponentId")]
public virtual List<ManufactureComponent> ManufactureComponents { get; set; } =
new();
public static Component? Create(ComponentBindingModel model)
{
if (model == null)
{
return null;
}
return new Component()
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public static Component Create(ComponentViewModel model)
{
return new Component
{
Id = model.Id,
ComponentName = model.ComponentName,
Cost = model.Cost
};
}
public void Update(ComponentBindingModel model)
{
if (model == null)
{
return;
}
ComponentName = model.ComponentName;
Cost = model.Cost;
}
public ComponentViewModel GetViewModel => new()
{
Id = Id,
ComponentName = ComponentName,
Cost = Cost
};
}
}

View File

@ -0,0 +1,104 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class Manufacture : IManufactureModel
{
public int Id { get; set; }
[Required]
public string ManufactureName { get; set; } = string.Empty;
[Required]
public double Price { get; set; }
private Dictionary<int, (IComponentModel, int)>? _manufactureComponents =
null;
[NotMapped]
public Dictionary<int, (IComponentModel, int)> ManufactureComponents
{
get
{
if (_manufactureComponents == null)
{
_manufactureComponents = Components
.ToDictionary(recPC => recPC.ComponentId, recPC =>
(recPC.Component as IComponentModel, recPC.Count));
}
return _manufactureComponents;
}
}
[ForeignKey("ManufactureId")]
public virtual List<ManufactureComponent> Components { get; set; } = new();
[ForeignKey("ManufactureId")]
public virtual List<Order> Orders { get; set; } = new();
[ForeignKey("ManufactureId")]
public virtual List<ShopManufacture> ShopManufactures { get; set; } = new();
public static Manufacture Create(BlacksmithWorkshopDataBase context,
ManufactureBindingModel model)
{
return new Manufacture()
{
Id = model.Id,
ManufactureName = model.ManufactureName,
Price = model.Price,
Components = model.ManufactureComponents.Select(x => new
ManufactureComponent
{
Component = context.Components.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ManufactureBindingModel model)
{
ManufactureName = model.ManufactureName;
Price = model.Price;
}
public ManufactureViewModel GetViewModel => new()
{
Id = Id,
ManufactureName = ManufactureName,
Price = Price,
ManufactureComponents = ManufactureComponents
};
public void UpdateComponents(BlacksmithWorkshopDataBase context,
ManufactureBindingModel model)
{
var manufactureComponents = context.ManufactureComponents.Where(rec =>
rec.ManufactureId == model.Id).ToList();
if (manufactureComponents != null && ManufactureComponents.Count > 0)
{
context.ManufactureComponents.RemoveRange(manufactureComponents.Where(rec
=> !model.ManufactureComponents.ContainsKey(rec.ComponentId)));
context.SaveChanges();
foreach (var updateComponent in manufactureComponents)
{
updateComponent.Count =
model.ManufactureComponents[updateComponent.ComponentId].Item2;
model.ManufactureComponents.Remove(updateComponent.ComponentId);
}
context.SaveChanges();
}
var manufacture = context.Manufactures.First(x => x.Id == Id);
foreach (var pc in model.ManufactureComponents)
{
context.ManufactureComponents.Add(new ManufactureComponent
{
Manufacture = manufacture,
Component = context.Components.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_manufactureComponents = null;
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class ManufactureComponent
{
public int Id { get; set; }
[Required]
public int ManufactureId { get; set; }
[Required]
public int ComponentId { get; set; }
[Required]
public int Count { get; set; }
public virtual Component Component { get; set; } = new();
public virtual Manufacture Manufacture { get; set; } = new();
}
}

View File

@ -0,0 +1,64 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Enums;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class Order : IOrderModel
{
public int Id { get; private set; }
[Required]
public int Count { get; private set; }
[Required]
public double Sum { get; private set; }
[Required]
public OrderStatus Status { get; private set; }
[Required]
public DateTime DateCreate { get; private set; }
public DateTime? DateImplement { get; private set; }
[Required]
public int ManufactureId { get; private set; }
public virtual Manufacture? Manufacture { get; set; }
public static Order Create(OrderBindingModel model)
{
return new Order()
{
Id = model.Id,
Count = model.Count,
Sum = model.Sum,
Status = model.Status,
DateCreate = model.DateCreate,
DateImplement = model.DateImplement,
ManufactureId = model.ManufactureId,
};
}
public void Update(OrderBindingModel? model)
{
if (model == null)
{
return;
}
Status = model.Status;
DateImplement = model.DateImplement;
}
public OrderViewModel GetViewModel => new()
{
ManufactureId = ManufactureId,
ManufactureName = Manufacture?.ManufactureName ?? string.Empty,
Count = Count,
Sum = Sum,
Status = Status,
DateCreate = DateCreate,
DateImplement = DateImplement,
Id = Id,
};
}
}

View File

@ -0,0 +1,112 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class Shop : IShopModel
{
public int Id { get; private set; }
[Required]
public string ShopName { get; private set; } = string.Empty;
[Required]
public string Address { get; private set; } = string.Empty;
[Required]
public DateTime OpeningDate { get; private set; }
[Required]
public int MaxCapacity { get; private set; }
private Dictionary<int, (IManufactureModel, int)>? _ShopManufacture = null;
[NotMapped]
public Dictionary<int, (IManufactureModel, int)> ShopManufactures
{
get
{
if (_ShopManufacture == null)
{
_ShopManufacture = Manufactures
.ToDictionary(x => x.ManufactureId, x =>
(x.Manufacture as IManufactureModel, x.Count));
}
return _ShopManufacture;
}
}
[ForeignKey("ShopId")]
public virtual List<ShopManufacture> Manufactures { get; set; } = new();
public static Shop? Create(BlacksmithWorkshopDataBase context, ShopBindingModel model)
{
if (model == null)
return null;
return new Shop()
{
Id = model.Id,
ShopName = model.ShopName,
Address = model.Address,
OpeningDate = model.OpeningDate,
MaxCapacity = model.MaxCapacity,
Manufactures = model.ShopManufactures.Select(x => new ShopManufacture
{
Manufacture = context.Manufactures.First(y => y.Id == x.Key),
Count = x.Value.Item2
}).ToList()
};
}
public void Update(ShopBindingModel? model)
{
if (model == null)
{
return;
}
ShopName = model.ShopName;
Address = model.Address;
OpeningDate = model.OpeningDate;
MaxCapacity = model.MaxCapacity;
}
public ShopViewModel GetViewModel => new()
{
Id = Id,
ShopName = ShopName,
Address = Address,
OpeningDate = OpeningDate,
ShopManufactures = ShopManufactures,
MaxCapacity = MaxCapacity
};
public void UpdateManufactures(BlacksmithWorkshopDataBase context, ShopBindingModel model)
{
var ShopManufacture = context.ShopManufactures.Where(rec =>
rec.ShopId == model.Id).ToList();
if (ShopManufacture != null && ShopManufacture.Count > 0)
{
context.ShopManufactures.RemoveRange(ShopManufacture.Where(rec
=> !model.ShopManufactures.ContainsKey(rec.ShopId)));
context.SaveChanges();
foreach (var updateManufacture in ShopManufacture)
{
updateManufacture.Count =
model.ShopManufactures[updateManufacture.ManufactureId].Item2;
model.ShopManufactures.Remove(updateManufacture.ManufactureId);
}
context.SaveChanges();
}
var shop = context.Shops.First(x => x.Id == Id);
foreach (var pc in model.ShopManufactures)
{
context.ShopManufactures.Add(new ShopManufacture
{
Shop = shop,
Manufacture = context.Manufactures.First(x => x.Id == pc.Key),
Count = pc.Value.Item2
});
context.SaveChanges();
}
_ShopManufacture = null;
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopDatabaseImplement.Models
{
public class ShopManufacture
{
public int Id { get; set; }
[Required]
public int ManufactureId { get; set; }
[Required]
public int ShopId { get; set; }
[Required]
public int Count { get; set; }
public virtual Shop Shop { get; set; } = new();
public virtual Manufacture Manufacture { get; set; } = new();
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\BlacksmithWorkshopContracts\BlacksmithWorkshopContracts.csproj" />
<ProjectReference Include="..\BlacksmithWorkshopDataModels\BlacksmithWorkshopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,33 @@
using BlacksmithWorkshopListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopListImplement
{
public class DataListSingleton
{
private static DataListSingleton? _instance;
public List<Component> Components { get; set; }
public List<Order> Orders { get; set; }
public List<Manufacture> Manufactures { get; set; }
public List<Shop> Shops { get; set; }
private DataListSingleton()
{
Components = new List<Component>();
Orders = new List<Order>();
Manufactures = new List<Manufacture>();
Shops = new List<Shop>();
}
public static DataListSingleton GetInstance()
{
if (_instance == null)
{
_instance = new DataListSingleton();
}
return _instance;
}
}
}

View File

@ -0,0 +1,108 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopListImplement.Implements
{
public class ComponentStorage : IComponentStorage
{
private readonly DataListSingleton _source;
public ComponentStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ComponentViewModel> GetFullList()
{
var result = new List<ComponentViewModel>();
foreach (var component in _source.Components)
{
result.Add(component.GetViewModel);
}
return result;
}
public List<ComponentViewModel> GetFilteredList(ComponentSearchModel
model)
{
var result = new List<ComponentViewModel>();
if (string.IsNullOrEmpty(model.ComponentName))
{
return result;
}
foreach (var component in _source.Components)
{
if (component.ComponentName.Contains(model.ComponentName))
{
result.Add(component.GetViewModel);
}
}
return result;
}
public ComponentViewModel? GetElement(ComponentSearchModel model)
{
if (string.IsNullOrEmpty(model.ComponentName) && !model.Id.HasValue)
{
return null;
}
foreach (var component in _source.Components)
{
if ((!string.IsNullOrEmpty(model.ComponentName) &&
component.ComponentName == model.ComponentName) ||
(model.Id.HasValue && component.Id == model.Id))
{
return component.GetViewModel;
}
}
return null;
}
public ComponentViewModel? Insert(ComponentBindingModel model)
{
model.Id = 1;
foreach (var component in _source.Components)
{
if (model.Id <= component.Id)
{
model.Id = component.Id + 1;
}
}
var newComponent = Component.Create(model);
if (newComponent == null)
{
return null;
}
_source.Components.Add(newComponent);
return newComponent.GetViewModel;
}
public ComponentViewModel? Update(ComponentBindingModel model)
{
foreach (var component in _source.Components)
{
if (component.Id == model.Id)
{
component.Update(model);
return component.GetViewModel;
}
}
return null;
}
public ComponentViewModel? Delete(ComponentBindingModel model)
{
for (int i = 0; i < _source.Components.Count; ++i)
{
if (_source.Components[i].Id == model.Id)
{
var element = _source.Components[i];
_source.Components.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,108 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopListImplement.Implements
{
public class ManufactureStorage : IManufactureStorage
{
private readonly DataListSingleton _source;
public ManufactureStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<ManufactureViewModel> GetFullList()
{
var result = new List<ManufactureViewModel>();
foreach (var Manufacture in _source.Manufactures)
{
result.Add(Manufacture.GetViewModel);
}
return result;
}
public List<ManufactureViewModel> GetFilteredList(ManufactureSearchModel
model)
{
var result = new List<ManufactureViewModel>();
if (string.IsNullOrEmpty(model.ManufactureName))
{
return result;
}
foreach (var Manufacture in _source.Manufactures)
{
if (Manufacture.ManufactureName.Contains(model.ManufactureName))
{
result.Add(Manufacture.GetViewModel);
}
}
return result;
}
public ManufactureViewModel? GetElement(ManufactureSearchModel model)
{
if (string.IsNullOrEmpty(model.ManufactureName) && !model.Id.HasValue)
{
return null;
}
foreach (var Manufacture in _source.Manufactures)
{
if ((!string.IsNullOrEmpty(model.ManufactureName) &&
Manufacture.ManufactureName == model.ManufactureName) ||
(model.Id.HasValue && Manufacture.Id == model.Id))
{
return Manufacture.GetViewModel;
}
}
return null;
}
public ManufactureViewModel? Insert(ManufactureBindingModel model)
{
model.Id = 1;
foreach (var Manufacture in _source.Manufactures)
{
if (model.Id <= Manufacture.Id)
{
model.Id = Manufacture.Id + 1;
}
}
var newManufacture = Manufacture.Create(model);
if (newManufacture == null)
{
return null;
}
_source.Manufactures.Add(newManufacture);
return newManufacture.GetViewModel;
}
public ManufactureViewModel? Update(ManufactureBindingModel model)
{
foreach (var Manufacture in _source.Manufactures)
{
if (Manufacture.Id == model.Id)
{
Manufacture.Update(model);
return Manufacture.GetViewModel;
}
}
return null;
}
public ManufactureViewModel? Delete(ManufactureBindingModel model)
{
for (int i = 0; i < _source.Manufactures.Count; ++i)
{
if (_source.Manufactures[i].Id == model.Id)
{
var element = _source.Manufactures[i];
_source.Manufactures.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
}
}

View File

@ -0,0 +1,118 @@
using BlacksmithWorkshopContracts.BindingModels;
using BlacksmithWorkshopContracts.SearchModels;
using BlacksmithWorkshopContracts.StoragesContracts;
using BlacksmithWorkshopContracts.ViewModels;
using BlacksmithWorkshopListImplement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlacksmithWorkshopListImplement.Implements
{
public class OrderStorage : IOrderStorage
{
private readonly DataListSingleton _source;
public OrderStorage()
{
_source = DataListSingleton.GetInstance();
}
public List<OrderViewModel> GetFullList()
{
var result = new List<OrderViewModel>();
foreach (var order in _source.Orders)
{
result.Add(AccessManufactureStorage(order.GetViewModel));
}
return result;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel
model)
{
var result = new List<OrderViewModel>();
if (!model.Id.HasValue)
{
return result;
}
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
result.Add(AccessManufactureStorage(order.GetViewModel));
}
}
return result;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
foreach (var order in _source.Orders)
{
if (model.Id.HasValue && order.Id == model.Id)
{
return order.GetViewModel;
}
}
return null;
}
public OrderViewModel? Insert(OrderBindingModel model)
{
model.Id = 1;
foreach (var order in _source.Orders)
{
if (model.Id <= order.Id)
{
model.Id = order.Id + 1;
}
}
var newOrder = Order.Create(model);
if (newOrder == null)
{
return null;
}
_source.Orders.Add(newOrder);
return newOrder.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
foreach (var order in _source.Orders)
{
if (order.Id == model.Id)
{
order.Update(model);
return order.GetViewModel;
}
}
return null;
}
public OrderViewModel? Delete(OrderBindingModel model)
{
for (int i = 0; i < _source.Orders.Count; ++i)
{
if (_source.Orders[i].Id == model.Id)
{
var element = _source.Orders[i];
_source.Orders.RemoveAt(i);
return element.GetViewModel;
}
}
return null;
}
public OrderViewModel AccessManufactureStorage(OrderViewModel model)
{
foreach (var Manufacture in _source.Manufactures)
{
if (Manufacture.Id == model.ManufactureId)
{
model.ManufactureName = Manufacture.ManufactureName;
break;
}
}
return model;
}
}
}

Some files were not shown because too many files have changed in this diff Show More