done
This commit is contained in:
parent
4b3da3c21e
commit
f8fc0b4584
13
BusinessLogic/BusinessLogic.csproj
Normal file
13
BusinessLogic/BusinessLogic.csproj
Normal 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="..\Contracts\Contracts.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
65
BusinessLogic/ManufacturerLogic.cs
Normal file
65
BusinessLogic/ManufacturerLogic.cs
Normal file
@ -0,0 +1,65 @@
|
||||
using Contracts.BindingModels;
|
||||
using Contracts.BusinessLogicContracts;
|
||||
using Contracts.StorageContracts;
|
||||
using Contracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BusinessLogic
|
||||
{
|
||||
public class ManufacturerLogic : IManufacturerLogic
|
||||
{
|
||||
private readonly IManufacturerStorage _ManufacturerStorage;
|
||||
public ManufacturerLogic(IManufacturerStorage ManufacturerStorage)
|
||||
{
|
||||
_ManufacturerStorage = ManufacturerStorage;
|
||||
}
|
||||
|
||||
public void CreateOrUpdate(ManufacturerBindingModel model)
|
||||
{
|
||||
var element = _ManufacturerStorage.GetElement(
|
||||
new ManufacturerBindingModel
|
||||
{
|
||||
Name = model.Name
|
||||
});
|
||||
if (element != null && element.Id != model.Id)
|
||||
{
|
||||
throw new Exception("Такой статус уже существует");
|
||||
}
|
||||
if (model.Id.HasValue)
|
||||
{
|
||||
_ManufacturerStorage.Update(model);
|
||||
}
|
||||
else
|
||||
{
|
||||
_ManufacturerStorage.Insert(model);
|
||||
}
|
||||
}
|
||||
|
||||
public void Delete(ManufacturerBindingModel model)
|
||||
{
|
||||
var element = _ManufacturerStorage.GetElement(new ManufacturerBindingModel { Id = model.Id });
|
||||
if (element == null)
|
||||
{
|
||||
throw new Exception("Статус не найден");
|
||||
}
|
||||
_ManufacturerStorage.Delete(model);
|
||||
}
|
||||
|
||||
public List<ManufacturerViewModel> Read(ManufacturerBindingModel model)
|
||||
{
|
||||
if (model == null)
|
||||
{
|
||||
return _ManufacturerStorage.GetFullList();
|
||||
}
|
||||
if (model.Id.HasValue)
|
||||
{
|
||||
return new List<ManufacturerViewModel> { _ManufacturerStorage.GetElement(model) };
|
||||
}
|
||||
return _ManufacturerStorage.GetFilteredList(model);
|
||||
}
|
||||
}
|
||||
}
|
76
BusinessLogic/ProductLogic.cs
Normal file
76
BusinessLogic/ProductLogic.cs
Normal file
@ -0,0 +1,76 @@
|
||||
using Contracts.BindingModels;
|
||||
using Contracts.BusinessLogicContracts;
|
||||
using Contracts.StorageContracts;
|
||||
using Contracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BusinessLogic
|
||||
{
|
||||
public class ProductLogic : IProductLogic
|
||||
{
|
||||
private readonly IProductStorage _ProductStorage;
|
||||
public ProductLogic(IProductStorage ProductStorage)
|
||||
{
|
||||
_ProductStorage = ProductStorage;
|
||||
}
|
||||
public void CreateOrUpdate(ProductBindingModel model)
|
||||
{
|
||||
var element = _ProductStorage.GetElement(
|
||||
new ProductBindingModel
|
||||
{
|
||||
DeliveryDate = model.DeliveryDate,
|
||||
Name = model.Name,
|
||||
Manufacturers = model.Manufacturers,
|
||||
Image = model.Image
|
||||
});
|
||||
if (element != null && element.Id != model.Id)
|
||||
{
|
||||
throw new Exception("Клиент с таким именем уже существует");
|
||||
}
|
||||
if (model.Id.HasValue)
|
||||
{
|
||||
_ProductStorage.Update(model);
|
||||
}
|
||||
else
|
||||
{
|
||||
_ProductStorage.Insert(model);
|
||||
}
|
||||
}
|
||||
|
||||
public void Delete(ProductBindingModel model)
|
||||
{
|
||||
var element = _ProductStorage.GetElement(new ProductBindingModel { Id = model.Id });
|
||||
if (element == null)
|
||||
{
|
||||
throw new Exception("Клиент не найден");
|
||||
}
|
||||
_ProductStorage.Delete(model);
|
||||
}
|
||||
|
||||
public List<ProductViewModel> Read(ProductBindingModel model)
|
||||
{
|
||||
if (model == null)
|
||||
{
|
||||
return _ProductStorage.GetFullList();
|
||||
}
|
||||
if (model.Id.HasValue)
|
||||
{
|
||||
return new List<ProductViewModel> { _ProductStorage.GetElement(model) };
|
||||
}
|
||||
return _ProductStorage.GetFilteredList(model);
|
||||
}
|
||||
|
||||
public List<(int, double)> GetWordInfo()
|
||||
{
|
||||
var data = _ProductStorage.GetProductCountByManufacturer();
|
||||
|
||||
return data
|
||||
.Select((g, index) => (Index: index + 1, Value: (double)g.Count))
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
}
|
14
Contracts/BindingModels/ManufacturerBindingModel.cs
Normal file
14
Contracts/BindingModels/ManufacturerBindingModel.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Contracts.BindingModels
|
||||
{
|
||||
public class ManufacturerBindingModel
|
||||
{
|
||||
public int? Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
18
Contracts/BindingModels/ProductBindingModel.cs
Normal file
18
Contracts/BindingModels/ProductBindingModel.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Contracts.BindingModels
|
||||
{
|
||||
public class ProductBindingModel
|
||||
{
|
||||
public int? Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
public byte[] Image { get; set; }
|
||||
public string Manufacturers { get; set; }
|
||||
public DateTime DeliveryDate { get; set; }
|
||||
}
|
||||
}
|
17
Contracts/BusinessLogicContracts/IManufacturerLogic.cs
Normal file
17
Contracts/BusinessLogicContracts/IManufacturerLogic.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using Contracts.BindingModels;
|
||||
using Contracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Contracts.BusinessLogicContracts
|
||||
{
|
||||
public interface IManufacturerLogic
|
||||
{
|
||||
List<ManufacturerViewModel> Read(ManufacturerBindingModel model);
|
||||
void CreateOrUpdate(ManufacturerBindingModel model);
|
||||
void Delete(ManufacturerBindingModel model);
|
||||
}
|
||||
}
|
18
Contracts/BusinessLogicContracts/IProductLogic.cs
Normal file
18
Contracts/BusinessLogicContracts/IProductLogic.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using Contracts.BindingModels;
|
||||
using Contracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Contracts.BusinessLogicContracts
|
||||
{
|
||||
public interface IProductLogic
|
||||
{
|
||||
List<ProductViewModel> Read(ProductBindingModel model);
|
||||
List<(int, double)> GetWordInfo();
|
||||
void CreateOrUpdate(ProductBindingModel model);
|
||||
void Delete(ProductBindingModel model);
|
||||
}
|
||||
}
|
9
Contracts/Contracts.csproj
Normal file
9
Contracts/Contracts.csproj
Normal file
@ -0,0 +1,9 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
17
Contracts/ReportModels/ProductReportModel.cs
Normal file
17
Contracts/ReportModels/ProductReportModel.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Contracts.ReportModels
|
||||
{
|
||||
public class ProductReportModel
|
||||
{
|
||||
public int? Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string Image { get; set; }
|
||||
public string Manufacturers { get; set; }
|
||||
public string DeliveryDate { get; set; }
|
||||
}
|
||||
}
|
20
Contracts/StorageContracts/IManufacturerStorage.cs
Normal file
20
Contracts/StorageContracts/IManufacturerStorage.cs
Normal file
@ -0,0 +1,20 @@
|
||||
using Contracts.BindingModels;
|
||||
using Contracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Contracts.StorageContracts
|
||||
{
|
||||
public interface IManufacturerStorage
|
||||
{
|
||||
List<ManufacturerViewModel> GetFullList();
|
||||
List<ManufacturerViewModel> GetFilteredList(ManufacturerBindingModel model);
|
||||
ManufacturerViewModel GetElement(ManufacturerBindingModel model);
|
||||
void Insert(ManufacturerBindingModel model);
|
||||
void Update(ManufacturerBindingModel model);
|
||||
void Delete(ManufacturerBindingModel model);
|
||||
}
|
||||
}
|
23
Contracts/StorageContracts/IProductStorage.cs
Normal file
23
Contracts/StorageContracts/IProductStorage.cs
Normal file
@ -0,0 +1,23 @@
|
||||
using Contracts.BindingModels;
|
||||
using Contracts.ViewModels;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Contracts.StorageContracts
|
||||
{
|
||||
public interface IProductStorage
|
||||
{
|
||||
List<ProductViewModel> GetFullList();
|
||||
List<ProductViewModel> GetFilteredList(ProductBindingModel model);
|
||||
ProductViewModel GetElement(ProductBindingModel model);
|
||||
|
||||
List<(string Manufacturer, int Count)> GetProductCountByManufacturer();
|
||||
|
||||
void Insert(ProductBindingModel model);
|
||||
void Update(ProductBindingModel model);
|
||||
void Delete(ProductBindingModel model);
|
||||
}
|
||||
}
|
14
Contracts/ViewModels/ManufacturerViewModel.cs
Normal file
14
Contracts/ViewModels/ManufacturerViewModel.cs
Normal file
@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Contracts.ViewModels
|
||||
{
|
||||
public class ManufacturerViewModel
|
||||
{
|
||||
public int? Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
24
Contracts/ViewModels/ProductViewModel.cs
Normal file
24
Contracts/ViewModels/ProductViewModel.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Contracts.ViewModels
|
||||
{
|
||||
public class ProductViewModel
|
||||
{
|
||||
public int? Id { get; set; }
|
||||
|
||||
[DisplayName("Название")]
|
||||
public string Name { get; set; }
|
||||
|
||||
[DisplayName("Изображение")]
|
||||
public byte[] Image { get; set; }
|
||||
[DisplayName("Производитель")]
|
||||
public string Manufacturers { get; set; }
|
||||
[DisplayName("Дата поставки")]
|
||||
public DateTime DeliveryDate { get; set; }
|
||||
}
|
||||
}
|
22
DatabaseImplement/DatabaseImplement.csproj
Normal file
22
DatabaseImplement/DatabaseImplement.csproj
Normal file
@ -0,0 +1,22 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.33" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.33" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.33">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Contracts\Contracts.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
121
DatabaseImplement/Implements/ManufacturerStorage.cs
Normal file
121
DatabaseImplement/Implements/ManufacturerStorage.cs
Normal file
@ -0,0 +1,121 @@
|
||||
using Contracts.BindingModels;
|
||||
using Contracts.StorageContracts;
|
||||
using Contracts.ViewModels;
|
||||
using DatabaseImplement.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DatabaseImplement.Implements
|
||||
{
|
||||
public class ManufacturerStorage : IManufacturerStorage
|
||||
{
|
||||
public void Delete(ManufacturerBindingModel model)
|
||||
{
|
||||
var context = new ProductsDatabase();
|
||||
var Manufacturer = context.Manufacturers.FirstOrDefault(rec => rec.Id == model.Id);
|
||||
if (Manufacturer != null)
|
||||
{
|
||||
context.Manufacturers.Remove(Manufacturer);
|
||||
context.SaveChanges();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("Производитель не найден");
|
||||
}
|
||||
}
|
||||
|
||||
public ManufacturerViewModel GetElement(ManufacturerBindingModel model)
|
||||
{
|
||||
if (model == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
using var context = new ProductsDatabase();
|
||||
|
||||
var manufacturer = context.Manufacturers
|
||||
.ToList()
|
||||
.FirstOrDefault(rec => rec.Id == model.Id || rec.Name == model.Name);
|
||||
return manufacturer != null ? CreateModel(manufacturer) : null;
|
||||
}
|
||||
|
||||
|
||||
public List<ManufacturerViewModel> GetFilteredList(ManufacturerBindingModel model)
|
||||
{
|
||||
if (model == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
using var context = new ProductsDatabase();
|
||||
return context.Manufacturers
|
||||
.Where(rec => rec.Name.Contains(model.Name))
|
||||
.Select(CreateModel)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public List<ManufacturerViewModel> GetFullList()
|
||||
{
|
||||
using var context = new ProductsDatabase();
|
||||
return context.Manufacturers
|
||||
.Select(CreateModel)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public void Insert(ManufacturerBindingModel model)
|
||||
{
|
||||
var context = new ProductsDatabase();
|
||||
var transaction = context.Database.BeginTransaction();
|
||||
try
|
||||
{
|
||||
context.Manufacturers.Add(CreateModel(model, new Manufacturer()));
|
||||
context.SaveChanges();
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void Update(ManufacturerBindingModel model)
|
||||
{
|
||||
var context = new ProductsDatabase();
|
||||
var transaction = context.Database.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var Manufacturer = context.Manufacturers.FirstOrDefault(rec => rec.Id == model.Id);
|
||||
if (Manufacturer == null)
|
||||
{
|
||||
throw new Exception("Производитель не найден");
|
||||
}
|
||||
CreateModel(model, Manufacturer);
|
||||
context.SaveChanges();
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static Manufacturer CreateModel(ManufacturerBindingModel model, Manufacturer Manufacturer)
|
||||
{
|
||||
Manufacturer.Name = model.Name;
|
||||
return Manufacturer;
|
||||
}
|
||||
|
||||
private static ManufacturerViewModel CreateModel(Manufacturer Manufacturer)
|
||||
{
|
||||
return new ManufacturerViewModel
|
||||
{
|
||||
Id = Manufacturer.Id,
|
||||
Name = Manufacturer.Name
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
144
DatabaseImplement/Implements/ProductStorage.cs
Normal file
144
DatabaseImplement/Implements/ProductStorage.cs
Normal file
@ -0,0 +1,144 @@
|
||||
using Contracts.BindingModels;
|
||||
using Contracts.StorageContracts;
|
||||
using Contracts.ViewModels;
|
||||
using DatabaseImplement.Models;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DatabaseImplement.Implements
|
||||
{
|
||||
|
||||
public class ProductStorage : IProductStorage
|
||||
{
|
||||
public void Delete(ProductBindingModel model)
|
||||
{
|
||||
var context = new ProductsDatabase();
|
||||
var Product = context.Products.FirstOrDefault(rec => rec.Id == model.Id);
|
||||
if (Product != null)
|
||||
{
|
||||
context.Products.Remove(Product);
|
||||
context.SaveChanges();
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new Exception("Продукт не найден");
|
||||
}
|
||||
}
|
||||
|
||||
public ProductViewModel GetElement(ProductBindingModel model)
|
||||
{
|
||||
if (model == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
using var context = new ProductsDatabase();
|
||||
var Product = context.Products
|
||||
.ToList()
|
||||
.FirstOrDefault(rec => rec.Id == model.Id);
|
||||
return Product != null ? CreateModel(Product) : null;
|
||||
}
|
||||
|
||||
public List<ProductViewModel> GetFilteredList(ProductBindingModel model)
|
||||
{
|
||||
var context = new ProductsDatabase();
|
||||
return context.Products
|
||||
.ToList()
|
||||
.Select(CreateModel)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public List<(string Manufacturer, int Count)> GetProductCountByManufacturer()
|
||||
{
|
||||
var context = new ProductsDatabase();
|
||||
return context.Products
|
||||
.GroupBy(p => p.Manufacturers)
|
||||
.Select(g => new { Manufacturer = g.Key, Count = g.Count() })
|
||||
.AsEnumerable() // Приведение к Enumerable, чтобы продолжить обработку в памяти
|
||||
.Select(g => (g.Manufacturer, g.Count))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private ProductViewModel CustomCreateModel(Product product)
|
||||
{
|
||||
return new ProductViewModel
|
||||
{
|
||||
Manufacturers = product.Manufacturers,
|
||||
};
|
||||
}
|
||||
|
||||
public List<ProductViewModel> GetFullList()
|
||||
{
|
||||
using (var context = new ProductsDatabase())
|
||||
{
|
||||
return context.Products
|
||||
.ToList()
|
||||
.Select(CreateModel)
|
||||
.ToList();
|
||||
}
|
||||
}
|
||||
|
||||
public void Insert(ProductBindingModel model)
|
||||
{
|
||||
var context = new ProductsDatabase();
|
||||
var transaction = context.Database.BeginTransaction();
|
||||
try
|
||||
{
|
||||
context.Products.Add(CreateModel(model, new Product()));
|
||||
context.SaveChanges();
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public void Update(ProductBindingModel model)
|
||||
{
|
||||
var context = new ProductsDatabase();
|
||||
var transaction = context.Database.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var Product = context.Products.FirstOrDefault(rec => rec.Id == model.Id);
|
||||
if (Product == null)
|
||||
{
|
||||
throw new Exception("Продукт не найден");
|
||||
}
|
||||
CreateModel(model, Product);
|
||||
context.SaveChanges();
|
||||
transaction.Commit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static Product CreateModel(ProductBindingModel model, Product Product)
|
||||
{
|
||||
Product.DeliveryDate = model.DeliveryDate;
|
||||
Product.Name = model.Name;
|
||||
Product.Manufacturers = model.Manufacturers;
|
||||
Product.Image = model.Image;
|
||||
|
||||
return Product;
|
||||
}
|
||||
|
||||
private ProductViewModel CreateModel(Product Product)
|
||||
{
|
||||
return new ProductViewModel
|
||||
{
|
||||
Id = Product.Id,
|
||||
Image = Product.Image,
|
||||
Name = Product.Name,
|
||||
Manufacturers = Product.Manufacturers,
|
||||
DeliveryDate = Product.DeliveryDate
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
74
DatabaseImplement/Migrations/20241012142150_Init.Designer.cs
generated
Normal file
74
DatabaseImplement/Migrations/20241012142150_Init.Designer.cs
generated
Normal file
@ -0,0 +1,74 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using DatabaseImplement;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DatabaseImplement.Migrations
|
||||
{
|
||||
[DbContext(typeof(ProductsDatabase))]
|
||||
[Migration("20241012142150_Init")]
|
||||
partial class Init
|
||||
{
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "6.0.33")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||
|
||||
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1);
|
||||
|
||||
modelBuilder.Entity("DatabaseImplement.Models.Manufacturer", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Manufacturers");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("DatabaseImplement.Models.Product", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
|
||||
|
||||
b.Property<DateTime>("DeliveryDate")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<byte[]>("Image")
|
||||
.IsRequired()
|
||||
.HasColumnType("varbinary(max)");
|
||||
|
||||
b.Property<string>("Manufacturers")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Products");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
51
DatabaseImplement/Migrations/20241012142150_Init.cs
Normal file
51
DatabaseImplement/Migrations/20241012142150_Init.cs
Normal file
@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DatabaseImplement.Migrations
|
||||
{
|
||||
public partial class Init : Migration
|
||||
{
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Manufacturers",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false)
|
||||
.Annotation("SqlServer:Identity", "1, 1"),
|
||||
Name = table.Column<string>(type: "nvarchar(max)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Manufacturers", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Products",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false)
|
||||
.Annotation("SqlServer:Identity", "1, 1"),
|
||||
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
|
||||
Image = table.Column<byte[]>(type: "varbinary(max)", nullable: false),
|
||||
Manufacturers = table.Column<string>(type: "nvarchar(max)", nullable: false),
|
||||
DeliveryDate = table.Column<DateTime>(type: "datetime2", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Products", x => x.Id);
|
||||
});
|
||||
}
|
||||
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Manufacturers");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Products");
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,72 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using DatabaseImplement;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace DatabaseImplement.Migrations
|
||||
{
|
||||
[DbContext(typeof(ProductsDatabase))]
|
||||
partial class ProductsDatabaseModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "6.0.33")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||
|
||||
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1);
|
||||
|
||||
modelBuilder.Entity("DatabaseImplement.Models.Manufacturer", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Manufacturers");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("DatabaseImplement.Models.Product", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"), 1L, 1);
|
||||
|
||||
b.Property<DateTime>("DeliveryDate")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<byte[]>("Image")
|
||||
.IsRequired()
|
||||
.HasColumnType("varbinary(max)");
|
||||
|
||||
b.Property<string>("Manufacturers")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Name")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Products");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
17
DatabaseImplement/Models/Manufacturer.cs
Normal file
17
DatabaseImplement/Models/Manufacturer.cs
Normal file
@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace DatabaseImplement.Models
|
||||
{
|
||||
public class Manufacturer
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
[Required]
|
||||
public string Name { get; set; }
|
||||
}
|
||||
}
|
22
DatabaseImplement/Models/Product.cs
Normal file
22
DatabaseImplement/Models/Product.cs
Normal 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 DatabaseImplement.Models
|
||||
{
|
||||
public class Product
|
||||
{
|
||||
public int Id { get; set; }
|
||||
[Required]
|
||||
public string Name { get; set; }
|
||||
[Required]
|
||||
public byte[] Image { get; set; }
|
||||
[Required]
|
||||
public string Manufacturers { get; set; }
|
||||
[Required]
|
||||
public DateTime DeliveryDate { get; set; }
|
||||
}
|
||||
}
|
25
DatabaseImplement/ProductsDatabase.cs
Normal file
25
DatabaseImplement/ProductsDatabase.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using DatabaseImplement.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace DatabaseImplement
|
||||
{
|
||||
public class ProductsDatabase : DbContext
|
||||
{
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
if (optionsBuilder.IsConfigured == false)
|
||||
{
|
||||
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-SPMUS7R;Initial Catalog=ProductsDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
|
||||
}
|
||||
base.OnConfiguring(optionsBuilder);
|
||||
}
|
||||
public virtual DbSet<Product> Products { set; get; }
|
||||
public virtual DbSet<Manufacturer> Manufacturers { set; get; }
|
||||
}
|
||||
}
|
43
ShopProducts.sln
Normal file
43
ShopProducts.sln
Normal file
@ -0,0 +1,43 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.8.34408.163
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ShopProducts", "ShopProducts\ShopProducts.csproj", "{E8F82DF1-6741-454A-B96D-C1F2FB29134D}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Contracts", "Contracts\Contracts.csproj", "{F2440E2E-293A-4107-980B-EC0020529692}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BusinessLogic", "BusinessLogic\BusinessLogic.csproj", "{344C1681-67A5-485B-8E99-89F7D5866078}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DatabaseImplement", "DatabaseImplement\DatabaseImplement.csproj", "{80BABD36-989A-4181-9159-23A0BD3CF04A}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{E8F82DF1-6741-454A-B96D-C1F2FB29134D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{E8F82DF1-6741-454A-B96D-C1F2FB29134D}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{E8F82DF1-6741-454A-B96D-C1F2FB29134D}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{E8F82DF1-6741-454A-B96D-C1F2FB29134D}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F2440E2E-293A-4107-980B-EC0020529692}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F2440E2E-293A-4107-980B-EC0020529692}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F2440E2E-293A-4107-980B-EC0020529692}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F2440E2E-293A-4107-980B-EC0020529692}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{344C1681-67A5-485B-8E99-89F7D5866078}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{344C1681-67A5-485B-8E99-89F7D5866078}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{344C1681-67A5-485B-8E99-89F7D5866078}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{344C1681-67A5-485B-8E99-89F7D5866078}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{80BABD36-989A-4181-9159-23A0BD3CF04A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{80BABD36-989A-4181-9159-23A0BD3CF04A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{80BABD36-989A-4181-9159-23A0BD3CF04A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{80BABD36-989A-4181-9159-23A0BD3CF04A}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {1B480F8A-27B6-4A43-896B-4B570320DF49}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
63
ShopProducts/FormManufacturers.Designer.cs
generated
Normal file
63
ShopProducts/FormManufacturers.Designer.cs
generated
Normal file
@ -0,0 +1,63 @@
|
||||
namespace ShopProducts
|
||||
{
|
||||
partial class FormManufacturers
|
||||
{
|
||||
/// <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()
|
||||
{
|
||||
dataGridView1 = new DataGridView();
|
||||
((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit();
|
||||
SuspendLayout();
|
||||
//
|
||||
// dataGridView1
|
||||
//
|
||||
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
|
||||
dataGridView1.Location = new Point(12, 12);
|
||||
dataGridView1.Name = "dataGridView1";
|
||||
dataGridView1.RowTemplate.Height = 25;
|
||||
dataGridView1.Size = new Size(642, 350);
|
||||
dataGridView1.TabIndex = 0;
|
||||
dataGridView1.CellContentClick += dataGridView1_CellContentClick;
|
||||
dataGridView1.KeyDown += dataGridView1_KeyDown;
|
||||
//
|
||||
// FormManufacturers
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(663, 374);
|
||||
Controls.Add(dataGridView1);
|
||||
Name = "FormManufacturers";
|
||||
Text = "FormManufacturers";
|
||||
Load += FormManufacturers_Load;
|
||||
((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit();
|
||||
ResumeLayout(false);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private DataGridView dataGridView1;
|
||||
}
|
||||
}
|
117
ShopProducts/FormManufacturers.cs
Normal file
117
ShopProducts/FormManufacturers.cs
Normal file
@ -0,0 +1,117 @@
|
||||
using Contracts.BindingModels;
|
||||
using Contracts.BusinessLogicContracts;
|
||||
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 ShopProducts
|
||||
{
|
||||
public partial class FormManufacturers : Form
|
||||
{
|
||||
private readonly IManufacturerLogic _manufacturerLogic;
|
||||
BindingList<ManufacturerBindingModel> list;
|
||||
public FormManufacturers(IManufacturerLogic manufacturerLogic)
|
||||
{
|
||||
InitializeComponent();
|
||||
_manufacturerLogic = manufacturerLogic;
|
||||
list = new BindingList<ManufacturerBindingModel>();
|
||||
// dataGridView1.AllowUserToAddRows = false;
|
||||
}
|
||||
|
||||
private void LoadData()
|
||||
{
|
||||
try
|
||||
{
|
||||
var list1 = _manufacturerLogic.Read(null);
|
||||
list.Clear();
|
||||
foreach (var item in list1)
|
||||
{
|
||||
list.Add(new ManufacturerBindingModel
|
||||
{
|
||||
Id = item.Id,
|
||||
Name = item.Name,
|
||||
});
|
||||
}
|
||||
if (list != null)
|
||||
{
|
||||
dataGridView1.DataSource = list;
|
||||
dataGridView1.Columns[0].Visible = false;
|
||||
dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void FormManufacturers_Load(object sender, EventArgs e)
|
||||
{
|
||||
LoadData();
|
||||
}
|
||||
|
||||
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
|
||||
{
|
||||
var typeName = (string)dataGridView1.CurrentRow.Cells[1].Value;
|
||||
if (!string.IsNullOrEmpty(typeName))
|
||||
{
|
||||
if (dataGridView1.CurrentRow.Cells[0].Value != null)
|
||||
{
|
||||
_manufacturerLogic.CreateOrUpdate(new ManufacturerBindingModel()
|
||||
{
|
||||
Id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value),
|
||||
Name = (string)dataGridView1.CurrentRow.Cells[1].EditedFormattedValue
|
||||
});
|
||||
}
|
||||
else
|
||||
{
|
||||
_manufacturerLogic.CreateOrUpdate(new ManufacturerBindingModel()
|
||||
{
|
||||
Name = (string)dataGridView1.CurrentRow.Cells[1].EditedFormattedValue
|
||||
});
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Введена пустая строка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
LoadData();
|
||||
}
|
||||
|
||||
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.KeyData == Keys.Insert)
|
||||
{
|
||||
if (dataGridView1.Rows.Count == 0)
|
||||
{
|
||||
list.Add(new ManufacturerBindingModel());
|
||||
dataGridView1.DataSource = new BindingList<ManufacturerBindingModel>(list);
|
||||
dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[1];
|
||||
return;
|
||||
}
|
||||
if (dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value != null)
|
||||
{
|
||||
list.Add(new ManufacturerBindingModel());
|
||||
dataGridView1.DataSource = new BindingList<ManufacturerBindingModel>(list);
|
||||
dataGridView1.CurrentCell = dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1];
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (e.KeyData == Keys.Delete)
|
||||
{
|
||||
if (MessageBox.Show("Удалить выбранный элемент", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_manufacturerLogic.Delete(new ManufacturerBindingModel() { Id = (int)dataGridView1.CurrentRow.Cells[0].Value });
|
||||
LoadData();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
189
ShopProducts/FormProduct.Designer.cs
generated
Normal file
189
ShopProducts/FormProduct.Designer.cs
generated
Normal file
@ -0,0 +1,189 @@
|
||||
namespace ShopProducts
|
||||
{
|
||||
partial class FormProduct
|
||||
{
|
||||
/// <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()
|
||||
{
|
||||
textBoxName = new TextBox();
|
||||
label1 = new Label();
|
||||
label2 = new Label();
|
||||
label3 = new Label();
|
||||
customComboBoxManufacturers = new ControlsLibraryNet60.Selected.ControlSelectedComboBoxSingle();
|
||||
label4 = new Label();
|
||||
customTextBoxDate = new ControlsLibraryNet60.Input.ControlInputRegexDate();
|
||||
buttonSave = new Button();
|
||||
buttonCancel = new Button();
|
||||
imageFileLabel = new Label();
|
||||
pickFileButton = new Button();
|
||||
SuspendLayout();
|
||||
//
|
||||
// textBoxName
|
||||
//
|
||||
textBoxName.Location = new Point(14, 36);
|
||||
textBoxName.Margin = new Padding(3, 4, 3, 4);
|
||||
textBoxName.Name = "textBoxName";
|
||||
textBoxName.Size = new Size(261, 27);
|
||||
textBoxName.TabIndex = 0;
|
||||
textBoxName.TextChanged += textBoxName_TextChanged;
|
||||
//
|
||||
// label1
|
||||
//
|
||||
label1.AutoSize = true;
|
||||
label1.Location = new Point(14, 12);
|
||||
label1.Name = "label1";
|
||||
label1.Size = new Size(49, 20);
|
||||
label1.TabIndex = 1;
|
||||
label1.Text = "Name";
|
||||
//
|
||||
// label2
|
||||
//
|
||||
label2.AutoSize = true;
|
||||
label2.Location = new Point(13, 71);
|
||||
label2.Name = "label2";
|
||||
label2.Size = new Size(51, 20);
|
||||
label2.TabIndex = 2;
|
||||
label2.Text = "Image";
|
||||
//
|
||||
// label3
|
||||
//
|
||||
label3.AutoSize = true;
|
||||
label3.Location = new Point(13, 129);
|
||||
label3.Name = "label3";
|
||||
label3.Size = new Size(103, 20);
|
||||
label3.TabIndex = 4;
|
||||
label3.Text = "Manufacturers";
|
||||
//
|
||||
// customComboBoxManufacturers
|
||||
//
|
||||
customComboBoxManufacturers.Location = new Point(16, 153);
|
||||
customComboBoxManufacturers.Margin = new Padding(6, 4, 6, 4);
|
||||
customComboBoxManufacturers.Name = "customComboBoxManufacturers";
|
||||
customComboBoxManufacturers.SelectedElement = "";
|
||||
customComboBoxManufacturers.Size = new Size(256, 32);
|
||||
customComboBoxManufacturers.TabIndex = 5;
|
||||
customComboBoxManufacturers.SelectedElementChange += customComboBoxManufacturers_SelectedElementChange;
|
||||
//
|
||||
// label4
|
||||
//
|
||||
label4.AutoSize = true;
|
||||
label4.Location = new Point(16, 189);
|
||||
label4.Name = "label4";
|
||||
label4.Size = new Size(41, 20);
|
||||
label4.TabIndex = 6;
|
||||
label4.Text = "Date";
|
||||
//
|
||||
// customTextBoxDate
|
||||
//
|
||||
customTextBoxDate.Location = new Point(16, 213);
|
||||
customTextBoxDate.Margin = new Padding(6, 4, 6, 4);
|
||||
customTextBoxDate.Name = "customTextBoxDate";
|
||||
customTextBoxDate.Pattern = "^\\d{1,2} \\w{3,8} \\d{4}$";
|
||||
customTextBoxDate.Size = new Size(256, 31);
|
||||
customTextBoxDate.TabIndex = 7;
|
||||
customTextBoxDate.Value = "";
|
||||
customTextBoxDate.ElementChanged += customTextBoxDate_ElementChanged;
|
||||
//
|
||||
// buttonSave
|
||||
//
|
||||
buttonSave.Location = new Point(16, 272);
|
||||
buttonSave.Margin = new Padding(3, 4, 3, 4);
|
||||
buttonSave.Name = "buttonSave";
|
||||
buttonSave.Size = new Size(86, 31);
|
||||
buttonSave.TabIndex = 8;
|
||||
buttonSave.Text = "Save";
|
||||
buttonSave.UseVisualStyleBackColor = true;
|
||||
buttonSave.Click += buttonSave_Click;
|
||||
//
|
||||
// buttonCancel
|
||||
//
|
||||
buttonCancel.Location = new Point(186, 272);
|
||||
buttonCancel.Margin = new Padding(3, 4, 3, 4);
|
||||
buttonCancel.Name = "buttonCancel";
|
||||
buttonCancel.Size = new Size(86, 31);
|
||||
buttonCancel.TabIndex = 9;
|
||||
buttonCancel.Text = "Cancel";
|
||||
buttonCancel.UseVisualStyleBackColor = true;
|
||||
buttonCancel.Click += buttonCancel_Click;
|
||||
//
|
||||
// imageFileLabel
|
||||
//
|
||||
imageFileLabel.AutoSize = true;
|
||||
imageFileLabel.Location = new Point(16, 101);
|
||||
imageFileLabel.Name = "imageFileLabel";
|
||||
imageFileLabel.Size = new Size(54, 20);
|
||||
imageFileLabel.TabIndex = 10;
|
||||
imageFileLabel.Text = "No file";
|
||||
//
|
||||
// pickFileButton
|
||||
//
|
||||
pickFileButton.Location = new Point(135, 97);
|
||||
pickFileButton.Name = "pickFileButton";
|
||||
pickFileButton.Size = new Size(140, 29);
|
||||
pickFileButton.TabIndex = 11;
|
||||
pickFileButton.Text = "Pick file";
|
||||
pickFileButton.UseVisualStyleBackColor = true;
|
||||
pickFileButton.Click += pickFileButton_Click;
|
||||
//
|
||||
// FormProduct
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(287, 331);
|
||||
Controls.Add(pickFileButton);
|
||||
Controls.Add(imageFileLabel);
|
||||
Controls.Add(buttonCancel);
|
||||
Controls.Add(buttonSave);
|
||||
Controls.Add(customTextBoxDate);
|
||||
Controls.Add(label4);
|
||||
Controls.Add(customComboBoxManufacturers);
|
||||
Controls.Add(label3);
|
||||
Controls.Add(label2);
|
||||
Controls.Add(label1);
|
||||
Controls.Add(textBoxName);
|
||||
Margin = new Padding(3, 4, 3, 4);
|
||||
Name = "FormProduct";
|
||||
Text = "FormProduct";
|
||||
Load += FormProduct_Load;
|
||||
ResumeLayout(false);
|
||||
PerformLayout();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private TextBox textBoxName;
|
||||
private Label label1;
|
||||
private Label label2;
|
||||
private Label label3;
|
||||
private ControlsLibraryNet60.Selected.ControlSelectedComboBoxSingle customComboBoxManufacturers;
|
||||
private Label label4;
|
||||
private ControlsLibraryNet60.Input.ControlInputRegexDate customTextBoxDate;
|
||||
private Button buttonSave;
|
||||
private Button buttonCancel;
|
||||
private Label imageFileLabel;
|
||||
private Button pickFileButton;
|
||||
}
|
||||
}
|
160
ShopProducts/FormProduct.cs
Normal file
160
ShopProducts/FormProduct.cs
Normal file
@ -0,0 +1,160 @@
|
||||
using Contracts.BindingModels;
|
||||
using Contracts.BusinessLogicContracts;
|
||||
using Contracts.ViewModels;
|
||||
using DocumentFormat.OpenXml.Office2010.Excel;
|
||||
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 ShopProducts
|
||||
{
|
||||
// ^\d{2}\s(?:January|February|March|April|May|June|July|August|September|October|November|December)\s\d{4}$
|
||||
|
||||
public partial class FormProduct : Form
|
||||
{
|
||||
public int Id { set { id = value; } }
|
||||
|
||||
private readonly IProductLogic _logic;
|
||||
private readonly IManufacturerLogic _logicM;
|
||||
|
||||
private int? id;
|
||||
private bool _wasChanged = false;
|
||||
|
||||
private byte[]? productImage = null;
|
||||
public FormProduct(IProductLogic logic, IManufacturerLogic logicM)
|
||||
{
|
||||
InitializeComponent();
|
||||
_logic = logic;
|
||||
_logicM = logicM;
|
||||
}
|
||||
|
||||
private void buttonSave_Click(object sender, EventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (string.IsNullOrEmpty(textBoxName.Text))
|
||||
{
|
||||
MessageBox.Show("Заполните имя", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
if (productImage == null)
|
||||
{
|
||||
MessageBox.Show("Выберите фото", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrEmpty(customComboBoxManufacturers.SelectedElement))
|
||||
{
|
||||
MessageBox.Show("Выберите производителя", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
if (string.IsNullOrEmpty(customTextBoxDate.Value))
|
||||
{
|
||||
MessageBox.Show("Заполните дату", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
var date = DateTime.ParseExact(customTextBoxDate.Value, "dd MMMM yyyy", new System.Globalization.CultureInfo("ru-RU"));
|
||||
_logic.CreateOrUpdate(new ProductBindingModel
|
||||
{
|
||||
Id = id,
|
||||
Image = productImage,
|
||||
Name = textBoxName.Text,
|
||||
Manufacturers = customComboBoxManufacturers.SelectedElement.ToString(),
|
||||
DeliveryDate = date,
|
||||
});
|
||||
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
DialogResult = DialogResult.OK;
|
||||
Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void buttonCancel_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_wasChanged)
|
||||
{
|
||||
DialogResult dialogResult = MessageBox.Show("Есть внесенные изменения, вы точно хотите выйти?", "Предупреждение", MessageBoxButtons.YesNo);
|
||||
if (dialogResult == DialogResult.Yes)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
return;
|
||||
}
|
||||
DialogResult = DialogResult.Cancel;
|
||||
Close();
|
||||
}
|
||||
|
||||
private void textBoxName_TextChanged(object sender, EventArgs e)
|
||||
{
|
||||
_wasChanged = true;
|
||||
}
|
||||
|
||||
private void textBoxImage_TextChanged(object sender, EventArgs e)
|
||||
{
|
||||
_wasChanged = true;
|
||||
}
|
||||
|
||||
private void customComboBoxManufacturers_SelectedElementChange(object sender, EventArgs e)
|
||||
{
|
||||
_wasChanged = true;
|
||||
}
|
||||
|
||||
private void customTextBoxDate_ElementChanged(object sender, EventArgs e)
|
||||
{
|
||||
_wasChanged = true;
|
||||
}
|
||||
|
||||
private void FormProduct_Load(object sender, EventArgs e)
|
||||
{
|
||||
List<ManufacturerViewModel> mViews = _logicM.Read(null);
|
||||
if (mViews != null)
|
||||
{
|
||||
for (int i = 0; i < mViews.Count; i++)
|
||||
{
|
||||
customComboBoxManufacturers.AddElement(mViews[i].Name);
|
||||
}
|
||||
}
|
||||
|
||||
if (id.HasValue)
|
||||
{
|
||||
ProductViewModel product = _logic.Read(new ProductBindingModel { Id = id.Value })?[0];
|
||||
if (product != null)
|
||||
{
|
||||
textBoxName.Text = product.Name;
|
||||
ChangeImageFile(product.Image);
|
||||
customComboBoxManufacturers.SelectedElement = product.Manufacturers;
|
||||
var date = product.DeliveryDate.ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("ru-RU"));
|
||||
customTextBoxDate.Value = date;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void pickFileButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
using OpenFileDialog openFileDialog = new OpenFileDialog
|
||||
{
|
||||
Filter = "Изображения|*.jpg;*.jpeg;*.png;*.bmp"
|
||||
};
|
||||
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
ChangeImageFile(File.ReadAllBytes(openFileDialog.FileName));
|
||||
}
|
||||
}
|
||||
|
||||
private void ChangeImageFile(byte[]? bytes)
|
||||
{
|
||||
productImage = bytes;
|
||||
imageFileLabel.Text = bytes == null ? "No file" : "File picked";
|
||||
}
|
||||
}
|
||||
}
|
147
ShopProducts/FormProducts.Designer.cs
generated
Normal file
147
ShopProducts/FormProducts.Designer.cs
generated
Normal file
@ -0,0 +1,147 @@
|
||||
namespace ShopProducts
|
||||
{
|
||||
partial class FormProducts
|
||||
{
|
||||
/// <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()
|
||||
{
|
||||
components = new System.ComponentModel.Container();
|
||||
controlDataTableRow1 = new ControlsLibraryNet60.Data.ControlDataTableRow();
|
||||
contextMenuStrip1 = new ContextMenuStrip(components);
|
||||
сохранитьВордtoolStripMenuItem = new ToolStripMenuItem();
|
||||
сохранитьЭксельtoolStripMenuItem = new ToolStripMenuItem();
|
||||
сохранитьПдфtoolStripMenuItem = new ToolStripMenuItem();
|
||||
удалитьtoolStripMenuItem = new ToolStripMenuItem();
|
||||
редактироватьtoolStripMenuItem = new ToolStripMenuItem();
|
||||
добавитьtoolStripMenuItem = new ToolStripMenuItem();
|
||||
справочникtoolStripMenuItem = new ToolStripMenuItem();
|
||||
pdfWithImages1 = new WinFormsLibrary1.PdfWithImages(components);
|
||||
componentDocumentWithTableHeaderRowExcel1 = new ComponentsLibraryNet60.DocumentWithTable.ComponentDocumentWithTableHeaderRowExcel(components);
|
||||
componentDocumentWithChartBarWord1 = new ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord(components);
|
||||
contextMenuStrip1.SuspendLayout();
|
||||
SuspendLayout();
|
||||
//
|
||||
// controlDataTableRow1
|
||||
//
|
||||
controlDataTableRow1.Location = new Point(89, 53);
|
||||
controlDataTableRow1.Margin = new Padding(5, 4, 5, 4);
|
||||
controlDataTableRow1.Name = "controlDataTableRow1";
|
||||
controlDataTableRow1.SelectedRowIndex = -1;
|
||||
controlDataTableRow1.Size = new Size(730, 479);
|
||||
controlDataTableRow1.TabIndex = 0;
|
||||
//
|
||||
// contextMenuStrip1
|
||||
//
|
||||
contextMenuStrip1.ImageScalingSize = new Size(20, 20);
|
||||
contextMenuStrip1.Items.AddRange(new ToolStripItem[] { сохранитьВордtoolStripMenuItem, сохранитьЭксельtoolStripMenuItem, сохранитьПдфtoolStripMenuItem, удалитьtoolStripMenuItem, редактироватьtoolStripMenuItem, добавитьtoolStripMenuItem, справочникtoolStripMenuItem });
|
||||
contextMenuStrip1.Name = "contextMenuStrip1";
|
||||
contextMenuStrip1.Size = new Size(255, 172);
|
||||
//
|
||||
// сохранитьВордtoolStripMenuItem
|
||||
//
|
||||
сохранитьВордtoolStripMenuItem.Name = "сохранитьВордtoolStripMenuItem";
|
||||
сохранитьВордtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
|
||||
сохранитьВордtoolStripMenuItem.Size = new Size(254, 24);
|
||||
сохранитьВордtoolStripMenuItem.Text = "Сохранить Ворд";
|
||||
сохранитьВордtoolStripMenuItem.Click += сохранитьВордToolStripMenuItem_Click;
|
||||
//
|
||||
// сохранитьЭксельtoolStripMenuItem
|
||||
//
|
||||
сохранитьЭксельtoolStripMenuItem.Name = "сохранитьЭксельtoolStripMenuItem";
|
||||
сохранитьЭксельtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.C;
|
||||
сохранитьЭксельtoolStripMenuItem.Size = new Size(254, 24);
|
||||
сохранитьЭксельtoolStripMenuItem.Text = "Сохранить Эксель";
|
||||
сохранитьЭксельtoolStripMenuItem.Click += сохранитьЭксельToolStripMenuItem_Click;
|
||||
//
|
||||
// сохранитьПдфtoolStripMenuItem
|
||||
//
|
||||
сохранитьПдфtoolStripMenuItem.Name = "сохранитьПдфtoolStripMenuItem";
|
||||
сохранитьПдфtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.T;
|
||||
сохранитьПдфtoolStripMenuItem.Size = new Size(254, 24);
|
||||
сохранитьПдфtoolStripMenuItem.Text = "Сохранить ПДФ";
|
||||
сохранитьПдфtoolStripMenuItem.Click += сохранитьПдфToolStripMenuItem_Click;
|
||||
//
|
||||
// удалитьtoolStripMenuItem
|
||||
//
|
||||
удалитьtoolStripMenuItem.Name = "удалитьtoolStripMenuItem";
|
||||
удалитьtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.D;
|
||||
удалитьtoolStripMenuItem.Size = new Size(254, 24);
|
||||
удалитьtoolStripMenuItem.Text = "Удалить";
|
||||
удалитьtoolStripMenuItem.Click += удалитьToolStripMenuItem_Click;
|
||||
//
|
||||
// редактироватьtoolStripMenuItem
|
||||
//
|
||||
редактироватьtoolStripMenuItem.Name = "редактироватьtoolStripMenuItem";
|
||||
редактироватьtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.U;
|
||||
редактироватьtoolStripMenuItem.Size = new Size(254, 24);
|
||||
редактироватьtoolStripMenuItem.Text = "Редактировать";
|
||||
редактироватьtoolStripMenuItem.Click += редактироватьToolStripMenuItem_Click;
|
||||
//
|
||||
// добавитьtoolStripMenuItem
|
||||
//
|
||||
добавитьtoolStripMenuItem.Name = "добавитьtoolStripMenuItem";
|
||||
добавитьtoolStripMenuItem.ShortcutKeys = Keys.Control | Keys.A;
|
||||
добавитьtoolStripMenuItem.Size = new Size(254, 24);
|
||||
добавитьtoolStripMenuItem.Text = "Добавить";
|
||||
добавитьtoolStripMenuItem.Click += добавитьToolStripMenuItem_Click;
|
||||
//
|
||||
// справочникtoolStripMenuItem
|
||||
//
|
||||
справочникtoolStripMenuItem.Name = "справочникtoolStripMenuItem";
|
||||
справочникtoolStripMenuItem.Size = new Size(254, 24);
|
||||
справочникtoolStripMenuItem.Text = "Справочник";
|
||||
справочникtoolStripMenuItem.Click += справочникToolStripMenuItem_Click;
|
||||
//
|
||||
// FormProducts
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(914, 600);
|
||||
Controls.Add(controlDataTableRow1);
|
||||
Margin = new Padding(3, 4, 3, 4);
|
||||
Name = "FormProducts";
|
||||
Text = "Form1";
|
||||
Load += FormProducts_Load;
|
||||
contextMenuStrip1.ResumeLayout(false);
|
||||
ResumeLayout(false);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private ControlsLibraryNet60.Data.ControlDataTableRow controlDataTableRow1;
|
||||
private ContextMenuStrip contextMenuStrip1;
|
||||
private ToolStripMenuItem сохранитьВордtoolStripMenuItem;
|
||||
private ToolStripMenuItem сохранитьЭксельtoolStripMenuItem;
|
||||
private ToolStripMenuItem сохранитьПдфtoolStripMenuItem;
|
||||
private ToolStripMenuItem удалитьtoolStripMenuItem;
|
||||
private ToolStripMenuItem редактироватьtoolStripMenuItem;
|
||||
private ToolStripMenuItem добавитьtoolStripMenuItem;
|
||||
private ToolStripMenuItem справочникtoolStripMenuItem;
|
||||
private WinFormsLibrary1.PdfWithImages pdfWithImages1;
|
||||
private ComponentsLibraryNet60.DocumentWithTable.ComponentDocumentWithTableHeaderRowExcel componentDocumentWithTableHeaderRowExcel1;
|
||||
private ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord componentDocumentWithChartBarWord1;
|
||||
}
|
||||
}
|
250
ShopProducts/FormProducts.cs
Normal file
250
ShopProducts/FormProducts.cs
Normal file
@ -0,0 +1,250 @@
|
||||
using ComponentsLibraryNet60.Models;
|
||||
using Contracts.BindingModels;
|
||||
using Contracts.BusinessLogicContracts;
|
||||
using Contracts.ViewModels;
|
||||
using ControlsLibraryNet60.Models;
|
||||
using DocumentFormat.OpenXml.Drawing.Charts;
|
||||
using WinFormsLibrary1.Configs.Image;
|
||||
|
||||
namespace ShopProducts
|
||||
{
|
||||
public partial class FormProducts : Form
|
||||
{
|
||||
private readonly IProductLogic _productLogic;
|
||||
public FormProducts(IProductLogic productLogic)
|
||||
{
|
||||
InitializeComponent();
|
||||
_productLogic = productLogic;
|
||||
controlDataTableRow1.ContextMenuStrip = contextMenuStrip1;
|
||||
InitTable();
|
||||
}
|
||||
|
||||
private void InitTable()
|
||||
{
|
||||
var tableConfig = new List<DataTableColumnConfig>
|
||||
{
|
||||
new DataTableColumnConfig
|
||||
{
|
||||
ColumnHeader = "Id",
|
||||
PropertyName = "Id",
|
||||
Visible = false
|
||||
},
|
||||
new DataTableColumnConfig
|
||||
{
|
||||
ColumnHeader = "Name",
|
||||
PropertyName = "Name",
|
||||
Visible = true
|
||||
},
|
||||
new DataTableColumnConfig
|
||||
{
|
||||
ColumnHeader = "Manufacturers",
|
||||
PropertyName = "Manufacturers",
|
||||
Visible = true
|
||||
},
|
||||
new DataTableColumnConfig
|
||||
{
|
||||
ColumnHeader = "Delivery date",
|
||||
PropertyName = "DeliveryDate",
|
||||
Visible = true
|
||||
}
|
||||
};
|
||||
|
||||
controlDataTableRow1.LoadColumns(tableConfig);
|
||||
}
|
||||
|
||||
private void LoadData()
|
||||
{
|
||||
try
|
||||
{
|
||||
controlDataTableRow1.Clear();
|
||||
|
||||
var list = _productLogic.Read(null);
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
controlDataTableRow1.AddRow(list[i]);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
private void FormProducts_Load(object sender, EventArgs e)
|
||||
{
|
||||
LoadData();
|
||||
}
|
||||
private void AddNewElement()
|
||||
{
|
||||
var service = Program.ServiceProvider?.GetService(typeof(FormProduct));
|
||||
if (service is FormProduct form)
|
||||
{
|
||||
if (form.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
LoadData();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void UpdateElement()
|
||||
{
|
||||
var selectedProduct = controlDataTableRow1.GetSelectedObject<ProductViewModel>();
|
||||
if (selectedProduct != null)
|
||||
{
|
||||
var service = Program.ServiceProvider?.GetService(typeof(FormProduct));
|
||||
if (service is FormProduct form)
|
||||
{
|
||||
form.Id = Convert.ToInt32(selectedProduct.Id);
|
||||
if (form.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
LoadData();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Âûáåðèòå êëèåíòà äëÿ ðåäàêòèðîâàíèÿ");
|
||||
}
|
||||
}
|
||||
|
||||
private void DeleteElement()
|
||||
{
|
||||
if (MessageBox.Show("Óäàëèòü çàïèñü", "Âîïðîñ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
var selectedProduct = controlDataTableRow1.GetSelectedObject<ProductViewModel>();
|
||||
try
|
||||
{
|
||||
int id = Convert.ToInt32(selectedProduct.Id);
|
||||
_productLogic.Delete(new ProductBindingModel { Id = id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
LoadData();
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateWord()
|
||||
{
|
||||
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
|
||||
{
|
||||
saveFileDialog.Filter = "Word Document (*.docx)|*.docx";
|
||||
saveFileDialog.Title = "Ñîõðàíèòü Word ôàéë";
|
||||
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
var data = _productLogic.GetWordInfo();
|
||||
componentDocumentWithChartBarWord1.CreateDoc(new ComponentDocumentWithChartConfig
|
||||
{
|
||||
FilePath = saveFileDialog.FileName,
|
||||
Header = "Ãèñòîãðàììà ïðîäóêòîâ",
|
||||
ChartTitle = "Êîë-âî ïðîäóêöèè ïî ïðîèçâîäèòåëþ",
|
||||
LegendLocation = ComponentsLibraryNet60.Models.Location.Bottom,
|
||||
Data = new Dictionary<string, List<(int Date, double Value)>>
|
||||
{
|
||||
{ "TTT", data }
|
||||
}
|
||||
});
|
||||
|
||||
MessageBox.Show("Word óñïåøíî ñîçäàí!", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateExcel()
|
||||
{
|
||||
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
|
||||
{
|
||||
saveFileDialog.Filter = "Excel Workbook (*.xlsx)|*.xlsx";
|
||||
saveFileDialog.Title = "Ñîõðàíèòü Excel ôàéë";
|
||||
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
var list = _productLogic.Read(null);
|
||||
componentDocumentWithTableHeaderRowExcel1.CreateDoc(new ComponentDocumentWithTableHeaderDataConfig<ProductViewModel>
|
||||
{
|
||||
FilePath = saveFileDialog.FileName,
|
||||
Header = "Ïðîäóêòû",
|
||||
UseUnion = true,
|
||||
ColumnsRowsWidth = new List<(int, int)> { (5, 0), (10, 0), (10, 0), (10, 0) },
|
||||
ColumnUnion = new List<(int StartIndex, int Count)> { (1, 2) },
|
||||
Headers = new List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)>
|
||||
{
|
||||
(0, 0, "ID", "Id"),
|
||||
(1, 0, "Ïðîäóêò", ""),
|
||||
(1, 1, "Íàçâàíèå", "Name"),
|
||||
(2, 1, "Ïðîèçâîäèòåëü", "Manufacturers"),
|
||||
(3, 0, "Äàòà ïîñòàâêè", "DeliveryDate"),
|
||||
},
|
||||
Data = list
|
||||
});
|
||||
|
||||
MessageBox.Show("Excel óñïåøíî ñîçäàí!", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void CreatePdf()
|
||||
{
|
||||
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
|
||||
{
|
||||
saveFileDialog.Filter = "PDF Document (*.pdf)|*.pdf";
|
||||
saveFileDialog.Title = "Ñîõðàíèòü PDF ôàéë";
|
||||
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
var productImages = _productLogic.Read(null).Select(p => p.Image).ToList();
|
||||
var config = new PdfWithImageConfig
|
||||
{
|
||||
FilePath = saveFileDialog.FileName,
|
||||
Header = "Äîêóìåíò ñ èçîáðàæåíèÿìè",
|
||||
Images = productImages
|
||||
};
|
||||
pdfWithImages1.CreatePdf(config);
|
||||
MessageBox.Show("PDF óñïåøíî ñîçäàí!", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void ñîõðàíèòüÂîðäToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
CreateWord();
|
||||
}
|
||||
|
||||
private void ñîõðàíèòüÝêñåëüToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
CreateExcel();
|
||||
}
|
||||
|
||||
private void ñîõðàíèòüÏäôToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
CreatePdf();
|
||||
}
|
||||
|
||||
private void óäàëèòüToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
DeleteElement();
|
||||
}
|
||||
|
||||
private void ðåäàêòèðîâàòüToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
UpdateElement();
|
||||
}
|
||||
|
||||
private void äîáàâèòüToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
AddNewElement();
|
||||
}
|
||||
|
||||
private void ñïðàâî÷íèêToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
var service = Program.ServiceProvider?.GetService(typeof(FormManufacturers));
|
||||
if (service is FormManufacturers form)
|
||||
{
|
||||
form.ShowDialog();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -117,7 +117,16 @@
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<metadata name="pdfWithImages1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<metadata name="contextMenuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
<metadata name="pdfWithImages1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>202, 17</value>
|
||||
</metadata>
|
||||
<metadata name="componentDocumentWithTableHeaderRowExcel1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>368, 17</value>
|
||||
</metadata>
|
||||
<metadata name="componentDocumentWithChartBarWord1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 58</value>
|
||||
</metadata>
|
||||
</root>
|
44
ShopProducts/Program.cs
Normal file
44
ShopProducts/Program.cs
Normal file
@ -0,0 +1,44 @@
|
||||
using BusinessLogic;
|
||||
using Contracts.BusinessLogicContracts;
|
||||
using Contracts.StorageContracts;
|
||||
using DatabaseImplement.Implements;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ShopProducts
|
||||
{
|
||||
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<FormProducts>());
|
||||
}
|
||||
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddLogging(option =>
|
||||
{
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
});
|
||||
services.AddTransient<IProductStorage, ProductStorage>();
|
||||
services.AddTransient<IManufacturerStorage, ManufacturerStorage>();
|
||||
services.AddTransient<IProductLogic, ProductLogic>();
|
||||
services.AddTransient<IManufacturerLogic, ManufacturerLogic>();
|
||||
services.AddTransient<FormProducts>();
|
||||
services.AddTransient<FormProduct>();
|
||||
services.AddTransient<FormManufacturers>();
|
||||
}
|
||||
}
|
||||
}
|
27
ShopProducts/ShopProducts.csproj
Normal file
27
ShopProducts/ShopProducts.csproj
Normal file
@ -0,0 +1,27 @@
|
||||
<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="ComponentsLibraryNet60" Version="1.0.0" />
|
||||
<PackageReference Include="ControlsLibraryNet60" Version="1.0.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="6.0.33">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="WinFormsLibrary1" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\BusinessLogic\BusinessLogic.csproj" />
|
||||
<ProjectReference Include="..\Contracts\Contracts.csproj" />
|
||||
<ProjectReference Include="..\DatabaseImplement\DatabaseImplement.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
334
WinFormsApp1/Form1.Designer.cs
generated
334
WinFormsApp1/Form1.Designer.cs
generated
@ -1,334 +0,0 @@
|
||||
namespace WinFormsApp1
|
||||
{
|
||||
partial class Form1
|
||||
{
|
||||
/// <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()
|
||||
{
|
||||
components = new System.ComponentModel.Container();
|
||||
customCheckedListBox = new WinFormsLibrary1.CustomCheckedListBox();
|
||||
addInListboxItemButton = new Button();
|
||||
clearListboxButton = new Button();
|
||||
listboxItemValuetextBox = new TextBox();
|
||||
getSelectedItemButton = new Button();
|
||||
selectedItemLabel = new Label();
|
||||
customTextBox = new WinFormsLibrary1.CustomTextBox();
|
||||
errorCustomTextBoxLabel = new Label();
|
||||
checkCustomTextBoxButton = new Button();
|
||||
customDataTree = new WinFormsLibrary1.CustomDataTree();
|
||||
label1 = new Label();
|
||||
nameTextBox = new TextBox();
|
||||
label2 = new Label();
|
||||
positionTextBox = new TextBox();
|
||||
label3 = new Label();
|
||||
addEmployeeButton = new Button();
|
||||
departamentComboBox = new ComboBox();
|
||||
getSelectedTreeItemButton = new Button();
|
||||
pdfWithImages1 = new WinFormsLibrary1.PdfWithImages(components);
|
||||
listBoxImages = new ListBox();
|
||||
button1 = new Button();
|
||||
createPdfButton = new Button();
|
||||
pdfTableButton = new Button();
|
||||
pdfDiagramButton = new Button();
|
||||
SuspendLayout();
|
||||
//
|
||||
// customCheckedListBox
|
||||
//
|
||||
customCheckedListBox.Location = new Point(25, 9);
|
||||
customCheckedListBox.Margin = new Padding(3, 2, 3, 2);
|
||||
customCheckedListBox.Name = "customCheckedListBox";
|
||||
customCheckedListBox.SelectedElement = "";
|
||||
customCheckedListBox.Size = new Size(130, 156);
|
||||
customCheckedListBox.TabIndex = 0;
|
||||
//
|
||||
// addInListboxItemButton
|
||||
//
|
||||
addInListboxItemButton.Location = new Point(175, 35);
|
||||
addInListboxItemButton.Margin = new Padding(3, 2, 3, 2);
|
||||
addInListboxItemButton.Name = "addInListboxItemButton";
|
||||
addInListboxItemButton.Size = new Size(130, 28);
|
||||
addInListboxItemButton.TabIndex = 1;
|
||||
addInListboxItemButton.Text = "Add or select item";
|
||||
addInListboxItemButton.UseVisualStyleBackColor = true;
|
||||
addInListboxItemButton.Click += addInListboxItemButton_Click;
|
||||
//
|
||||
// clearListboxButton
|
||||
//
|
||||
clearListboxButton.Location = new Point(175, 68);
|
||||
clearListboxButton.Margin = new Padding(3, 2, 3, 2);
|
||||
clearListboxButton.Name = "clearListboxButton";
|
||||
clearListboxButton.Size = new Size(130, 28);
|
||||
clearListboxButton.TabIndex = 2;
|
||||
clearListboxButton.Text = "Clear listbox";
|
||||
clearListboxButton.UseVisualStyleBackColor = true;
|
||||
clearListboxButton.Click += clearListboxButton_Click;
|
||||
//
|
||||
// listboxItemValuetextBox
|
||||
//
|
||||
listboxItemValuetextBox.Location = new Point(175, 9);
|
||||
listboxItemValuetextBox.Margin = new Padding(3, 2, 3, 2);
|
||||
listboxItemValuetextBox.Name = "listboxItemValuetextBox";
|
||||
listboxItemValuetextBox.Size = new Size(131, 23);
|
||||
listboxItemValuetextBox.TabIndex = 3;
|
||||
//
|
||||
// getSelectedItemButton
|
||||
//
|
||||
getSelectedItemButton.Location = new Point(175, 125);
|
||||
getSelectedItemButton.Margin = new Padding(3, 2, 3, 2);
|
||||
getSelectedItemButton.Name = "getSelectedItemButton";
|
||||
getSelectedItemButton.Size = new Size(130, 32);
|
||||
getSelectedItemButton.TabIndex = 4;
|
||||
getSelectedItemButton.Text = "Get selected item";
|
||||
getSelectedItemButton.UseVisualStyleBackColor = true;
|
||||
getSelectedItemButton.Click += getSelectedItemButton_Click;
|
||||
//
|
||||
// selectedItemLabel
|
||||
//
|
||||
selectedItemLabel.AutoSize = true;
|
||||
selectedItemLabel.Location = new Point(175, 108);
|
||||
selectedItemLabel.Name = "selectedItemLabel";
|
||||
selectedItemLabel.Size = new Size(84, 15);
|
||||
selectedItemLabel.TabIndex = 5;
|
||||
selectedItemLabel.Text = "Selected item: ";
|
||||
//
|
||||
// customTextBox
|
||||
//
|
||||
customTextBox.Location = new Point(370, 9);
|
||||
customTextBox.Margin = new Padding(3, 2, 3, 2);
|
||||
customTextBox.MaxLength = 5;
|
||||
customTextBox.MinLength = 0;
|
||||
customTextBox.Name = "customTextBox";
|
||||
customTextBox.Size = new Size(208, 23);
|
||||
customTextBox.TabIndex = 6;
|
||||
customTextBox.Value = "";
|
||||
//
|
||||
// errorCustomTextBoxLabel
|
||||
//
|
||||
errorCustomTextBoxLabel.AutoSize = true;
|
||||
errorCustomTextBoxLabel.Location = new Point(370, 68);
|
||||
errorCustomTextBoxLabel.Name = "errorCustomTextBoxLabel";
|
||||
errorCustomTextBoxLabel.Size = new Size(0, 15);
|
||||
errorCustomTextBoxLabel.TabIndex = 7;
|
||||
//
|
||||
// checkCustomTextBoxButton
|
||||
//
|
||||
checkCustomTextBoxButton.Location = new Point(370, 35);
|
||||
checkCustomTextBoxButton.Margin = new Padding(3, 2, 3, 2);
|
||||
checkCustomTextBoxButton.Name = "checkCustomTextBoxButton";
|
||||
checkCustomTextBoxButton.Size = new Size(208, 28);
|
||||
checkCustomTextBoxButton.TabIndex = 8;
|
||||
checkCustomTextBoxButton.Text = "Check";
|
||||
checkCustomTextBoxButton.UseVisualStyleBackColor = true;
|
||||
checkCustomTextBoxButton.Click += checkCustomTextBoxButton_Click;
|
||||
//
|
||||
// customDataTree
|
||||
//
|
||||
customDataTree.Location = new Point(25, 189);
|
||||
customDataTree.Name = "customDataTree";
|
||||
customDataTree.Size = new Size(281, 193);
|
||||
customDataTree.TabIndex = 9;
|
||||
//
|
||||
// label1
|
||||
//
|
||||
label1.AutoSize = true;
|
||||
label1.Location = new Point(342, 277);
|
||||
label1.Name = "label1";
|
||||
label1.Size = new Size(39, 15);
|
||||
label1.TabIndex = 10;
|
||||
label1.Text = "Name";
|
||||
//
|
||||
// nameTextBox
|
||||
//
|
||||
nameTextBox.Location = new Point(343, 295);
|
||||
nameTextBox.Name = "nameTextBox";
|
||||
nameTextBox.Size = new Size(152, 23);
|
||||
nameTextBox.TabIndex = 11;
|
||||
//
|
||||
// label2
|
||||
//
|
||||
label2.AutoSize = true;
|
||||
label2.Location = new Point(342, 233);
|
||||
label2.Name = "label2";
|
||||
label2.Size = new Size(50, 15);
|
||||
label2.TabIndex = 12;
|
||||
label2.Text = "Position";
|
||||
//
|
||||
// positionTextBox
|
||||
//
|
||||
positionTextBox.Location = new Point(343, 251);
|
||||
positionTextBox.Name = "positionTextBox";
|
||||
positionTextBox.Size = new Size(152, 23);
|
||||
positionTextBox.TabIndex = 13;
|
||||
//
|
||||
// label3
|
||||
//
|
||||
label3.AutoSize = true;
|
||||
label3.Location = new Point(343, 189);
|
||||
label3.Name = "label3";
|
||||
label3.Size = new Size(76, 15);
|
||||
label3.TabIndex = 14;
|
||||
label3.Text = "Departament";
|
||||
//
|
||||
// addEmployeeButton
|
||||
//
|
||||
addEmployeeButton.Location = new Point(342, 324);
|
||||
addEmployeeButton.Name = "addEmployeeButton";
|
||||
addEmployeeButton.Size = new Size(152, 22);
|
||||
addEmployeeButton.TabIndex = 15;
|
||||
addEmployeeButton.Text = "Add employee";
|
||||
addEmployeeButton.UseVisualStyleBackColor = true;
|
||||
addEmployeeButton.Click += addEmployeeButton_Click;
|
||||
//
|
||||
// departamentComboBox
|
||||
//
|
||||
departamentComboBox.FormattingEnabled = true;
|
||||
departamentComboBox.Location = new Point(342, 207);
|
||||
departamentComboBox.Name = "departamentComboBox";
|
||||
departamentComboBox.Size = new Size(152, 23);
|
||||
departamentComboBox.TabIndex = 16;
|
||||
//
|
||||
// getSelectedTreeItemButton
|
||||
//
|
||||
getSelectedTreeItemButton.Location = new Point(342, 352);
|
||||
getSelectedTreeItemButton.Name = "getSelectedTreeItemButton";
|
||||
getSelectedTreeItemButton.Size = new Size(152, 30);
|
||||
getSelectedTreeItemButton.TabIndex = 17;
|
||||
getSelectedTreeItemButton.Text = "Get selected";
|
||||
getSelectedTreeItemButton.UseVisualStyleBackColor = true;
|
||||
getSelectedTreeItemButton.Click += getSelectedTreeItemButton_Click;
|
||||
//
|
||||
// listBoxImages
|
||||
//
|
||||
listBoxImages.FormattingEnabled = true;
|
||||
listBoxImages.ItemHeight = 15;
|
||||
listBoxImages.Location = new Point(25, 398);
|
||||
listBoxImages.Name = "listBoxImages";
|
||||
listBoxImages.Size = new Size(280, 124);
|
||||
listBoxImages.TabIndex = 18;
|
||||
//
|
||||
// button1
|
||||
//
|
||||
button1.Location = new Point(25, 528);
|
||||
button1.Name = "button1";
|
||||
button1.Size = new Size(139, 23);
|
||||
button1.TabIndex = 19;
|
||||
button1.Text = "Выбрать изображения";
|
||||
button1.UseVisualStyleBackColor = true;
|
||||
button1.Click += button1_Click;
|
||||
//
|
||||
// createPdfButton
|
||||
//
|
||||
createPdfButton.Location = new Point(170, 528);
|
||||
createPdfButton.Name = "createPdfButton";
|
||||
createPdfButton.Size = new Size(135, 23);
|
||||
createPdfButton.TabIndex = 20;
|
||||
createPdfButton.Text = "Создать PDF";
|
||||
createPdfButton.UseVisualStyleBackColor = true;
|
||||
createPdfButton.Click += createPdfButton_Click;
|
||||
//
|
||||
// pdfTableButton
|
||||
//
|
||||
pdfTableButton.Location = new Point(342, 398);
|
||||
pdfTableButton.Name = "pdfTableButton";
|
||||
pdfTableButton.Size = new Size(152, 23);
|
||||
pdfTableButton.TabIndex = 21;
|
||||
pdfTableButton.Text = "Создать таблицу в PDF";
|
||||
pdfTableButton.UseVisualStyleBackColor = true;
|
||||
pdfTableButton.Click += pdfTableButton_Click;
|
||||
//
|
||||
// pdfDiagramButton
|
||||
//
|
||||
pdfDiagramButton.Location = new Point(342, 427);
|
||||
pdfDiagramButton.Name = "pdfDiagramButton";
|
||||
pdfDiagramButton.Size = new Size(152, 23);
|
||||
pdfDiagramButton.TabIndex = 22;
|
||||
pdfDiagramButton.Text = "Создать диаграмму";
|
||||
pdfDiagramButton.UseVisualStyleBackColor = true;
|
||||
pdfDiagramButton.Click += pdfDiagramButton_Click;
|
||||
//
|
||||
// Form1
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(700, 566);
|
||||
Controls.Add(pdfDiagramButton);
|
||||
Controls.Add(pdfTableButton);
|
||||
Controls.Add(createPdfButton);
|
||||
Controls.Add(button1);
|
||||
Controls.Add(listBoxImages);
|
||||
Controls.Add(getSelectedTreeItemButton);
|
||||
Controls.Add(departamentComboBox);
|
||||
Controls.Add(addEmployeeButton);
|
||||
Controls.Add(label3);
|
||||
Controls.Add(positionTextBox);
|
||||
Controls.Add(label2);
|
||||
Controls.Add(nameTextBox);
|
||||
Controls.Add(label1);
|
||||
Controls.Add(customDataTree);
|
||||
Controls.Add(checkCustomTextBoxButton);
|
||||
Controls.Add(errorCustomTextBoxLabel);
|
||||
Controls.Add(customTextBox);
|
||||
Controls.Add(selectedItemLabel);
|
||||
Controls.Add(getSelectedItemButton);
|
||||
Controls.Add(listboxItemValuetextBox);
|
||||
Controls.Add(clearListboxButton);
|
||||
Controls.Add(addInListboxItemButton);
|
||||
Controls.Add(customCheckedListBox);
|
||||
Margin = new Padding(3, 2, 3, 2);
|
||||
Name = "Form1";
|
||||
Text = "Form1";
|
||||
ResumeLayout(false);
|
||||
PerformLayout();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private WinFormsLibrary1.CustomCheckedListBox customCheckedListBox;
|
||||
private Button addInListboxItemButton;
|
||||
private Button clearListboxButton;
|
||||
private TextBox listboxItemValuetextBox;
|
||||
private Button getSelectedItemButton;
|
||||
private Label selectedItemLabel;
|
||||
private WinFormsLibrary1.CustomTextBox customTextBox;
|
||||
private Label errorCustomTextBoxLabel;
|
||||
private Button checkCustomTextBoxButton;
|
||||
private WinFormsLibrary1.CustomDataTree customDataTree;
|
||||
private Label label1;
|
||||
private TextBox nameTextBox;
|
||||
private Label label2;
|
||||
private TextBox positionTextBox;
|
||||
private Label label3;
|
||||
private Button addEmployeeButton;
|
||||
private ComboBox departamentComboBox;
|
||||
private Button getSelectedTreeItemButton;
|
||||
private WinFormsLibrary1.PdfWithImages pdfWithImages1;
|
||||
private ListBox listBoxImages;
|
||||
private Button button1;
|
||||
private Button createPdfButton;
|
||||
private Button pdfTableButton;
|
||||
private Button pdfDiagramButton;
|
||||
}
|
||||
}
|
@ -1,233 +0,0 @@
|
||||
using System.Security.Cryptography.Xml;
|
||||
using WinFormsLibrary1;
|
||||
using WinFormsLibrary1.Configs.Diagram;
|
||||
using WinFormsLibrary1.Configs.Image;
|
||||
using WinFormsLibrary1.Models;
|
||||
using WinFormsLibrary1.Errors;
|
||||
using WinFormsLibrary1.Configs.Diagram;
|
||||
using WinFormsLibrary1.Configs.Table;
|
||||
using PdfSharp.Pdf.Content.Objects;
|
||||
|
||||
namespace WinFormsApp1
|
||||
{
|
||||
public partial class Form1 : Form
|
||||
{
|
||||
private PdfWithImages pdfWithImages = new PdfWithImages();
|
||||
private List<byte[]> selectedImages = new List<byte[]>();
|
||||
|
||||
private PdfWithTable pdfWithTable = new PdfWithTable();
|
||||
|
||||
private PdfWithDiagram pdfWithDiagram = new PdfWithDiagram();
|
||||
|
||||
public Form1()
|
||||
{
|
||||
InitializeComponent();
|
||||
FillCustomCheckedListBox();
|
||||
FillCustomDataTree();
|
||||
}
|
||||
|
||||
private void FillCustomCheckedListBox()
|
||||
{
|
||||
List<string> list = new List<string>() { "Çíà÷åíèå 1", "Çíà÷åíèå 2", "Çíà÷åíèå 3" };
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
customCheckedListBox.AddItem(list[i]);
|
||||
}
|
||||
}
|
||||
|
||||
private void FillCustomDataTree()
|
||||
{
|
||||
departamentComboBox.Items.Add("Îòäåë ïðîäàæ");
|
||||
departamentComboBox.Items.Add("Îòäåë àíàëèòèêè");
|
||||
departamentComboBox.Items.Add("IT îòäåë");
|
||||
|
||||
DataTreeNodeConfig config = new DataTreeNodeConfig(new List<string> { "Department", "Position", "Name" });
|
||||
customDataTree.LoadConfig(config);
|
||||
|
||||
List<Employee> employees = new List<Employee>
|
||||
{
|
||||
new Employee("Èâàíîâ Èâàí", "Ìåíåäæåð", "Îòäåë ïðîäàæ"),
|
||||
new Employee("Ïåòðîâ Ïåòð", "Àíàëèòèê", "Îòäåë àíàëèòèêè"),
|
||||
new Employee("Ñèäîðîâ Ñèäîð", "Ìåíåäæåð", "Îòäåë ïðîäàæ"),
|
||||
new Employee("Ìàðèÿ Ñìèðíîâà", "Ðàçðàáîò÷èê", "IT îòäåë"),
|
||||
new Employee("Îëüãà Ïåòðîâà", "Ìåíåäæåð", "Îòäåë ïðîäàæ"),
|
||||
};
|
||||
|
||||
foreach (var employee in employees)
|
||||
{
|
||||
customDataTree.AddObject(employee);
|
||||
}
|
||||
}
|
||||
|
||||
private void addInListboxItemButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
string value = listboxItemValuetextBox.Text;
|
||||
if (customCheckedListBox.Items.Contains(value)) customCheckedListBox.SelectedElement = value;
|
||||
else customCheckedListBox.AddItem(value);
|
||||
}
|
||||
|
||||
private void clearListboxButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
customCheckedListBox.Clear();
|
||||
}
|
||||
|
||||
private void getSelectedItemButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
string value = customCheckedListBox.SelectedElement;
|
||||
|
||||
if (value == string.Empty) selectedItemLabel.Text = "Selected item: ~empty value~";
|
||||
else selectedItemLabel.Text = "Selected item: " + value;
|
||||
}
|
||||
|
||||
private void checkCustomTextBoxButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
errorCustomTextBoxLabel.Text = customTextBox.Value == string.Empty ? "~empty value~" : customTextBox.Value;
|
||||
}
|
||||
catch (RangeNotSetException ex)
|
||||
{
|
||||
// Îáðàáàòûâàåì îøèáêó, åñëè äèàïàçîí íå çàäàí.
|
||||
MessageBox.Show(ex.Message, "Îøèáêà äèàïàçîíà", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
}
|
||||
catch (TextLengthOutOfRangeException ex)
|
||||
{
|
||||
// Îáðàáàòûâàåì îøèáêó, åñëè äëèíà òåêñòà âíå äèàïàçîíà.
|
||||
MessageBox.Show(ex.Message, "Îøèáêà äëèíû òåêñòà", MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
}
|
||||
}
|
||||
|
||||
private void addEmployeeButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (positionTextBox.Text == null || nameTextBox.Text == null || departamentComboBox.SelectedItem == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
customDataTree.AddObject<Employee>(new(nameTextBox.Text, positionTextBox.Text, departamentComboBox.SelectedItem.ToString()));
|
||||
customDataTree.Update();
|
||||
}
|
||||
|
||||
private void getSelectedTreeItemButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
Employee employee = customDataTree.GetSelectedObject<Employee>();
|
||||
if (employee == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
positionTextBox.Text = employee.Position;
|
||||
nameTextBox.Text = employee.Name;
|
||||
departamentComboBox.SelectedItem = employee.Department;
|
||||
}
|
||||
|
||||
// PDF WITH IMAGE
|
||||
private void button1_Click(object sender, EventArgs e)
|
||||
{
|
||||
using OpenFileDialog openFileDialog = new OpenFileDialog
|
||||
{
|
||||
Multiselect = true,
|
||||
Filter = "Èçîáðàæåíèÿ|*.jpg;*.jpeg;*.png;*.bmp"
|
||||
};
|
||||
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
// Î÷èùàåì ïðåäûäóùèå äàííûå
|
||||
selectedImages.Clear();
|
||||
listBoxImages.Items.Clear();
|
||||
|
||||
// Äîáàâëÿåì âûáðàííûå èçîáðàæåíèÿ â ñïèñîê
|
||||
foreach (string filePath in openFileDialog.FileNames)
|
||||
{
|
||||
selectedImages.Add(File.ReadAllBytes(filePath));
|
||||
listBoxImages.Items.Add(Path.GetFileName(filePath));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void createPdfButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (selectedImages.Count == 0)
|
||||
{
|
||||
MessageBox.Show("Âûáåðèòå õîòÿ áû îäíî èçîáðàæåíèå!", "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
// Êîíôèãóðàöèÿ äëÿ PDF-äîêóìåíòà
|
||||
var config = new PdfWithImageConfig
|
||||
{
|
||||
FilePath = "PdfWithImage.pdf",
|
||||
Header = "Äîêóìåíò ñ èçîáðàæåíèÿìè",
|
||||
Images = selectedImages
|
||||
};
|
||||
|
||||
// Ñîçäàíèå PDF ÷åðåç êîìïîíåíò
|
||||
pdfWithImages.CreatePdf(config);
|
||||
|
||||
MessageBox.Show("PDF óñïåøíî ñîçäàí!", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
|
||||
// PDF WITH TABLE
|
||||
private void pdfTableButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
PdfWithTableConfig<Human> config = new PdfWithTableConfig<Human>
|
||||
{
|
||||
FileName = "PdfWithTable.pdf",
|
||||
DocumentTitle = "Ïðèìåð Òàáëèöû",
|
||||
RowHeights = new List<double> { 1, 1, 1 },
|
||||
Headers = new Dictionary<string, List<string>>
|
||||
{
|
||||
{ "Ëè÷íûå äàííûå", new List<string> {"Èìÿ", "Ôàìèëèÿ"} },
|
||||
{ "Âîçðàñò", new List<string>() }
|
||||
},
|
||||
PropertiesPerRow = new List<string> { "Name", "Surname", "Age" },
|
||||
Data = new List<Human>
|
||||
{
|
||||
new Human("Èâàí", "Èâàíîâ", 30),
|
||||
new Human("Ïåòð", "Ïåòðîâ", 25),
|
||||
new Human("Ñåðãåé", "Ñåðãååâ", 35)
|
||||
}
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
// Âûçîâ ìåòîäà äëÿ ñîçäàíèÿ PDF
|
||||
pdfWithTable.CreatePdf(config);
|
||||
MessageBox.Show("PDF-äîêóìåíò óñïåøíî ñîçäàí!", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Îøèáêà ïðè ñîçäàíèè PDF: {ex.Message}", "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
}
|
||||
|
||||
// PDF TO DIAGRAM
|
||||
private void pdfDiagramButton_Click(object sender, EventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
pdfWithDiagram.CreateDoc(new PdfWithDiagramConfig
|
||||
{
|
||||
FilePath = "PdfWithPieDiagram.pdf",
|
||||
Header = "Çàãîëîâîê",
|
||||
ChartTitle = "Êðóãîâàÿ äèàãðàììà",
|
||||
LegendLocation = WinFormsLibrary1.Configs.Diagram.Location.Bottom,
|
||||
Data = new Dictionary<string, List<(string Name, double Value)>>
|
||||
{
|
||||
{
|
||||
"Product A", new List<(string Name, double Value)>
|
||||
{
|
||||
("1111", 30.0),
|
||||
("2", 20.0),
|
||||
("3", 50.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
MessageBox.Show("PDF äîêóìåíò ñ äèàãðàììîé ñîçäàí!", "Óñïåõ");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show($"Îøèáêà: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
namespace WinFormsApp1
|
||||
{
|
||||
internal static class Program
|
||||
{
|
||||
/// <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();
|
||||
Application.Run(new Form1());
|
||||
}
|
||||
}
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
<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>
|
||||
<ProjectReference Include="..\WinFormsLibrary1\WinFormsLibrary1.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
@ -1,31 +0,0 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.8.34525.116
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinFormsLibrary1", "WinFormsLibrary1\WinFormsLibrary1.csproj", "{349684DA-EAF6-4A22-AB7E-A98216AA5EA9}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinFormsApp1", "WinFormsApp1\WinFormsApp1.csproj", "{B0B10C32-032F-49CB-9ED6-70A0DEE05587}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{349684DA-EAF6-4A22-AB7E-A98216AA5EA9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{349684DA-EAF6-4A22-AB7E-A98216AA5EA9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{349684DA-EAF6-4A22-AB7E-A98216AA5EA9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{349684DA-EAF6-4A22-AB7E-A98216AA5EA9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{B0B10C32-032F-49CB-9ED6-70A0DEE05587}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{B0B10C32-032F-49CB-9ED6-70A0DEE05587}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{B0B10C32-032F-49CB-9ED6-70A0DEE05587}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{B0B10C32-032F-49CB-9ED6-70A0DEE05587}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {BC3841E0-E2BA-4201-9D85-36D4B65C22E5}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
@ -1,16 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WinFormsLibrary1.Configs.Diagram
|
||||
{
|
||||
public enum Location
|
||||
{
|
||||
Left,
|
||||
Right,
|
||||
Top,
|
||||
Bottom
|
||||
}
|
||||
}
|
@ -1,28 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WinFormsLibrary1.Configs.Diagram
|
||||
{
|
||||
public class PdfWithDiagramConfig
|
||||
{
|
||||
public string FilePath { get; set; }
|
||||
public string Header { get; set; }
|
||||
public string ChartTitle { get; set; }
|
||||
public Location LegendLocation { get; set; }
|
||||
public Dictionary<string, List<(string Name, double Value)>> Data { get; set; }
|
||||
|
||||
public void CheckFields()
|
||||
{
|
||||
if (string.IsNullOrEmpty(FilePath))
|
||||
throw new ArgumentNullException(nameof(FilePath), "File path cannot be null or empty.");
|
||||
if (string.IsNullOrEmpty(Header))
|
||||
throw new ArgumentNullException(nameof(Header), "Header cannot be null or empty.");
|
||||
if (Data == null || !Data.Any())
|
||||
throw new ArgumentNullException(nameof(Data), "Data cannot be null or empty.");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -1,23 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WinFormsLibrary1.Configs.Image
|
||||
{
|
||||
public class PdfWithImageConfig
|
||||
{
|
||||
public string FilePath { get; set; }
|
||||
public string Header { get; set; }
|
||||
public List<byte[]> Images { get; set; }
|
||||
|
||||
public void CheckFields()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(FilePath) || string.IsNullOrWhiteSpace(Header) || Images == null || Images.Count == 0)
|
||||
{
|
||||
throw new ArgumentException("Все поля должны быть заполнены.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
@ -1,88 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WinFormsLibrary1.Configs.Table
|
||||
{
|
||||
public class PdfWithTableConfig<T>
|
||||
{
|
||||
/// <summary>
|
||||
/// Имя файла для сохранения PDF-документа.
|
||||
/// </summary>
|
||||
public string FileName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Заголовок документа PDF.
|
||||
/// </summary>
|
||||
public string DocumentTitle { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Список высот строк таблицы в виде массива двойных значений.
|
||||
/// </summary>
|
||||
public List<double> RowHeights { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Заголовки таблицы, где ключ - имя обобщающего столбца, а значение - список заголовков для соответствующего столбца.
|
||||
/// ВАЖНО: если строка не имеет обобщающего столбца, то заголовком будет ключ (список будет пустой)
|
||||
/// <code>
|
||||
/// var Headers = new Dictionary
|
||||
/// {
|
||||
/// {"Личные данные", new List("Имя", "Фамилия")},
|
||||
/// {"Возраст", new List()},
|
||||
/// }
|
||||
///
|
||||
/// ------------------------------
|
||||
/// | | Имя |
|
||||
/// | Личные данные |------------|
|
||||
/// | | Фамилия |
|
||||
/// |----------------------------|
|
||||
/// | Возраст |
|
||||
/// ------------------------------
|
||||
/// </code>
|
||||
/// </summary>
|
||||
public Dictionary<string, List<string>> Headers { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Список названий свойств, соответствующих данным, которые будут отображаться в строках таблицы.
|
||||
/// </summary>
|
||||
public List<string> PropertiesPerRow { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Данные для заполнения таблицы, представляющие собой список объектов типа T.
|
||||
/// </summary>
|
||||
public List<T> Data { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Проверяет корректность полей конфигурации.
|
||||
/// Вызывает исключение, если какое-либо поле не соответствует требованиям.
|
||||
/// </summary>
|
||||
public void CheckFields()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(FileName))
|
||||
throw new ArgumentException("Имя файла не может быть пустым.", nameof(FileName));
|
||||
|
||||
if (string.IsNullOrWhiteSpace(DocumentTitle))
|
||||
throw new ArgumentException("Название документа не может быть пустым.", nameof(DocumentTitle));
|
||||
|
||||
if (Headers == null || Headers.Count == 0)
|
||||
throw new ArgumentException("Заголовки для шапки не могут быть пустыми.", nameof(Headers));
|
||||
|
||||
if (Data == null || Data.Count == 0)
|
||||
throw new ArgumentException("Данные для таблицы не могут быть пустыми.", nameof(Data));
|
||||
|
||||
if (RowHeights == null || RowHeights.Count == 0)
|
||||
throw new ArgumentException("Высоты строк не могут быть пустыми.", nameof(RowHeights));
|
||||
|
||||
if (PropertiesPerRow.Any(string.IsNullOrWhiteSpace))
|
||||
throw new ArgumentException("Список названий свойств не может содержать пустые строки.", nameof(PropertiesPerRow));
|
||||
|
||||
if (RowHeights.Count != PropertiesPerRow.Count)
|
||||
throw new ArgumentException("Количество высот строк должно соответствовать количеству названий свойств.", nameof(RowHeights));
|
||||
|
||||
if (Data.Count != PropertiesPerRow.Count)
|
||||
throw new ArgumentException("Количество данных должно соответствовать количеству названий свойств.", nameof(Data));
|
||||
}
|
||||
}
|
||||
}
|
59
WinFormsLibrary1/CustomCheckedListBox.Designer.cs
generated
59
WinFormsLibrary1/CustomCheckedListBox.Designer.cs
generated
@ -1,59 +0,0 @@
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
partial class CustomCheckedListBox
|
||||
{
|
||||
/// <summary>
|
||||
/// Обязательная переменная конструктора.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Освободить все используемые ресурсы.
|
||||
/// </summary>
|
||||
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Код, автоматически созданный конструктором компонентов
|
||||
|
||||
/// <summary>
|
||||
/// Требуемый метод для поддержки конструктора — не изменяйте
|
||||
/// содержимое этого метода с помощью редактора кода.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
checkedListBox = new CheckedListBox();
|
||||
SuspendLayout();
|
||||
//
|
||||
// checkedListBox
|
||||
//
|
||||
checkedListBox.Dock = DockStyle.Fill;
|
||||
checkedListBox.FormattingEnabled = true;
|
||||
checkedListBox.Location = new Point(0, 0);
|
||||
checkedListBox.Name = "checkedListBox";
|
||||
checkedListBox.Size = new Size(281, 235);
|
||||
checkedListBox.TabIndex = 0;
|
||||
checkedListBox.ItemCheck += checkedListBox_ItemCheck;
|
||||
checkedListBox.SelectedIndexChanged += checkedListBox_SelectedIndexChanged;
|
||||
//
|
||||
// CustomCheckedListBox
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
Controls.Add(checkedListBox);
|
||||
Name = "CustomCheckedListBox";
|
||||
Size = new Size(281, 235);
|
||||
ResumeLayout(false);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private CheckedListBox checkedListBox;
|
||||
}
|
||||
}
|
@ -1,80 +0,0 @@
|
||||
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 WinFormsLibrary1
|
||||
{
|
||||
public partial class CustomCheckedListBox : UserControl
|
||||
{
|
||||
public CheckedListBox.ObjectCollection Items => checkedListBox.Items;
|
||||
private EventHandler _changeEvent;
|
||||
public CustomCheckedListBox()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
checkedListBox.Items.Clear();
|
||||
}
|
||||
|
||||
public string SelectedElement
|
||||
{
|
||||
get
|
||||
{
|
||||
if (checkedListBox.SelectedIndex > -1 && checkedListBox.GetItemChecked(checkedListBox.SelectedIndex))
|
||||
{
|
||||
return checkedListBox.SelectedItem.ToString();
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (checkedListBox.Items.Contains(value))
|
||||
{
|
||||
checkedListBox.SelectedItem = value;
|
||||
checkedListBox.SetItemChecked(checkedListBox.Items.IndexOf(value), true);
|
||||
}
|
||||
}
|
||||
}
|
||||
private void checkedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
|
||||
{
|
||||
if (e.NewValue == CheckState.Checked && checkedListBox.CheckedItems.Count > 0)
|
||||
{
|
||||
checkedListBox.ItemCheck -= checkedListBox_ItemCheck;
|
||||
checkedListBox.SetItemChecked(checkedListBox.CheckedIndices[0], value: false);
|
||||
checkedListBox.ItemCheck += checkedListBox_ItemCheck;
|
||||
}
|
||||
}
|
||||
public void AddItem(string item)
|
||||
{
|
||||
if (item == string.Empty) return;
|
||||
checkedListBox.Items.Add(item);
|
||||
}
|
||||
private void checkedListBox_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
_changeEvent?.Invoke(sender, e);
|
||||
}
|
||||
|
||||
// Cобытие, вызываемое при смене значения
|
||||
public event EventHandler ChangeEvent
|
||||
{
|
||||
add
|
||||
{
|
||||
_changeEvent += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
_changeEvent -= value;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
55
WinFormsLibrary1/CustomDataTree.Designer.cs
generated
55
WinFormsLibrary1/CustomDataTree.Designer.cs
generated
@ -1,55 +0,0 @@
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
partial class CustomDataTree
|
||||
{
|
||||
/// <summary>
|
||||
/// Обязательная переменная конструктора.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Освободить все используемые ресурсы.
|
||||
/// </summary>
|
||||
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Код, автоматически созданный конструктором компонентов
|
||||
|
||||
/// <summary>
|
||||
/// Требуемый метод для поддержки конструктора — не изменяйте
|
||||
/// содержимое этого метода с помощью редактора кода.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
treeView = new TreeView();
|
||||
SuspendLayout();
|
||||
//
|
||||
// treeView
|
||||
//
|
||||
treeView.Dock = DockStyle.Fill;
|
||||
treeView.Location = new Point(0, 0);
|
||||
treeView.Name = "treeView";
|
||||
treeView.Size = new Size(150, 150);
|
||||
treeView.TabIndex = 0;
|
||||
//
|
||||
// CustomDataTree
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(7F, 15F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
Controls.Add(treeView);
|
||||
Name = "CustomDataTree";
|
||||
ResumeLayout(false);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private TreeView treeView;
|
||||
}
|
||||
}
|
@ -1,114 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
public partial class CustomDataTree : UserControl
|
||||
{
|
||||
// Публичное свойство для установки и получения иерархии
|
||||
protected DataTreeNodeConfig Levels { get; set; }
|
||||
public CustomDataTree()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
treeView.Nodes.Clear();
|
||||
}
|
||||
|
||||
public void LoadConfig(DataTreeNodeConfig levels)
|
||||
{
|
||||
if (levels != null)
|
||||
{
|
||||
Levels = levels;
|
||||
}
|
||||
}
|
||||
|
||||
// Публичный метод для получения выбранной записи (для конечного элемента дерева)
|
||||
public T GetSelectedObject<T>() where T : class, new()
|
||||
{
|
||||
if (treeView.SelectedNode == null || Levels == null || treeView.SelectedNode.Nodes.Count > 0)
|
||||
{
|
||||
// сделать ошибки
|
||||
return null;
|
||||
}
|
||||
|
||||
T val = new T();
|
||||
|
||||
TreeNode currentNode = treeView.SelectedNode;
|
||||
int levelIndex = Levels.NodeNames.Count - 1;
|
||||
|
||||
while (currentNode != null && levelIndex >= 0)
|
||||
{
|
||||
// имя свойства
|
||||
string nodeName = Levels.NodeNames[levelIndex];
|
||||
string value = currentNode.Text;
|
||||
|
||||
// Получаем свойство по имени и устанавливаем его значение
|
||||
PropertyInfo property = val.GetType().GetProperty(nodeName);
|
||||
property?.SetValue(val, Convert.ChangeType(value, property.PropertyType));
|
||||
|
||||
// Переходим к родительскому узлу
|
||||
currentNode = currentNode.Parent;
|
||||
levelIndex--;
|
||||
}
|
||||
|
||||
// Если не прошли все уровни
|
||||
if (levelIndex >= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return val;
|
||||
}
|
||||
|
||||
|
||||
// Метод для добавления объекта в TreeView
|
||||
public void AddObject<T>(T element)
|
||||
{
|
||||
if (Levels == null || element == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
TreeNodeCollection currentNodeCollection = treeView.Nodes;
|
||||
|
||||
for (int i = 0; i < Levels.NodeNames.Count; i++)
|
||||
{
|
||||
string nodeName = Levels.NodeNames[i];
|
||||
PropertyInfo property = element.GetType().GetProperty(nodeName);
|
||||
if (property == null) continue;
|
||||
|
||||
string nodeValue = property.GetValue(element, null)?.ToString() ?? nodeName;
|
||||
|
||||
// Проверяем, существует ли уже ветка с таким именем
|
||||
TreeNode existingNode = null;
|
||||
foreach (TreeNode node in currentNodeCollection)
|
||||
{
|
||||
if (node.Text == nodeValue)
|
||||
{
|
||||
existingNode = node;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Если ветка не существует
|
||||
if (existingNode == null)
|
||||
{
|
||||
existingNode = currentNodeCollection.Add(nodeValue);
|
||||
}
|
||||
|
||||
currentNodeCollection = existingNode.Nodes;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
58
WinFormsLibrary1/CustomTextBox.Designer.cs
generated
58
WinFormsLibrary1/CustomTextBox.Designer.cs
generated
@ -1,58 +0,0 @@
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
partial class CustomTextBox
|
||||
{
|
||||
/// <summary>
|
||||
/// Обязательная переменная конструктора.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Освободить все используемые ресурсы.
|
||||
/// </summary>
|
||||
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Код, автоматически созданный конструктором компонентов
|
||||
|
||||
/// <summary>
|
||||
/// Требуемый метод для поддержки конструктора — не изменяйте
|
||||
/// содержимое этого метода с помощью редактора кода.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
textBox = new TextBox();
|
||||
SuspendLayout();
|
||||
//
|
||||
// textBox
|
||||
//
|
||||
textBox.Dock = DockStyle.Fill;
|
||||
textBox.Location = new Point(0, 0);
|
||||
textBox.Name = "textBox";
|
||||
textBox.Size = new Size(93, 27);
|
||||
textBox.TabIndex = 0;
|
||||
textBox.TextChanged += textBox1_TextChanged;
|
||||
//
|
||||
// CustomTextBox
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
Controls.Add(textBox);
|
||||
Name = "CustomTextBox";
|
||||
Size = new Size(93, 21);
|
||||
ResumeLayout(false);
|
||||
PerformLayout();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private TextBox textBox;
|
||||
}
|
||||
}
|
@ -1,66 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using WinFormsLibrary1.Errors;
|
||||
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
|
||||
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
public partial class CustomTextBox : UserControl
|
||||
{
|
||||
public int? MinLength { get; set; } = null;
|
||||
public int? MaxLength { get; set; } = null;
|
||||
|
||||
public event EventHandler ValueChanged;
|
||||
|
||||
public string Value
|
||||
{
|
||||
get
|
||||
{
|
||||
if (MinLength == null || MaxLength == null)
|
||||
throw new RangeNotSetException();
|
||||
|
||||
if (textBox.Text.Length < MinLength || textBox.Text.Length > MaxLength)
|
||||
throw new TextLengthOutOfRangeException(MinLength ?? -1, MaxLength ?? -1);
|
||||
|
||||
return textBox.Text;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (MinLength == null || MaxLength == null
|
||||
|| textBox.Text.Length < MinLength || textBox.Text.Length > MaxLength)
|
||||
return;
|
||||
|
||||
textBox.Text = value;
|
||||
}
|
||||
}
|
||||
|
||||
public string CheckValue(string v)
|
||||
{
|
||||
if (MinLength == null || MaxLength == null)
|
||||
throw new RangeNotSetException();
|
||||
|
||||
if (v.Length < MinLength || v.Length > MaxLength)
|
||||
throw new TextLengthOutOfRangeException(MinLength ?? -1, MaxLength ?? -1);
|
||||
|
||||
return v;
|
||||
|
||||
}
|
||||
|
||||
public CustomTextBox()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void textBox1_TextChanged(object sender, EventArgs e)
|
||||
{
|
||||
ValueChanged?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,120 +0,0 @@
|
||||
<?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>
|
@ -1,18 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
public class DataTreeNodeConfig
|
||||
{
|
||||
public List<string> NodeNames { get; set; } = new List<string>();
|
||||
|
||||
public DataTreeNodeConfig(List<string> nodeNames, bool alwaysCreateNewBranch = false)
|
||||
{
|
||||
NodeNames = nodeNames;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,13 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WinFormsLibrary1.Errors
|
||||
{
|
||||
public class RangeNotSetException : Exception
|
||||
{
|
||||
public RangeNotSetException() : base("Диапазон длины текста не задан.") { }
|
||||
}
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WinFormsLibrary1.Errors
|
||||
{
|
||||
public class TextLengthOutOfRangeException : Exception
|
||||
{
|
||||
public int MinLength { get; }
|
||||
public int MaxLength { get; }
|
||||
|
||||
public TextLengthOutOfRangeException(int minLength, int maxLength) : base($"Длина текста не входит в заданный диапазон [{minLength}, {maxLength}].")
|
||||
{
|
||||
MinLength = minLength;
|
||||
MaxLength = maxLength;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WinFormsLibrary1.Models
|
||||
{
|
||||
public class Employee
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public string Position { get; set; }
|
||||
public string Department { get; set; }
|
||||
public Employee() { }
|
||||
public Employee(string name, string position, string department)
|
||||
{
|
||||
Name = name;
|
||||
Position = position;
|
||||
Department = department;
|
||||
}
|
||||
}
|
||||
}
|
@ -1,22 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace WinFormsLibrary1.Models
|
||||
{
|
||||
public class Human
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public string Surname { get; set; }
|
||||
public int Age { get; set; }
|
||||
public Human() { }
|
||||
public Human(string name, string surname, int age)
|
||||
{
|
||||
Name = name;
|
||||
Surname = surname;
|
||||
Age = age;
|
||||
}
|
||||
}
|
||||
}
|
36
WinFormsLibrary1/PdfWithDiagram.Designer.cs
generated
36
WinFormsLibrary1/PdfWithDiagram.Designer.cs
generated
@ -1,36 +0,0 @@
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
partial class PdfWithDiagram
|
||||
{
|
||||
/// <summary>
|
||||
/// Обязательная переменная конструктора.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Освободить все используемые ресурсы.
|
||||
/// </summary>
|
||||
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Код, автоматически созданный конструктором компонентов
|
||||
|
||||
/// <summary>
|
||||
/// Требуемый метод для поддержки конструктора — не изменяйте
|
||||
/// содержимое этого метода с помощью редактора кода.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
components = new System.ComponentModel.Container();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
@ -1,117 +0,0 @@
|
||||
using MigraDoc.DocumentObjectModel.Shapes;
|
||||
using MigraDoc.DocumentObjectModel;
|
||||
using MigraDoc.Rendering;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using MigraDoc.DocumentObjectModel.Shapes.Charts;
|
||||
using WinFormsLibrary1.Configs.Diagram;
|
||||
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
public partial class PdfWithDiagram : Component
|
||||
{
|
||||
public PdfWithDiagram()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public PdfWithDiagram(IContainer container)
|
||||
{
|
||||
container.Add(this);
|
||||
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private Document _document;
|
||||
private Chart _chart;
|
||||
|
||||
private Document Document
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_document == null)
|
||||
{
|
||||
_document = new Document();
|
||||
}
|
||||
return _document;
|
||||
}
|
||||
}
|
||||
|
||||
public void CreateHeader(string header)
|
||||
{
|
||||
var section = Document.AddSection();
|
||||
var paragraph = section.AddParagraph(header);
|
||||
paragraph.Format.Font.Color = Colors.Black;
|
||||
paragraph.Format.Font.Bold = true;
|
||||
}
|
||||
|
||||
private void ConfigChart(PdfWithDiagramConfig config)
|
||||
{
|
||||
((Shape)_chart).Width = Unit.FromCentimeter(16.0);
|
||||
((Shape)_chart).Height = Unit.FromCentimeter(12.0);
|
||||
_chart.TopArea.AddParagraph(config.ChartTitle);
|
||||
_chart.XAxis.MajorTickMark = (TickMarkType)2;
|
||||
_chart.YAxis.MajorTickMark = (TickMarkType)2;
|
||||
_chart.YAxis.HasMajorGridlines = true;
|
||||
_chart.PlotArea.LineFormat.Width = new Unit(1);
|
||||
_chart.PlotArea.LineFormat.Visible = true;
|
||||
switch (config.LegendLocation)
|
||||
{
|
||||
case Location.Left:
|
||||
_chart.LeftArea.AddLegend();
|
||||
break;
|
||||
case Location.Right:
|
||||
_chart.RightArea.AddLegend();
|
||||
break;
|
||||
case Location.Top:
|
||||
_chart.TopArea.AddLegend();
|
||||
break;
|
||||
case Location.Bottom:
|
||||
_chart.BottomArea.AddLegend();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void CreatePieChart(PdfWithDiagramConfig config)
|
||||
{
|
||||
_chart = new Chart(ChartType.Pie2D);
|
||||
foreach (var kvp in config.Data)
|
||||
{
|
||||
Series series = _chart.SeriesCollection.AddSeries();
|
||||
series.Name = kvp.Key;
|
||||
series.Add(kvp.Value.Select(x => x.Value).ToArray()); // Используем Value для данных
|
||||
}
|
||||
_chart.XValues.AddXSeries().Add(config.Data.First().Value.Select(x => x.Name).ToArray()); // Используем Date для оси X
|
||||
ConfigChart(config);
|
||||
}
|
||||
|
||||
public void SaveDoc(string filepath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(filepath))
|
||||
throw new ArgumentNullException(nameof(filepath), "File path cannot be null or empty.");
|
||||
if (_document == null)
|
||||
throw new ArgumentNullException(nameof(_document), "Document is not created.");
|
||||
if (_chart != null)
|
||||
_document.LastSection.Add(_chart);
|
||||
PdfDocumentRenderer documentRenderer = new PdfDocumentRenderer(true)
|
||||
{
|
||||
Document = _document
|
||||
};
|
||||
documentRenderer.RenderDocument();
|
||||
documentRenderer.PdfDocument.Save(filepath);
|
||||
}
|
||||
|
||||
public void CreateDoc(PdfWithDiagramConfig config)
|
||||
{
|
||||
config.CheckFields();
|
||||
CreateHeader(config.Header);
|
||||
CreatePieChart(config);
|
||||
SaveDoc(config.FilePath);
|
||||
}
|
||||
}
|
||||
}
|
36
WinFormsLibrary1/PdfWithImages.Designer.cs
generated
36
WinFormsLibrary1/PdfWithImages.Designer.cs
generated
@ -1,36 +0,0 @@
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
partial class PdfWithImages
|
||||
{
|
||||
/// <summary>
|
||||
/// Обязательная переменная конструктора.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Освободить все используемые ресурсы.
|
||||
/// </summary>
|
||||
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Код, автоматически созданный конструктором компонентов
|
||||
|
||||
/// <summary>
|
||||
/// Требуемый метод для поддержки конструктора — не изменяйте
|
||||
/// содержимое этого метода с помощью редактора кода.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
components = new System.ComponentModel.Container();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
@ -1,177 +0,0 @@
|
||||
using MigraDoc.DocumentObjectModel;
|
||||
using MigraDoc.Rendering;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using WinFormsLibrary1.Configs.Image;
|
||||
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
public partial class PdfWithImages : Component
|
||||
{
|
||||
private Document _document = null;
|
||||
|
||||
private Section _section = null;
|
||||
|
||||
private List<byte[]> _images = null;
|
||||
|
||||
private Document Document
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_document == null)
|
||||
{
|
||||
_document = new Document();
|
||||
}
|
||||
|
||||
return _document;
|
||||
}
|
||||
}
|
||||
|
||||
private Section Section
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_section == null)
|
||||
{
|
||||
_section = Document.AddSection();
|
||||
}
|
||||
|
||||
return _section;
|
||||
}
|
||||
}
|
||||
|
||||
private List<byte[]> Images
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_images == null)
|
||||
{
|
||||
_images = new List<byte[]>();
|
||||
}
|
||||
|
||||
return _images;
|
||||
}
|
||||
}
|
||||
public PdfWithImages()
|
||||
{
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public PdfWithImages(IContainer container)
|
||||
{
|
||||
container.Add(this);
|
||||
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
|
||||
InitializeComponent();
|
||||
}
|
||||
public void CreatePdf(PdfWithImageConfig config)
|
||||
{
|
||||
config.CheckFields();
|
||||
CreateHeader(config.Header);
|
||||
foreach (var image in config.Images)
|
||||
{
|
||||
CreateImage(image);
|
||||
}
|
||||
|
||||
SavePdf(config.FilePath);
|
||||
}
|
||||
|
||||
public void CreateHeader(string header)
|
||||
{
|
||||
var paragraph = Section.AddParagraph(header);
|
||||
paragraph.Format.Font.Name = "Arial";
|
||||
paragraph.Format.Font.Bold = true;
|
||||
paragraph.Format.Font.Size = 20;
|
||||
paragraph.Format.SpaceAfter = 10;
|
||||
}
|
||||
|
||||
public void SavePdf(string filepath)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(filepath))
|
||||
{
|
||||
throw new ArgumentNullException("Имя файла не задано");
|
||||
}
|
||||
|
||||
if (_document == null || _section == null)
|
||||
{
|
||||
throw new ArgumentNullException("Документ не сформирован, сохранять нечего");
|
||||
}
|
||||
|
||||
var pdfRenderer = new PdfDocumentRenderer(true)
|
||||
{
|
||||
Document = _document,
|
||||
};
|
||||
pdfRenderer.RenderDocument();
|
||||
pdfRenderer.Save(filepath);
|
||||
}
|
||||
|
||||
public void CreateImage(byte[] image)
|
||||
{
|
||||
if (image == null || image.Length == 0)
|
||||
{
|
||||
throw new ArgumentNullException("Картинка не загружена");
|
||||
}
|
||||
|
||||
Images.Add(image);
|
||||
|
||||
var imageFileName = Path.GetTempFileName();
|
||||
File.WriteAllBytes(imageFileName, image);
|
||||
|
||||
var img = Section.AddImage(imageFileName);
|
||||
img.Width = Unit.FromCentimeter(15); // Можно настроить ширину изображения
|
||||
img.LockAspectRatio = true;
|
||||
Section.AddParagraph();
|
||||
|
||||
|
||||
|
||||
|
||||
/*if (image == null || image.Length == 0)
|
||||
{
|
||||
throw new ArgumentNullException("Картинка не загружена");
|
||||
}
|
||||
|
||||
Images.Add(image);
|
||||
|
||||
// Создаём временный файл
|
||||
var imageFileName = Path.GetTempFileName();
|
||||
File.WriteAllBytes(imageFileName, image);
|
||||
|
||||
// Открываем изображение и проверяем его ориентацию
|
||||
using (var img = System.Drawing.Image.FromFile(imageFileName))
|
||||
{
|
||||
// Проверяем ориентацию и вращаем, если необходимо
|
||||
if (Array.IndexOf(img.PropertyIdList, 274) > -1)
|
||||
{
|
||||
var orientation = (int)img.GetPropertyItem(274).Value[0];
|
||||
switch (orientation)
|
||||
{
|
||||
case 3: // Переворот на 180 градусов
|
||||
img.RotateFlip(RotateFlipType.Rotate180FlipNone);
|
||||
break;
|
||||
case 6: // Поворот на 90 градусов вправо
|
||||
img.RotateFlip(RotateFlipType.Rotate90FlipNone);
|
||||
break;
|
||||
case 8: // Поворот на 90 градусов влево
|
||||
img.RotateFlip(RotateFlipType.Rotate270FlipNone);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Сохраняем отредактированное изображение
|
||||
img.Save(imageFileName);
|
||||
}
|
||||
|
||||
// Вставляем изображение в PDF
|
||||
var pdfImage = Section.AddImage(imageFileName);
|
||||
pdfImage.Width = Unit.FromCentimeter(15); // Можно настроить ширину изображения
|
||||
pdfImage.LockAspectRatio = true;
|
||||
|
||||
// Добавляем пустую строку после изображения
|
||||
Section.AddParagraph();*/
|
||||
}
|
||||
}
|
||||
}
|
36
WinFormsLibrary1/PdfWithTable.Designer.cs
generated
36
WinFormsLibrary1/PdfWithTable.Designer.cs
generated
@ -1,36 +0,0 @@
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
partial class PdfWithTable
|
||||
{
|
||||
/// <summary>
|
||||
/// Обязательная переменная конструктора.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Освободить все используемые ресурсы.
|
||||
/// </summary>
|
||||
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Код, автоматически созданный конструктором компонентов
|
||||
|
||||
/// <summary>
|
||||
/// Требуемый метод для поддержки конструктора — не изменяйте
|
||||
/// содержимое этого метода с помощью редактора кода.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
components = new System.ComponentModel.Container();
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
@ -1,110 +0,0 @@
|
||||
using MigraDoc.DocumentObjectModel;
|
||||
using MigraDoc.DocumentObjectModel.IO;
|
||||
using MigraDoc.DocumentObjectModel.Tables;
|
||||
using MigraDoc.Rendering;
|
||||
using PdfSharp.Pdf;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using WinFormsLibrary1.Configs.Table;
|
||||
|
||||
namespace WinFormsLibrary1
|
||||
{
|
||||
public partial class PdfWithTable : Component
|
||||
{
|
||||
public void CreatePdf<T>(PdfWithTableConfig<T> config)
|
||||
{
|
||||
config.CheckFields();
|
||||
|
||||
// Создание документа
|
||||
var document = new Document();
|
||||
var section = document.AddSection();
|
||||
|
||||
// Установка заголовка
|
||||
var titleParagraph = section.AddParagraph(config.DocumentTitle);
|
||||
titleParagraph.Format.Alignment = ParagraphAlignment.Center;
|
||||
titleParagraph.Format.Font.Size = 16;
|
||||
titleParagraph.Format.Font.Bold = true;
|
||||
titleParagraph.Format.SpaceAfter = 20;
|
||||
|
||||
// Создание таблицы
|
||||
var table = section.AddTable();
|
||||
table.Borders.Width = 0.75;
|
||||
|
||||
// Создание столбцов
|
||||
for (int i = 0; i < config.Data.Count + 2; i++)
|
||||
{
|
||||
var column = table.AddColumn(Unit.FromCentimeter(3)); // Ширину можно настроить
|
||||
column.Format.Alignment = ParagraphAlignment.Center;
|
||||
}
|
||||
|
||||
// Создание заголовков
|
||||
for (int rowIndex = 0; rowIndex < config.PropertiesPerRow.Count; rowIndex++)
|
||||
{
|
||||
var row = table.AddRow();
|
||||
row.Height = Unit.FromCentimeter(config.RowHeights[rowIndex]); // Высота строки
|
||||
|
||||
foreach (Cell cell in row.Cells)
|
||||
{
|
||||
cell.VerticalAlignment = VerticalAlignment.Center;
|
||||
cell.Format.Alignment = ParagraphAlignment.Center;
|
||||
}
|
||||
}
|
||||
|
||||
int rowNum = 0;
|
||||
foreach (var kvp in config.Headers)
|
||||
{
|
||||
string key = kvp.Key;
|
||||
List<string> values = kvp.Value;
|
||||
|
||||
if (values.Count == 0)
|
||||
{
|
||||
table.Rows[rowNum].Cells[0].AddParagraph(key);
|
||||
table.Rows[rowNum].Cells[0].MergeRight = 1;
|
||||
rowNum++;
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
table.Rows[rowNum].Cells[0].AddParagraph(key);
|
||||
table.Rows[rowNum].Cells[0].MergeDown = values.Count - 1;
|
||||
|
||||
foreach (var value in values)
|
||||
{
|
||||
table.Rows[rowNum].Cells[1].AddParagraph(value);
|
||||
rowNum++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
for (int colIndex = 0; colIndex < config.Data.Count; colIndex++)
|
||||
{
|
||||
for (int rowIndex = 0; rowIndex < config.PropertiesPerRow.Count; rowIndex++)
|
||||
{
|
||||
Type type = typeof(T);
|
||||
PropertyInfo property = type.GetProperty(config.PropertiesPerRow[rowIndex]);
|
||||
|
||||
if (property == null)
|
||||
{
|
||||
throw new ArgumentException($"Property with name {config.PropertiesPerRow[rowIndex]} doesn't exist in class {type.Name}");
|
||||
}
|
||||
|
||||
table.Rows[rowIndex].Cells[colIndex + 2].AddParagraph(property.GetValue(config.Data[colIndex]).ToString());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Рендеринг документа в PDF
|
||||
var pdfRenderer = new PdfDocumentRenderer(true)
|
||||
{
|
||||
Document = document
|
||||
};
|
||||
pdfRenderer.RenderDocument();
|
||||
pdfRenderer.PdfDocument.Save(config.FileName);
|
||||
}
|
||||
}
|
||||
}
|
@ -1,15 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
Loading…
Reference in New Issue
Block a user