Compare commits

...

17 Commits
main ... lab4

Author SHA1 Message Date
ityurner02@mail.ru
9ecf656150 ЛР4 2023-10-31 22:44:35 +04:00
ityurner02@mail.ru
f882b814ab лр3 сдана) 2023-10-28 09:02:31 +04:00
ityurner02@mail.ru
e37edd505a лр3 похоже готова 2023-10-27 20:29:38 +04:00
ityurner02@mail.ru
d25940be9c все круды и 1/3 документов работают 2023-10-26 22:26:41 +04:00
ityurner02@mail.ru
ce203b3ffa продвигаюсь помаленьку 2023-10-25 23:06:54 +04:00
ityurner02@mail.ru
21b0c10895 Слои логики, котрактов и хранения 2023-10-24 22:46:56 +04:00
ityurner02@mail.ru
ea707ec754 лаба2 сдано 2023-10-14 10:57:08 +04:00
ityurner02@mail.ru
bb355ba8d4 3 компонент готов, остался 2 2023-10-11 21:23:26 +04:00
ityurner02@mail.ru
708c818336 маленькое изменение 2023-10-11 18:28:46 +04:00
ityurner02@mail.ru
4ff7ba2931 первый компонент 2023-10-11 17:32:36 +04:00
ityurner02@mail.ru
7e39d424c7 Смена библиотеки 2023-09-28 20:53:57 +04:00
ityurner02@mail.ru
65deacff8e сдано 2023-09-16 11:05:11 +04:00
ityurner02@mail.ru
17102989ae вроде все 2023-09-15 22:21:56 +04:00
ityurner02@mail.ru
2a817ffd5d похоже 2 компонент готов 2023-09-15 21:10:27 +04:00
ityurner02@mail.ru
96c441c7aa 1 компонент 2023-09-15 19:31:01 +04:00
ityurner02@mail.ru
a292f7107d потихоньку 2023-09-15 15:37:37 +04:00
ityurner02@mail.ru
7f4a5d287c начало 1 лабораторной 2023-09-13 19:40:06 +04:00
120 changed files with 4245 additions and 54 deletions

View File

@ -3,7 +3,19 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.7.34031.279 VisualStudioVersion = 17.7.34031.279
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinForms", "WinForms\WinForms.csproj", "{237F8689-B952-4E4B-AA51-71F3021838BF}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinForms", "WinForms\WinForms.csproj", "{237F8689-B952-4E4B-AA51-71F3021838BF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VisualCompLib", "VisualCompLib\VisualCompLib.csproj", "{FC1CFC63-5739-4519-B689-E8B614A9D106}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClientsContracts", "ClientsContracts\ClientsContracts.csproj", "{849DCBC2-7B2D-43A5-87BD-CFE9BC4F0B6C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClientBusinessLogic", "ClientBusinessLogic\ClientBusinessLogic.csproj", "{6A4A31E6-F956-4312-B63D-807ABF5CD63E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClientsDatabaseImplement", "ClientsDatabaseImplement\ClientsDatabaseImplement.csproj", "{662252C6-5C66-43CD-8D94-5360E2761EB6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Plugins", "Plugins\Plugins.csproj", "{02FB0192-28B9-480A-B38B-5AC41BB4141F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinFormsByPlugins", "WinFormsByPlugins\WinFormsByPlugins.csproj", "{37D75819-DB6E-4FD5-808D-B424058C4F02}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -15,6 +27,30 @@ Global
{237F8689-B952-4E4B-AA51-71F3021838BF}.Debug|Any CPU.Build.0 = Debug|Any CPU {237F8689-B952-4E4B-AA51-71F3021838BF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{237F8689-B952-4E4B-AA51-71F3021838BF}.Release|Any CPU.ActiveCfg = Release|Any CPU {237F8689-B952-4E4B-AA51-71F3021838BF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{237F8689-B952-4E4B-AA51-71F3021838BF}.Release|Any CPU.Build.0 = Release|Any CPU {237F8689-B952-4E4B-AA51-71F3021838BF}.Release|Any CPU.Build.0 = Release|Any CPU
{FC1CFC63-5739-4519-B689-E8B614A9D106}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FC1CFC63-5739-4519-B689-E8B614A9D106}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FC1CFC63-5739-4519-B689-E8B614A9D106}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FC1CFC63-5739-4519-B689-E8B614A9D106}.Release|Any CPU.Build.0 = Release|Any CPU
{849DCBC2-7B2D-43A5-87BD-CFE9BC4F0B6C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{849DCBC2-7B2D-43A5-87BD-CFE9BC4F0B6C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{849DCBC2-7B2D-43A5-87BD-CFE9BC4F0B6C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{849DCBC2-7B2D-43A5-87BD-CFE9BC4F0B6C}.Release|Any CPU.Build.0 = Release|Any CPU
{6A4A31E6-F956-4312-B63D-807ABF5CD63E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6A4A31E6-F956-4312-B63D-807ABF5CD63E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6A4A31E6-F956-4312-B63D-807ABF5CD63E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6A4A31E6-F956-4312-B63D-807ABF5CD63E}.Release|Any CPU.Build.0 = Release|Any CPU
{662252C6-5C66-43CD-8D94-5360E2761EB6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{662252C6-5C66-43CD-8D94-5360E2761EB6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{662252C6-5C66-43CD-8D94-5360E2761EB6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{662252C6-5C66-43CD-8D94-5360E2761EB6}.Release|Any CPU.Build.0 = Release|Any CPU
{02FB0192-28B9-480A-B38B-5AC41BB4141F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{02FB0192-28B9-480A-B38B-5AC41BB4141F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{02FB0192-28B9-480A-B38B-5AC41BB4141F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{02FB0192-28B9-480A-B38B-5AC41BB4141F}.Release|Any CPU.Build.0 = Release|Any CPU
{37D75819-DB6E-4FD5-808D-B424058C4F02}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{37D75819-DB6E-4FD5-808D-B424058C4F02}.Debug|Any CPU.Build.0 = Debug|Any CPU
{37D75819-DB6E-4FD5-808D-B424058C4F02}.Release|Any CPU.ActiveCfg = Release|Any CPU
{37D75819-DB6E-4FD5-808D-B424058C4F02}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -0,0 +1,63 @@
using ClientsContracts.BindingModels;
using ClientsContracts.BusinessLogicContracts;
using ClientsContracts.StorageContracts;
using ClientsContracts.ViewModels;
namespace ClientBusinessLogic.BusinessLogics
{
public class ClientLogic : IClientLogic
{
private readonly IClientStorage _clientStorage;
public ClientLogic(IClientStorage clientStorage)
{
_clientStorage = clientStorage;
}
public void CreateOrUpdate(ClientBindingModel model)
{
var element = _clientStorage.GetElement(
new ClientBindingModel
{
Reviews = model.Reviews,
Name = model.Name,
Status = model.Status,
Amount = model.Amount
});
if (element != null && element.Id != model.Id)
{
throw new Exception("Клиент с таким именем уже существует");
}
if (model.Id.HasValue)
{
_clientStorage.Update(model);
}
else
{
_clientStorage.Insert(model);
}
}
public void Delete(ClientBindingModel model)
{
var element = _clientStorage.GetElement(new ClientBindingModel { Id = model.Id });
if (element == null)
{
throw new Exception("Клиент не найден");
}
_clientStorage.Delete(model);
}
public List<ClientViewModel> Read(ClientBindingModel model)
{
if (model == null)
{
return _clientStorage.GetFullList();
}
if (model.Id.HasValue)
{
return new List<ClientViewModel> { _clientStorage.GetElement(model) };
}
return _clientStorage.GetFilteredList(model);
}
}
}

View File

@ -0,0 +1,61 @@
using ClientsContracts.BindingModels;
using ClientsContracts.BusinessLogicContracts;
using ClientsContracts.StorageContracts;
using ClientsContracts.ViewModels;
namespace ClientBusinessLogic.BusinessLogics
{
public class StatusLogic : IStatusLogic
{
private readonly IStatusStorage _statusStorage;
public StatusLogic(IStatusStorage statusStorage)
{
_statusStorage = statusStorage;
}
public void CreateOrUpdate(StatusBindingModel model)
{
var element = _statusStorage.GetElement(
new StatusBindingModel
{
Name = model.Name
});
if (element != null && element.Id != model.Id)
{
throw new Exception("Такой статус уже существует");
}
if (model.Id.HasValue)
{
_statusStorage.Update(model);
}
else
{
_statusStorage.Insert(model);
}
}
public void Delete(StatusBindingModel model)
{
var element = _statusStorage.GetElement(new StatusBindingModel { Id = model.Id });
if (element == null)
{
throw new Exception("Статус не найден");
}
_statusStorage.Delete(model);
}
public List<StatusViewModel> Read(StatusBindingModel model)
{
if (model == null)
{
return _statusStorage.GetFullList();
}
if (model.Id.HasValue)
{
return new List<StatusViewModel> { _statusStorage.GetElement(model) };
}
return _statusStorage.GetFilteredList(model);
}
}
}

View File

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

View File

@ -0,0 +1,15 @@
namespace ClientsContracts.BindingModels
{
public class ClientBindingModel
{
public int? Id { get; set; }
public string Name { get; set; }
public string Reviews { get; set; }
public string Status { get; set; }
public int? Amount { get; set; }
}
}

View File

@ -0,0 +1,9 @@
namespace ClientsContracts.BindingModels
{
public class StatusBindingModel
{
public int? Id { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,12 @@
using ClientsContracts.BindingModels;
using ClientsContracts.ViewModels;
namespace ClientsContracts.BusinessLogicContracts
{
public interface IClientLogic
{
List<ClientViewModel> Read(ClientBindingModel model);
void CreateOrUpdate(ClientBindingModel model);
void Delete(ClientBindingModel model);
}
}

View File

@ -0,0 +1,12 @@
using ClientsContracts.BindingModels;
using ClientsContracts.ViewModels;
namespace ClientsContracts.BusinessLogicContracts
{
public interface IStatusLogic
{
List<StatusViewModel> Read(StatusBindingModel model);
void CreateOrUpdate(StatusBindingModel model);
void Delete(StatusBindingModel model);
}
}

View File

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

View File

@ -0,0 +1,16 @@
using ClientsContracts.BindingModels;
using ClientsContracts.ViewModels;
namespace ClientsContracts.StorageContracts
{
public interface IClientStorage
{
List<ClientViewModel> GetFullList();
List<ClientViewModel> GetFilteredList(ClientBindingModel model);
ClientViewModel GetElement(ClientBindingModel model);
void Insert(ClientBindingModel model);
void Update(ClientBindingModel model);
void Delete(ClientBindingModel model);
}
}

View File

@ -0,0 +1,16 @@
using ClientsContracts.BindingModels;
using ClientsContracts.ViewModels;
namespace ClientsContracts.StorageContracts
{
public interface IStatusStorage
{
List<StatusViewModel> GetFullList();
List<StatusViewModel> GetFilteredList(StatusBindingModel model);
StatusViewModel GetElement(StatusBindingModel model);
void Insert(StatusBindingModel model);
void Update(StatusBindingModel model);
void Delete(StatusBindingModel model);
}
}

View File

@ -0,0 +1,19 @@
using System.ComponentModel;
namespace ClientsContracts.ViewModels
{
public class ClientViewModel
{
public int? Id { get; set; }
[DisplayName("ФИО")]
public string Name { get; set; }
[DisplayName("Отзывы")]
public string Reviews { get; set; }
[DisplayName("Статус")]
public string Status { get; set; }
[DisplayName("Сумма покупок")]
public string Amount { get; set; }
}
}

View File

@ -0,0 +1,9 @@
namespace ClientsContracts.ViewModels
{
public class StatusViewModel
{
public int? Id { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using Microsoft.EntityFrameworkCore;
using ClientsDatabaseImplement.Models;
namespace ClientsDatabaseImplement
{
public class ClientsDatabase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=ClientsDatabase;Username=postgres;Password=186qazwsx");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Client> Clients { set; get; }
public virtual DbSet<Status> Statuses { set; get; }
}
}

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.11" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ClientsContracts\ClientsContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,120 @@
using ClientsContracts.StorageContracts;
using ClientsContracts.BindingModels;
using ClientsContracts.ViewModels;
using ClientsDatabaseImplement.Models;
namespace ClientsDatabaseImplement.Implements
{
public class ClientStorage : IClientStorage
{
public void Delete(ClientBindingModel model)
{
var context = new ClientsDatabase();
var client = context.Clients.FirstOrDefault(rec => rec.Id == model.Id);
if (client != null)
{
context.Clients.Remove(client);
context.SaveChanges();
}
else
{
throw new Exception("Клиент не найден");
}
}
public ClientViewModel GetElement(ClientBindingModel model)
{
if (model == null)
{
return null;
}
using var context = new ClientsDatabase();
var client = context.Clients
.ToList()
.FirstOrDefault(rec => rec.Id == model.Id);
return client != null ? CreateModel(client) : null;
}
public List<ClientViewModel> GetFilteredList(ClientBindingModel model)
{
var context = new ClientsDatabase();
return context.Clients
.Where(client => client.Name.Contains(model.Name) && client.Status.Contains(model.Status))
.ToList()
.Select(CreateModel)
.ToList();
}
public List<ClientViewModel> GetFullList()
{
using (var context = new ClientsDatabase())
{
return context.Clients
.ToList()
.Select(CreateModel)
.ToList();
}
}
public void Insert(ClientBindingModel model)
{
var context = new ClientsDatabase();
var transaction = context.Database.BeginTransaction();
try
{
context.Clients.Add(CreateModel(model, new Client()));
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
public void Update(ClientBindingModel model)
{
var context = new ClientsDatabase();
var transaction = context.Database.BeginTransaction();
try
{
var client = context.Clients.FirstOrDefault(rec => rec.Id == model.Id);
if (client == null)
{
throw new Exception("Клиент не найден");
}
CreateModel(model, client);
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
private static Client CreateModel(ClientBindingModel model, Client client)
{
client.Amount = model.Amount;
client.Name = model.Name;
client.Status = model.Status;
client.Reviews = model.Reviews;
return client;
}
private ClientViewModel CreateModel(Client client)
{
return new ClientViewModel
{
Id = client.Id,
Amount = client.Amount.ToString(),
Name = client.Name,
Status = client.Status,
Reviews = client.Reviews
};
}
}
}

View File

@ -0,0 +1,115 @@
using ClientsContracts.StorageContracts;
using ClientsContracts.BindingModels;
using ClientsContracts.ViewModels;
using ClientsDatabaseImplement.Models;
namespace ClientsDatabaseImplement.Implements
{
public class StatusStorage : IStatusStorage
{
public void Delete(StatusBindingModel model)
{
var context = new ClientsDatabase();
var status = context.Statuses.FirstOrDefault(rec => rec.Id == model.Id);
if (status != null)
{
context.Statuses.Remove(status);
context.SaveChanges();
}
else
{
throw new Exception("Статус не найден");
}
}
public StatusViewModel GetElement(StatusBindingModel model)
{
if (model == null)
{
return null;
}
using var context = new ClientsDatabase();
var status = context.Statuses
.ToList()
.FirstOrDefault(rec => rec.Id == model.Id || rec.Name == model.Name);
return status != null ? CreateModel(status) : null;
}
public List<StatusViewModel> GetFilteredList(StatusBindingModel model)
{
if (model == null)
{
return null;
}
using var context = new ClientsDatabase();
return context.Statuses
.Where(rec => rec.Name.Contains(model.Name))
.Select(CreateModel)
.ToList();
}
public List<StatusViewModel> GetFullList()
{
using var context = new ClientsDatabase();
return context.Statuses
.Select(CreateModel)
.ToList();
}
public void Insert(StatusBindingModel model)
{
var context = new ClientsDatabase();
var transaction = context.Database.BeginTransaction();
try
{
context.Statuses.Add(CreateModel(model, new Status()));
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
public void Update(StatusBindingModel model)
{
var context = new ClientsDatabase();
var transaction = context.Database.BeginTransaction();
try
{
var status = context.Statuses.FirstOrDefault(rec => rec.Id == model.Id);
if (status == null)
{
throw new Exception("Статус не найден");
}
CreateModel(model, status);
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
private static Status CreateModel(StatusBindingModel model, Status status)
{
status.Name = model.Name;
return status;
}
private static StatusViewModel CreateModel(Status status)
{
return new StatusViewModel
{
Id = status.Id,
Name = status.Name
};
}
}
}

View File

@ -0,0 +1,75 @@
// <auto-generated />
using System;
using ClientsDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ClientsDatabaseImplement.Migrations
{
[DbContext(typeof(ClientsDatabase))]
[Migration("20231024184241_InitMigration")]
partial class InitMigration
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ClientsDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("Amount")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Reviews")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("ClientsDatabaseImplement.Models.Status", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Statuses");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,54 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ClientsDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitMigration : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Clients",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false),
Reviews = table.Column<string>(type: "text", nullable: false),
Status = table.Column<string>(type: "text", nullable: false),
Amount = table.Column<int>(type: "integer", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Clients", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Statuses",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Statuses", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Statuses");
}
}
}

View File

@ -0,0 +1,72 @@
// <auto-generated />
using System;
using ClientsDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace ClientsDatabaseImplement.Migrations
{
[DbContext(typeof(ClientsDatabase))]
partial class ClientsDatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.11")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("ClientsDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int?>("Amount")
.HasColumnType("integer");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Reviews")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Status")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Clients");
});
modelBuilder.Entity("ClientsDatabaseImplement.Models.Status", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Statuses");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,19 @@
using System.ComponentModel.DataAnnotations;
namespace ClientsDatabaseImplement.Models
{
public class Client
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Reviews { get; set; }
[Required]
public string Status { get; set; }
public int? Amount { get; set; }
}
}

View File

@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace ClientsDatabaseImplement.Models
{
public class Status
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
}

View File

@ -0,0 +1,16 @@
namespace Plugins
{
public interface IPluginsConvention
{
string PluginName { get; }
UserControl GetControl { get; }
PluginsConventionElement GetElement { get; }
Form GetForm(PluginsConventionElement element);
Form GetThesaurus();
bool DeleteElement(PluginsConventionElement element);
void ReloadData();
bool CreateSimpleDocument(PluginsConventionSaveDocument saveDocument);
bool CreateTableDocument(PluginsConventionSaveDocument saveDocument);
bool CreateChartDocument(PluginsConventionSaveDocument saveDocument);
}
}

View File

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

View File

@ -0,0 +1,7 @@
namespace Plugins
{
public class PluginsConventionElement
{
public Guid Id { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace Plugins
{
public class PluginsConventionSaveDocument
{
public string FileName { get; set; }
}
}

View File

@ -0,0 +1,25 @@
namespace VisualCompLib.Components.SupportClasses
{
public class BigTable<T>
{
public string FilePath = string.Empty;
public string DocumentTitle = string.Empty;
public List<ColumnDefinition> ColumnDefinitions;
public List<ColumnDefinition> ColumnDefinitions2;
public List<T> Data;
public List<int[]> MergedColumns;
public BigTable(string filePath, string documentTitle, List<ColumnDefinition> columnDefinitions, List<ColumnDefinition> columnDefinitions2, List<T> data, List<int[]> mergedColumns)
{
FilePath = filePath;
DocumentTitle = documentTitle;
ColumnDefinitions = columnDefinitions;
Data = data;
MergedColumns = mergedColumns;
ColumnDefinitions2 = columnDefinitions2;
}
}
}

View File

@ -0,0 +1,9 @@
namespace VisualCompLib.Components.SupportClasses
{
public class ColumnDefinition
{
public string Header;
public string PropertyName;
public double Weight;
}
}

View File

@ -0,0 +1,18 @@
namespace VisualCompLib.Components.SupportClasses
{
public class DataLineChart
{
public string NameSeries { get; set; } = string.Empty;
public string[] NameData { get; set; }
public double[] Data { get; set; }
public DataLineChart(string nameSeries, string[] nameData, double[] data)
{
NameSeries = nameSeries;
NameData = nameData;
Data = data;
}
}
}

View File

@ -0,0 +1,17 @@
namespace VisualCompLib.Components.SupportClasses.Enums
{
public enum EnumAreaLegend
{
None,
Left,
Top,
Right,
Bottom,
TopRight
}
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VisualCompLib.Components.SupportClasses
{
public class LargeText
{
public string FilePath = string.Empty;
public string DocumentTitle = string.Empty;
public string[] TextData;
public LargeText(string filePath, string documentTitle, string[] textData)
{
FilePath = filePath;
DocumentTitle = documentTitle;
TextData = textData;
}
}
}

View File

@ -0,0 +1,26 @@
using VisualCompLib.Components.SupportClasses.Enums;
namespace VisualCompLib.Components.SupportClasses
{
public class SimpleLineChart
{
public string FilePath = string.Empty;
public string FileHeader = string.Empty;
public string LineChartName = string.Empty;
public EnumAreaLegend AreaLegend;
public List<DataLineChart> DataList = new();
public SimpleLineChart(string filePath, string fileHeader, string lineChartName, EnumAreaLegend areaLegend, List<DataLineChart> dataList)
{
FilePath = filePath;
FileHeader = fileHeader;
LineChartName = lineChartName;
AreaLegend = areaLegend;
DataList = dataList;
}
}
}

View File

@ -0,0 +1,36 @@
namespace VisualCompLib.Components
{
partial class WordLineChart
{
/// <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
}
}

View File

@ -0,0 +1,84 @@
using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Drawing.Charts;
using System.ComponentModel;
using VisualCompLib.Components.SupportClasses;
namespace VisualCompLib.Components
{
public partial class WordLineChart : Component
{
public WordLineChart()
{
InitializeComponent();
}
public WordLineChart(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void AddLineChart(SimpleLineChart simpleLineChart)
{
if (!CheckData(simpleLineChart.DataList))
{
throw new Exception("Не данные заполнены");
}
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Aspose.Words.Font font = builder.Font;
font.Size = 24;
font.Bold = true;
font.Color = Color.Black;
font.Name = "Times New Roman";
ParagraphFormat paragraphFormat = builder.ParagraphFormat;
paragraphFormat.FirstLineIndent = 8;
paragraphFormat.SpaceAfter = 24;
paragraphFormat.Alignment = ParagraphAlignment.Center;
paragraphFormat.KeepTogether = true;
builder.Writeln(simpleLineChart.FileHeader);
Shape shape = builder.InsertChart(ChartType.Line, 500, 270);
Chart chart = shape.Chart;
chart.Title.Text = simpleLineChart.LineChartName;
ChartSeriesCollection seriesColl = chart.Series;
Console.WriteLine(seriesColl.Count);
seriesColl.Clear();
foreach (var data in simpleLineChart.DataList)
{
seriesColl.Add(data.NameSeries, data.NameData, data.Data );
}
ChartLegend legend = chart.Legend;
legend.Position = (LegendPosition)simpleLineChart.AreaLegend;
legend.Overlay = true;
doc.Save(simpleLineChart.FilePath);
}
static bool CheckData(List<DataLineChart> data)
{
foreach (var _data in data)
{
if (string.IsNullOrEmpty(_data.NameSeries) || string.IsNullOrEmpty(_data.NameData.ToString()) || string.IsNullOrEmpty(_data.Data.ToString()))
{
return false;
}
}
return true;
}
}
}

View File

@ -0,0 +1,36 @@
namespace VisualCompLib.Components
{
partial class WordTable
{
/// <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
}
}

View File

@ -0,0 +1,128 @@
using System.ComponentModel;
using VisualCompLib.Components.SupportClasses;
using Aspose.Words;
using Aspose.Words.Tables;
namespace VisualCompLib.Components
{
public partial class WordTable : Component
{
public WordTable()
{
InitializeComponent();
}
public WordTable(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateTable<T>(BigTable<T> bigTable)
{
if (bigTable.Data == null)
{
throw new ArgumentException("Не заданы все данные");
}
foreach (var columnDefinition in bigTable.ColumnDefinitions)
{
if (string.IsNullOrEmpty(columnDefinition.PropertyName))
{
throw new ArgumentException($"Не задано свойство столбца: {columnDefinition.Header}");
}
}
Document document = new Document();
DocumentBuilder builder = new DocumentBuilder(document);
Style titleStyle = builder.Document.Styles.Add(StyleType.Paragraph, "Title");
titleStyle.Font.Size = 16;
titleStyle.Font.Bold = true;
builder.ParagraphFormat.Style = titleStyle;
builder.Writeln(bigTable.DocumentTitle);
Table table = builder.StartTable();
foreach (var columnDefinition in bigTable.ColumnDefinitions)
{
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnDefinition.Weight);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write(columnDefinition.Header);
}
foreach (var mergedColumn in bigTable.MergedColumns)
{
int startCellIndex = mergedColumn[0];
int endCellIndex = mergedColumn[mergedColumn.Length - 1];
for (int i = startCellIndex; i <= endCellIndex; i++)
{
table.Rows[0].Cells[i].CellFormat.HorizontalMerge = CellMerge.First;
table.Rows[0].Cells[i].CellFormat.VerticalMerge = CellMerge.First;
}
for (int i = startCellIndex + 1; i <= endCellIndex; i++)
{
table.Rows[0].Cells[i].CellFormat.HorizontalMerge = CellMerge.Previous;
table.Rows[0].Cells[i].CellFormat.VerticalMerge = CellMerge.First;
}
}
builder.EndRow();
foreach (var columnDefinition2 in bigTable.ColumnDefinitions2)
{
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnDefinition2.Weight);
builder.Write(columnDefinition2.Header);
}
builder.EndRow();
int columnIndex;
foreach (var columnDefinition in bigTable.ColumnDefinitions)
{
string currentPropertyName = columnDefinition.PropertyName;
columnIndex = 0;
foreach (var columnDefinition2 in bigTable.ColumnDefinitions2)
{
string currentPropertyName1 = columnDefinition2.PropertyName;
if (currentPropertyName == currentPropertyName1)
{
table.Rows[0].Cells[columnIndex].CellFormat.VerticalMerge = CellMerge.First;
table.Rows[1].Cells[columnIndex].CellFormat.VerticalMerge = CellMerge.Previous;
}
columnIndex++;
}
}
foreach (var item in bigTable.Data)
{
foreach (var columnDefinition2 in bigTable.ColumnDefinitions2)
{
builder.InsertCell();
var propertyValue = item.GetType()
.GetProperty(columnDefinition2.PropertyName)?
.GetValue(item)?.ToString();
builder.Write(propertyValue ?? "");
}
builder.EndRow();
}
builder.EndTable();
document.Save(bigTable.FilePath);
}
}
}

View File

@ -0,0 +1,36 @@
namespace VisualCompLib.Components
{
partial class WordText
{
/// <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
}
}

View File

@ -0,0 +1,133 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
using System.ComponentModel;
using VisualCompLib.Components.SupportClasses;
namespace VisualCompLib.Components
{
public partial class WordText : Component
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
public WordText()
{
InitializeComponent();
}
public WordText(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateWordText(LargeText largeText)
{
if (string.IsNullOrEmpty(largeText.FilePath) || string.IsNullOrEmpty(largeText.DocumentTitle) || !CheckData(largeText.TextData))
{
throw new Exception("Не все данные заполнены");
}
_wordDocument = WordprocessingDocument.Create(largeText.FilePath, WordprocessingDocumentType.Document);
//вытаскиваем главную часть из вордовского документа
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
//генерируем тело основной части документа
_docBody = mainPart.Document.AppendChild(new Body());
_wordDocument.Close();
AddText(largeText);
}
private void AddText(LargeText largeText)
{
using (var document = WordprocessingDocument.Open(largeText.FilePath, true))
{
var doc = document.MainDocumentPart.Document;
#region Создание заголовка
ParagraphProperties paragraphProperties = new();
paragraphProperties.AppendChild(new Justification
{
Val = JustificationValues.Center
});
paragraphProperties.AppendChild(new Indentation());
Paragraph header = new();
header.AppendChild(paragraphProperties);
var docRun = new Run();
var properties = new RunProperties();
properties.AppendChild(new FontSize
{
Val = "48"
});
properties.AppendChild(new Bold());
docRun.AppendChild(properties);
docRun.AppendChild(new Text(largeText.DocumentTitle));
header.AppendChild(docRun);
doc.Body.Append(header);
#endregion
#region Создание текста
for (int i = 0; i < largeText.TextData.Length; i++)
{
ParagraphProperties paragraphProperties2 = new();
paragraphProperties2.AppendChild(new Justification
{
Val = JustificationValues.Both
});
paragraphProperties2.AppendChild(new Indentation());
Paragraph text = new();
text.AppendChild(paragraphProperties2);
var docRun2 = new Run();
var properties2 = new RunProperties();
properties2.AppendChild(new FontSize
{
Val = "24"
});
docRun2.AppendChild(properties2);
docRun2.AppendChild(new Text(largeText.TextData[i]));
text.AppendChild(docRun2);
doc.Body.Append(text);
}
#endregion
doc.Save();
}
}
bool CheckData(string[] data)
{
for (int i = 0; i < data.Length; i++)
{
if (string.IsNullOrEmpty(data[i])) return false;
}
return true;
}
}
}

View File

@ -0,0 +1,62 @@
namespace VisualCompLib
{
partial class MyDropDownList
{
/// <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()
{
dropDownList = new ComboBox();
SuspendLayout();
//
// dropDownList
//
dropDownList.DropDownStyle = ComboBoxStyle.DropDownList;
dropDownList.FormattingEnabled = true;
dropDownList.Location = new Point(3, 4);
dropDownList.Margin = new Padding(3, 4, 3, 4);
dropDownList.Name = "dropDownList";
dropDownList.Size = new Size(187, 28);
dropDownList.TabIndex = 0;
dropDownList.SelectedValueChanged += comboBox_SelectedValueChanged;
//
// MyDropDownList
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
AutoSize = true;
AutoSizeMode = AutoSizeMode.GrowAndShrink;
Controls.Add(dropDownList);
Margin = new Padding(3, 4, 3, 4);
Name = "MyDropDownList";
Size = new Size(193, 38);
ResumeLayout(false);
}
#endregion
private ComboBox dropDownList;
}
}

View File

@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace VisualCompLib
{
public partial class MyDropDownList : UserControl
{
public MyDropDownList()
{
InitializeComponent();
}
public void LoadValues(List<string> Values)
{
if (Values.Count == 0)
{
return;
}
dropDownList.Items.AddRange(Values.ToArray());
}
public void Clear()
{
dropDownList.Items.Clear();
}
public string SelectedValue
{
get
{
if (dropDownList.Items.Count == 0)
{
return "";
}
if (dropDownList.SelectedItem == null)
{
return "";
}
return dropDownList.SelectedItem.ToString();
}
set
{
if (dropDownList.Items.Contains(value))
{
dropDownList.SelectedItem = value;
}
}
}
private EventHandler onValueChanged;
public event EventHandler ValueChanged
{
add
{
onValueChanged += value;
}
remove
{
onValueChanged -= value;
}
}
private void comboBox_SelectedValueChanged(object sender, EventArgs e)
{
onValueChanged?.Invoke(sender, e);
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,59 @@
namespace VisualCompLib
{
partial class MyEmailTextBox
{
/// <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()
{
this.emailTextBox = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// emailTextBox
//
this.emailTextBox.Location = new System.Drawing.Point(3, 3);
this.emailTextBox.Name = "emailTextBox";
this.emailTextBox.Size = new System.Drawing.Size(170, 22);
this.emailTextBox.TabIndex = 0;
this.emailTextBox.TextChanged += new System.EventHandler(this.textBox_TextChanged);
this.emailTextBox.Enter += new System.EventHandler(this.textBox_Enter);
//
// MyEmailTextBox
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.emailTextBox);
this.Name = "MyEmailTextBox";
this.Size = new System.Drawing.Size(177, 30);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox emailTextBox;
}
}

View File

@ -0,0 +1,93 @@
using System;
using ToolTip = System.Windows.Forms.ToolTip;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Drawing;
namespace VisualCompLib
{
public partial class MyEmailTextBox : UserControl
{
//Шаблон для textbox
private string pattern;
//Пример ввода
private string example = "ti@gmail.com";
public MyEmailTextBox()
{
InitializeComponent();
}
public string Pattern
{
get { return pattern; }
set { pattern = value; }
}
public string TextBoxValue
{
get
{
Regex rg = new Regex(Pattern);
bool address = rg.IsMatch(emailTextBox.Text);
if (address)
{
return emailTextBox.Text;
}
else
{
Error = "Некорректный ввод";
return null;
}
}
set
{
Regex rg = new Regex(Pattern);
bool address = rg.IsMatch(value);
if (address)
{
emailTextBox.Text = value;
}
else
{
Error = "Некорректный ввод";
}
}
}
public string Error
{
get; private set;
}
public void setExample(string str)
{
Regex rg = new Regex(Pattern);
bool address = rg.IsMatch(str);
if (address)
{
example = str;
}
}
private void textBox_Enter(object sender, EventArgs e)
{
int VisibleTime = 2000; //ms
ToolTip tooltip = new ToolTip();
tooltip.Show(example, emailTextBox, 30, -20, VisibleTime);
}
private EventHandler onValueChanged;
public event EventHandler ValueChanged
{
add
{
onValueChanged += value;
}
remove
{
onValueChanged -= value;
}
}
private void textBox_TextChanged(object sender, EventArgs e)
{
onValueChanged?.Invoke(sender, e);
}
}
}

View File

@ -0,0 +1,59 @@
namespace VisualCompLib
{
partial class MyListBoxObjects
{
/// <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()
{
this.listBoxObj = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// listBoxObj
//
this.listBoxObj.FormattingEnabled = true;
this.listBoxObj.HorizontalScrollbar = true;
this.listBoxObj.ItemHeight = 16;
this.listBoxObj.Location = new System.Drawing.Point(3, 3);
this.listBoxObj.Name = "listBoxObj";
this.listBoxObj.Size = new System.Drawing.Size(353, 116);
this.listBoxObj.TabIndex = 0;
//
// MyListBoxObjects
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.listBoxObj);
this.Name = "MyListBoxObjects";
this.Size = new System.Drawing.Size(359, 133);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListBox listBoxObj;
}
}

View File

@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace VisualCompLib
{
public partial class MyListBoxObjects : UserControl
{
//Макетная строка
private string layoutString;
//начальный символ для обнаружения свойств/полей
private string startSymbol;
//конечный символ для обнаружения свойств/полей
private string endSymbol;
public MyListBoxObjects()
{
InitializeComponent();
}
//Метод для установки информации о макетной строке и символах (начального и конечного)
public void SetLayoutInfo(string layout, string startS, string endS)
{
if (layout == null || startS == null || endS == null)
{
return;
}
layoutString = layout;
startSymbol = startS;
endSymbol = endS;
}
//свойство для получения и заполнения индекса выбранного элемента
public int SelectedIndex
{
get
{
if (listBoxObj.SelectedIndex == -1)
{
return -1;
}
return listBoxObj.SelectedIndex;
}
set
{
if (listBoxObj.SelectedItems.Count != 0)
{
listBoxObj.SelectedIndex = value;
}
}
}
//Публичный параметризованный метод для получения объекта из выбранной строки(создать объект и через рефлексию заполнить свойства его).
public T GetObjectFromStr<T>() where T : class, new()
{
string selStr = "";
if (listBoxObj.SelectedIndex != -1)
{
selStr = listBoxObj.SelectedItem.ToString();
}
T curObject = new T();
foreach (var pr in typeof(T).GetProperties())
{
if (!pr.CanWrite)
{
continue;
}
int borderOne = selStr.IndexOf(startSymbol);
StringBuilder sb = new StringBuilder(selStr);
sb[borderOne] = 'z';
selStr = sb.ToString();
int borderTwo = selStr.IndexOf(endSymbol);
if (borderOne == -1 || borderTwo == -1) break;
string propertyValue = selStr.Substring(borderOne + 1, borderTwo - borderOne - 1);
selStr = selStr.Substring(borderTwo + 1);
pr.SetValue(curObject, Convert.ChangeType(propertyValue, pr.PropertyType));
}
return curObject;
}
//параметризованный метод, у которого в передаваемых параметрах идет список объектов некого класса и через этот список идет заполнение ListBox;
public void AddInListBox<T>(List<T> objects)
{
if (layoutString == null || startSymbol == null || endSymbol == null)
{
MessageBox.Show("заполните информацию о макетной строке");
return;
}
if (!layoutString.Contains(startSymbol) || !layoutString.Contains(endSymbol))
{
MessageBox.Show("Макетная строка не содержит нужные элементы");
return;
}
foreach (var item in objects)
{
string str = layoutString;
foreach (var prop in item.GetType().GetProperties())
{
string str1 = $"{startSymbol}" + $"{prop.Name}" + $"{endSymbol}";
str = str.Replace(str1, $"{startSymbol}" + prop.GetValue(item).ToString() + $"{endSymbol}");
}
listBoxObj.Items.Add(str);
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VisualCompLib.Object
{
public class Student
{
public string Name { get; set; }
public string Group { get; set; }
public string Faculty { get; set; }
public int Course { get; set; }
public Student(string name, string group, string faculty, int course)
{
Name = name;
Group = group;
Faculty = faculty;
Course = course;
}
public Student()
{
}
}
}

View File

@ -0,0 +1,29 @@
<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="Aspose.Words" Version="23.10.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="2.20.0" />
<PackageReference Include="FreeSpire.Doc" Version="11.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="MyDropDownList.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Update="MyEmailTextBox.cs">
<SubType>UserControl</SubType>
</Compile>
<Compile Update="MyListBoxObjects.cs">
<SubType>UserControl</SubType>
</Compile>
</ItemGroup>
</Project>

View File

@ -1,39 +0,0 @@
namespace WinForms
{
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()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

@ -1,10 +0,0 @@
namespace WinForms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}

183
COP/WinForms/FormClient.Designer.cs generated Normal file
View File

@ -0,0 +1,183 @@
using ControlsLibraryNet60.Input;
namespace WinForms
{
partial class FormClient
{
/// <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()
{
LabelFIO = new Label();
textBoxName = new TextBox();
label1 = new Label();
label2 = new Label();
textBoxReviews = new TextBox();
label3 = new Label();
buttonSave = new Button();
buttonCancel = new Button();
controlInputNullableInt1 = new ControlInputNullableInt();
myDropDownList1 = new VisualCompLib.MyDropDownList();
SuspendLayout();
//
// LabelFIO
//
LabelFIO.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
LabelFIO.AutoSize = true;
LabelFIO.Location = new Point(15, 13);
LabelFIO.Name = "LabelFIO";
LabelFIO.Size = new Size(42, 20);
LabelFIO.TabIndex = 0;
LabelFIO.Text = "ФИО";
//
// textBoxName
//
textBoxName.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxName.Location = new Point(15, 41);
textBoxName.Margin = new Padding(3, 4, 3, 4);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(244, 27);
textBoxName.TabIndex = 1;
//
// label1
//
label1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
label1.AutoSize = true;
label1.Location = new Point(14, 81);
label1.Name = "label1";
label1.Size = new Size(52, 20);
label1.TabIndex = 3;
label1.Text = "Статус";
//
// label2
//
label2.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
label2.AutoSize = true;
label2.Location = new Point(15, 148);
label2.Name = "label2";
label2.Size = new Size(63, 20);
label2.TabIndex = 4;
label2.Text = "Отзывы";
//
// textBoxReviews
//
textBoxReviews.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
textBoxReviews.Location = new Point(15, 175);
textBoxReviews.Margin = new Padding(3, 4, 3, 4);
textBoxReviews.Name = "textBoxReviews";
textBoxReviews.Size = new Size(244, 27);
textBoxReviews.TabIndex = 5;
//
// label3
//
label3.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
label3.AutoSize = true;
label3.Location = new Point(15, 212);
label3.Name = "label3";
label3.Size = new Size(116, 20);
label3.TabIndex = 7;
label3.Text = "Сумма покупок";
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSave.Location = new Point(14, 311);
buttonSave.Margin = new Padding(3, 4, 3, 4);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(243, 31);
buttonSave.TabIndex = 8;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonCancel.Location = new Point(14, 349);
buttonCancel.Margin = new Padding(3, 4, 3, 4);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(243, 31);
buttonCancel.TabIndex = 9;
buttonCancel.Text = "Отменить";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// controlInputNullableInt1
//
controlInputNullableInt1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
controlInputNullableInt1.Location = new Point(14, 240);
controlInputNullableInt1.Margin = new Padding(5, 8, 5, 8);
controlInputNullableInt1.Name = "controlInputNullableInt1";
controlInputNullableInt1.Size = new Size(244, 39);
controlInputNullableInt1.TabIndex = 12;
controlInputNullableInt1.Value = null;
//
// myDropDownList1
//
myDropDownList1.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
myDropDownList1.Location = new Point(12, 105);
myDropDownList1.Margin = new Padding(3, 4, 3, 4);
myDropDownList1.Name = "myDropDownList1";
myDropDownList1.SelectedValue = "";
myDropDownList1.Size = new Size(201, 39);
myDropDownList1.TabIndex = 13;
//
// FormClient
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(273, 397);
Controls.Add(myDropDownList1);
Controls.Add(controlInputNullableInt1);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(label3);
Controls.Add(textBoxReviews);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(textBoxName);
Controls.Add(LabelFIO);
Margin = new Padding(3, 4, 3, 4);
Name = "FormClient";
Text = "Клиенты";
Load += FormClient_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label LabelFIO;
private TextBox textBoxName;
private Label label1;
private Label label2;
private TextBox textBoxReviews;
private Label label3;
private Button buttonSave;
private Button buttonCancel;
private ControlInputNullableInt controlInputNullableInt1;
private VisualCompLib.MyDropDownList myDropDownList1;
}
}

104
COP/WinForms/FormClient.cs Normal file
View File

@ -0,0 +1,104 @@
using ClientsContracts.BindingModels;
using ClientsContracts.BusinessLogicContracts;
using ClientsContracts.ViewModels;
using ControlsLibraryNet60.Input;
using System.Windows.Forms;
namespace WinForms
{
public partial class FormClient : Form
{
public int Id { set { id = value; } }
private readonly IClientLogic _logic;
private readonly IStatusLogic _logicS;
private int? id;
public FormClient(IClientLogic logic, IStatusLogic logicS)
{
InitializeComponent();
_logic = logic;
_logicS = logicS;
}
private void FormClient_Load(object sender, EventArgs e)
{
List<StatusViewModel> viewS = _logicS.Read(null);
if (viewS != null)
{
List<string> list = new List<string>();
foreach (StatusViewModel s in viewS)
{
list.Add(s.Name);
}
myDropDownList1.LoadValues(list);
}
if (id.HasValue)
{
try
{
ClientViewModel view = _logic.Read(new ClientBindingModel { Id = id.Value })?[0];
if (view != null)
{
textBoxReviews.Text = view.Reviews;
textBoxName.Text = view.Name;
myDropDownList1.SelectedValue = view.Status;
if (view.Amount != null && view.Amount != "")
{
controlInputNullableInt1.Value = Int32.Parse(view.Amount);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните имя", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(myDropDownList1.SelectedValue))
{
MessageBox.Show("Выберите статус", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (textBoxReviews.Text == null)
{
MessageBox.Show("Заполните отзывы", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
int? amount = controlInputNullableInt1.Value;
try
{
_logic.CreateOrUpdate(new ClientBindingModel
{
Id = id,
Reviews = textBoxReviews.Text,
Name = textBoxName.Text,
Status = myDropDownList1.SelectedValue.ToString(),
Amount = amount
});
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)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

148
COP/WinForms/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,148 @@
namespace WinForms
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
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();
myTreeView1 = new VisableComponents.MyTreeView();
wordText1 = new VisualCompLib.Components.WordText(components);
excelChart1 = new UnvisableComponents.ExcelChart(components);
componentDocumentWithTableMultiHeaderPdf1 = new ComponentsLibraryNet60.DocumentWithTable.ComponentDocumentWithTableMultiHeaderPdf(components);
contextMenuStrip1.SuspendLayout();
SuspendLayout();
//
// 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(267, 172);
//
// добавитьToolStripMenuItem
//
добавитьToolStripMenuItem.Name = обавитьToolStripMenuItem";
добавитьToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.A;
добавитьToolStripMenuItem.Size = new Size(266, 24);
добавитьToolStripMenuItem.Text = "Добавить";
добавитьToolStripMenuItem.Click += добавитьToolStripMenuItem_Click;
//
// редактироватьToolStripMenuItem
//
редактироватьToolStripMenuItem.Name = "редактироватьToolStripMenuItem";
редактироватьToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.U;
редактироватьToolStripMenuItem.Size = new Size(266, 24);
редактироватьToolStripMenuItem.Text = "Редактировать";
редактироватьToolStripMenuItem.Click += редактироватьToolStripMenuItem_Click;
//
// удалитьToolStripMenuItem
//
удалитьToolStripMenuItem.Name = "удалитьToolStripMenuItem";
удалитьToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.D;
удалитьToolStripMenuItem.Size = new Size(266, 24);
удалитьToolStripMenuItem.Text = "Удалить";
удалитьToolStripMenuItem.Click += удалитьToolStripMenuItem_Click;
//
// сохранитьВВордToolStripMenuItem
//
сохранитьВВордToolStripMenuItem.Name = "сохранитьВВордToolStripMenuItem";
сохранитьВВордToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
сохранитьВВордToolStripMenuItem.Size = new Size(266, 24);
сохранитьВВордToolStripMenuItem.Text = "Сохранить в Ворд";
сохранитьВВордToolStripMenuItem.Click += сохранитьВВордToolStripMenuItem_Click;
//
// сохранитьВЭксельToolStripMenuItem
//
сохранитьВЭксельToolStripMenuItem.Name = "сохранитьВЭксельToolStripMenuItem";
сохранитьВЭксельToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.C;
сохранитьВЭксельToolStripMenuItem.Size = new Size(266, 24);
сохранитьВЭксельToolStripMenuItem.Text = "Сохранить в Эксель";
сохранитьВЭксельToolStripMenuItem.Click += сохранитьВЭксельToolStripMenuItem_Click;
//
// сохранитьВПдфToolStripMenuItem
//
сохранитьВПдфToolStripMenuItem.Name = "сохранитьВПдфToolStripMenuItem";
сохранитьВПдфToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.T;
сохранитьВПдфToolStripMenuItem.Size = new Size(266, 24);
сохранитьВПдфToolStripMenuItem.Text = "Сохранить в пдф";
сохранитьВПдфToolStripMenuItem.Click += сохранитьВПдфToolStripMenuItem_Click;
//
// статусыToolStripMenuItem
//
статусыToolStripMenuItem.Name = "статусыToolStripMenuItem";
статусыToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.Tab;
статусыToolStripMenuItem.Size = new Size(266, 24);
статусыToolStripMenuItem.Text = "Статусы";
статусыToolStripMenuItem.Click += статусыToolStripMenuItem_Click;
//
// myTreeView1
//
myTreeView1.AutoSizeMode = AutoSizeMode.GrowAndShrink;
myTreeView1.BackColor = SystemColors.ControlDark;
myTreeView1.Location = new Point(12, 13);
myTreeView1.Margin = new Padding(3, 4, 3, 4);
myTreeView1.MinimumSize = new Size(200, 200);
myTreeView1.Name = "myTreeView1";
myTreeView1.Size = new Size(776, 424);
myTreeView1.TabIndex = 1;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(myTreeView1);
Name = "FormMain";
Text = "Учет клиентов";
Load += FormMain_Load;
contextMenuStrip1.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
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 VisableComponents.MyTreeView myTreeView1;
private VisualCompLib.Components.WordText wordText1;
private UnvisableComponents.ExcelChart excelChart1;
private ComponentsLibraryNet60.DocumentWithTable.ComponentDocumentWithTableMultiHeaderPdf componentDocumentWithTableMultiHeaderPdf1;
}
}

227
COP/WinForms/FormMain.cs Normal file
View File

@ -0,0 +1,227 @@
using ClientBusinessLogic.BusinessLogics;
using ClientsContracts.BusinessLogicContracts;
using ClientsContracts.ViewModels;
using ClientsContracts.BindingModels;
using ControlsLibraryNet60.Data;
using ComponentsLibraryNet60.Models;
using UnvisableComponents;
using Unity;
using DocumentFormat.OpenXml.Spreadsheet;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
namespace WinForms
{
public partial class FormMain : Form
{
private readonly IClientLogic _clientLogic;
private readonly IStatusLogic _statusLogic;
public FormMain(IClientLogic clientLogic, IStatusLogic statusLogic)
{
_clientLogic = clientLogic;
_statusLogic = statusLogic;
InitializeComponent();
List<string> stringToHierachy = new List<string>() { "Status", "Amount", "Id", "Name" };
myTreeView1.addToHierarchy(stringToHierachy);
myTreeView1.ContextMenuStrip = contextMenuStrip1;
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
var list = _clientLogic.Read(null);
for (int i = 0; i < list.Count; i++)
{
if (list[i].Amount == null || list[i].Amount == "") { list[i].Amount = "нет"; }
}
myTreeView1.LoadTree(list);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AddNewElement()
{
var form = Program.Container.Resolve<FormClient>();
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
private void UpdateElement()
{
var form = Program.Container.Resolve<FormClient>();
var selectedClient = myTreeView1.GetNode(typeof(ClientViewModel));
if (selectedClient != null)
{
form.Id = Convert.ToInt32((selectedClient as ClientViewModel).Id);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
else
{
MessageBox.Show("Выберите клиента для редактирования");
}
}
private void DeleteElement()
{
if (MessageBox.Show("Удалить запись", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
var selectedClient = myTreeView1.GetNode(typeof(ClientViewModel));
int id = Convert.ToInt32((selectedClient as ClientViewModel).Id);
try
{
_clientLogic.Delete(new ClientBindingModel { Id = id });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
private void CreateWord()
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "docx|*.docx" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
List<string> textList = new List<string>();
var list = _clientLogic.Read(null);
if (list != null)
{
foreach (var item in list)
{
if (item.Amount != null && item.Amount != "")
{
string clients = string.Concat("ФИО: ", item.Name, " Отзывы: ", item.Reviews);
textList.Add(clients);
}
}
string[] textArray = textList.ToArray();
wordText1.CreateWordText(new(fileName, "Документ по клиентам, совершавшим покупки (ФИО клиента и его отзывы)", textArray));
}
}
private void createExcel()
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
var statuses = _statusLogic.Read(null);
var clients = _clientLogic.Read(null);
List<(string, int)> dates = new List<(string, int)>();
for (int i = 0; i < statuses.Count; i++)
{
int counter = 0;
for(int j = 0; j < clients.Count; j++)
{
if (clients[j].Status == statuses[i].Name && clients[j].Amount != null) counter++;
}
dates.Add((statuses[i].Name, counter));
}
excelChart1.Load(new ChartInfo
{
Path = fileName,
Title = "Сколько клиентов какого статуса совершали покупки",
DiagrammTitle = "Круговая диаграмма",
Dates = dates,
DirLegend = DirectionLegend.Right
});
}
private void CreatePdf()
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
var clients = _clientLogic.Read(null);
for (int i = 0; i < clients.Count; i++)
{
if (clients[i].Amount == null || clients[i].Amount == "") { clients[i].Amount = "нет"; }
}
componentDocumentWithTableMultiHeaderPdf1.CreateDoc(new ComponentDocumentWithTableHeaderDataConfig<ClientViewModel>
{
FilePath = fileName,
Header = "Отчет по клиентам",
ColumnsRowsWidth = new List<(int, int)> { (5, 5), (10, 5), (15, 0), (15, 0) },
Headers = new List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)>
{
(0, 0, "Id", "Id"),
(1, 0, "ФИО", "Name"),
(2, 0, "Статус", "Status"),
(3, 0, "Сумма покупок", "Amount")
},
Data = clients
});
}
private void статусыToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = Program.Container.Resolve<FormStatus>();
form.ShowDialog();
}
private void сохранитьВПдфToolStripMenuItem_Click(object sender, EventArgs e)
{
CreatePdf();
}
private void сохранитьВЭксельToolStripMenuItem_Click(object sender, EventArgs e)
{
createExcel();
}
private void сохранитьВВордToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateWord();
}
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();
}
}
}

132
COP/WinForms/FormMain.resx Normal file
View File

@ -0,0 +1,132 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="contextMenuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="wordText1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>202, 17</value>
</metadata>
<metadata name="excelChart1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>327, 17</value>
</metadata>
<metadata name="componentDocumentWithTableMultiHeaderPdf1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>460, 17</value>
</metadata>
</root>

67
COP/WinForms/FormStatus.Designer.cs generated Normal file
View File

@ -0,0 +1,67 @@
namespace WinForms
{
partial class FormStatus
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.dataGridView = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(12, 12);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(236, 217);
this.dataGridView.TabIndex = 0;
this.dataGridView.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellEndEdit);
this.dataGridView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dataGridView_KeyDown);
//
// FormStatus
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(260, 241);
this.Controls.Add(this.dataGridView);
this.Name = "FormStatus";
this.Text = "Статусы";
this.Load += new System.EventHandler(this.FormStatus_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
}
}

109
COP/WinForms/FormStatus.cs Normal file
View File

@ -0,0 +1,109 @@
using ClientsContracts.BindingModels;
using ClientsContracts.BusinessLogicContracts;
using System.ComponentModel;
namespace WinForms
{
public partial class FormStatus : Form
{
private readonly IStatusLogic statusLogic;
BindingList<StatusBindingModel> list;
public FormStatus(IStatusLogic _statusLogic)
{
InitializeComponent();
statusLogic = _statusLogic;
list = new BindingList<StatusBindingModel>();
dataGridView.AllowUserToAddRows = false;
}
private void LoadData()
{
try
{
var list1 = statusLogic.Read(null);
list.Clear();
foreach (var item in list1)
{
list.Add(new StatusBindingModel
{
Id = item.Id,
Name = item.Name,
});
}
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns[0].Visible = false;
dataGridView.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormStatus_Load(object sender, EventArgs e)
{
LoadData();
}
private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var typeName = (string)dataGridView.CurrentRow.Cells[1].Value;
if (!string.IsNullOrEmpty(typeName))
{
if (dataGridView.CurrentRow.Cells[0].Value != null)
{
statusLogic.CreateOrUpdate(new StatusBindingModel()
{
Id = Convert.ToInt32(dataGridView.CurrentRow.Cells[0].Value),
Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue
});
}
else
{
statusLogic.CreateOrUpdate(new StatusBindingModel()
{
Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue
});
}
}
else
{
MessageBox.Show("Введена пустая строка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Insert)
{
if (dataGridView.Rows.Count == 0)
{
list.Add(new StatusBindingModel());
dataGridView.DataSource = new BindingList<StatusBindingModel>(list);
dataGridView.CurrentCell = dataGridView.Rows[0].Cells[1];
return;
}
if (dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1].Value != null)
{
list.Add(new StatusBindingModel());
dataGridView.DataSource = new BindingList<StatusBindingModel>(list);
dataGridView.CurrentCell = dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1];
return;
}
}
if (e.KeyData == Keys.Delete)
{
if (MessageBox.Show("Удалить выбранный элемент", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
statusLogic.Delete(new StatusBindingModel() { Id = (int)dataGridView.CurrentRow.Cells[0].Value });
LoadData();
}
}
}
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,215 @@
using ClientBusinessLogic.BusinessLogics;
using ClientsContracts.BindingModels;
using Plugins;
using VisableComponents;
using UnvisableComponents;
using VisualCompLib.Components;
using ComponentsLibraryNet60.DocumentWithTable;
using ClientsContracts.ViewModels;
using ComponentsLibraryNet60.Models;
using ClientsDatabaseImplement.Implements;
namespace WinForms
{
public class PluginsConvention : IPluginsConvention
{
private readonly ClientLogic _clientLogic = new ClientLogic(new ClientStorage());
private readonly StatusLogic _statusLogic = new StatusLogic(new StatusStorage());
private MyTreeView myTreeView1 = new MyTreeView();
public string PluginName { get; set; } = "Дерево большое";
public UserControl GetControl
{
get
{
Load();
return myTreeView1;
}
}
public PluginsConventionElement GetElement
{
get
{
var selectedClient = myTreeView1.GetNode(typeof(ClientViewModel));
int? id = null;
if (selectedClient != null)
{
id = Convert.ToInt32((selectedClient as ClientViewModel).Id);
}
byte[] bytes = new byte[16];
if (!id.HasValue)
{
id = -1;
}
BitConverter.GetBytes(id.Value).CopyTo(bytes, 0);
return new()
{
Id = new Guid(bytes)
};
}
}
public bool CreateChartDocument(PluginsConventionSaveDocument saveDocument)
{
try
{
ExcelChart excelChart1 = new ExcelChart();
var statuses = _statusLogic.Read(null);
var clients = _clientLogic.Read(null);
List<(string, int)> dates = new List<(string, int)>();
for (int i = 0; i < statuses.Count; i++)
{
int counter = 0;
for (int j = 0; j < clients.Count; j++)
{
if (clients[j].Status == statuses[i].Name && clients[j].Amount != null) counter++;
}
dates.Add((statuses[i].Name, counter));
}
excelChart1.Load(new ChartInfo
{
Path = saveDocument.FileName,
Title = "Сколько клиентов какого статуса совершали покупки",
DiagrammTitle = "Круговая диаграмма",
Dates = dates,
DirLegend = DirectionLegend.Right
});
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
public bool CreateSimpleDocument(PluginsConventionSaveDocument saveDocument)
{
try
{
WordText wordText1 = new WordText();
List<string> textList = new List<string>();
var list = _clientLogic.Read(null);
if (list != null)
{
foreach (var item in list)
{
if (item.Amount != null && item.Amount != "")
{
string clients = string.Concat("ФИО: ", item.Name, " Отзывы: ", item.Reviews);
textList.Add(clients);
}
}
string[] textArray = textList.ToArray();
wordText1.CreateWordText(new(saveDocument.FileName, "Документ по клиентам, совершавшим покупки (ФИО клиента и его отзывы)", textArray));
}
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
public bool CreateTableDocument(PluginsConventionSaveDocument saveDocument)
{
try
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
ComponentDocumentWithTableMultiHeaderPdf componentDocumentWithTableMultiHeaderPdf1 = new ComponentDocumentWithTableMultiHeaderPdf();
var clients = _clientLogic.Read(null);
for (int i = 0; i < clients.Count; i++)
{
if (clients[i].Amount == null || clients[i].Amount == "") { clients[i].Amount = "нет"; }
}
componentDocumentWithTableMultiHeaderPdf1.CreateDoc(new ComponentDocumentWithTableHeaderDataConfig<ClientViewModel>
{
FilePath = saveDocument.FileName,
Header = "Отчет по клиентам",
ColumnsRowsWidth = new List<(int, int)> { (5, 5), (10, 5), (15, 0), (15, 0) },
Headers = new List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)>
{
(0, 0, "Id", "Id"),
(1, 0, "ФИО", "Name"),
(2, 0, "Статус", "Status"),
(3, 0, "Сумма покупок", "Amount")
},
Data = clients
});
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
private void Load()
{
List<string> stringToHierachy = new List<string>() { "Status", "Amount", "Id", "Name" };
myTreeView1.addToHierarchy(stringToHierachy);
LoadData();
}
private void LoadData()
{
try
{
var list = _clientLogic.Read(null);
for (int i = 0; i < list.Count; i++)
{
if (list[i].Amount == null || list[i].Amount == "") { list[i].Amount = "нет"; }
}
myTreeView1.LoadTree(list);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public bool DeleteElement(PluginsConventionElement element)
{
var selectedClient = myTreeView1.GetNode(typeof(ClientViewModel));
int id = Convert.ToInt32((selectedClient as ClientViewModel).Id);
try
{
_clientLogic.Delete(new ClientBindingModel { Id = id });
LoadData();
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
public Form GetForm(PluginsConventionElement element)
{
if (element == null)
{
return new FormClient(_clientLogic, _statusLogic);
}
if (element.Id.GetHashCode() >= 0)
{
FormClient form = new FormClient(_clientLogic, _statusLogic);
form.Id = element.Id.GetHashCode();
return form;
}
return null;
}
public Form GetThesaurus()
{
return new FormStatus(_statusLogic);
}
public void ReloadData()
{
LoadData();
}
}
}

View File

@ -1,17 +1,37 @@
using ClientsContracts.BusinessLogicContracts;
using ClientsContracts.StorageContracts;
using ClientsDatabaseImplement.Implements;
using Unity;
using Unity.Lifetime;
namespace WinForms namespace WinForms
{ {
internal static class Program internal static class Program
{ {
private static IUnityContainer container = null;
public static IUnityContainer Container { get { if (container == null) { container = BuildUnityContainer(); } return container; } }
/// <summary> /// <summary>
/// The main entry point for the application. /// The main entry point for the application.
/// </summary> /// </summary>
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, Application.SetHighDpiMode(HighDpiMode.SystemAware);
// see https://aka.ms/applicationconfiguration. Application.EnableVisualStyles();
ApplicationConfiguration.Initialize(); Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1()); Application.Run(Container.Resolve<FormMain>());
}
private static IUnityContainer BuildUnityContainer()
{
var currentContainer = new UnityContainer();
currentContainer.RegisterType<IClientStorage, ClientStorage>(new HierarchicalLifetimeManager());
currentContainer.RegisterType<IStatusStorage, StatusStorage>(new HierarchicalLifetimeManager());
currentContainer.RegisterType<IClientLogic, ClientBusinessLogic.BusinessLogics.ClientLogic>(new HierarchicalLifetimeManager());
currentContainer.RegisterType<IStatusLogic, ClientBusinessLogic.BusinessLogics.StatusLogic>(new HierarchicalLifetimeManager());
return currentContainer;
} }
} }
} }

View File

@ -8,4 +8,27 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="ComponentsLibraryNet60" Version="1.0.0" />
<PackageReference Include="ControlsLibraryNet60" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.11">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="UnvisableComponents" Version="1.0.0" />
<PackageReference Include="VisableComponents" Version="1.0.9" />
<PackageReference Include="VisualCompLib" Version="1.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ClientBusinessLogic\ClientBusinessLogic.csproj" />
<ProjectReference Include="..\ClientsDatabaseImplement\ClientsDatabaseImplement.csproj" />
<ProjectReference Include="..\Plugins\Plugins.csproj" />
</ItemGroup>
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
<Exec Command="copy /Y &quot;$(TargetDir)*.dll&quot; &quot;$(SolutionDir)plugin\*.dll&quot;" />
</Target>
</Project> </Project>

233
COP/WinFormsByPlugins/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,233 @@
namespace WinFormsByPlugins
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.ControlsStripMenuItem = new
System.Windows.Forms.ToolStripMenuItem();
this.ActionsToolStripMenuItem = new
System.Windows.Forms.ToolStripMenuItem();
this.DocsToolStripMenuItem = new
System.Windows.Forms.ToolStripMenuItem();
this.SimpleDocToolStripMenuItem = new
System.Windows.Forms.ToolStripMenuItem();
this.TableDocToolStripMenuItem = new
System.Windows.Forms.ToolStripMenuItem();
this.ChartDocToolStripMenuItem = new
System.Windows.Forms.ToolStripMenuItem();
this.panelControl = new System.Windows.Forms.Panel();
this.ThesaurusToolStripMenuItem = new
System.Windows.Forms.ToolStripMenuItem();
this.AddElementToolStripMenuItem = new
System.Windows.Forms.ToolStripMenuItem();
this.UpdElementToolStripMenuItem = new
System.Windows.Forms.ToolStripMenuItem();
this.DelElementToolStripMenuItem = new
System.Windows.Forms.ToolStripMenuItem();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// menuStrip
//
this.menuStrip.Items.AddRange(new
System.Windows.Forms.ToolStripItem[] {
this.ControlsStripMenuItem,
this.ActionsToolStripMenuItem,
this.DocsToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(800, 24);
this.menuStrip.TabIndex = 0;
this.menuStrip.Text = "Меню";
//
// ControlsStripMenuItem
//
this.ControlsStripMenuItem.Name = "ControlsStripMenuItem";
this.ControlsStripMenuItem.Size = new System.Drawing.Size(94,
20);
this.ControlsStripMenuItem.Text = "Компоненты";
//
// ActionsToolStripMenuItem
//
this.ActionsToolStripMenuItem.DropDownItems.AddRange(new
System.Windows.Forms.ToolStripItem[] {
this.ThesaurusToolStripMenuItem,
this.AddElementToolStripMenuItem,
this.UpdElementToolStripMenuItem,
this.DelElementToolStripMenuItem});
this.ActionsToolStripMenuItem.Name =
"ActionsToolStripMenuItem";
this.ActionsToolStripMenuItem.Size = new
System.Drawing.Size(70, 20);
this.ActionsToolStripMenuItem.Text = "Действия";
//
// DocsToolStripMenuItem
//
this.DocsToolStripMenuItem.DropDownItems.AddRange(new
System.Windows.Forms.ToolStripItem[] {
this.SimpleDocToolStripMenuItem,
this.TableDocToolStripMenuItem,
this.ChartDocToolStripMenuItem});
this.DocsToolStripMenuItem.Name = "DocsToolStripMenuItem";
this.DocsToolStripMenuItem.Size = new System.Drawing.Size(82, 20);
this.DocsToolStripMenuItem.Text = "Документы";
//
// SimpleDocToolStripMenuItem
//
this.SimpleDocToolStripMenuItem.Name = "SimpleDocToolStripMenuItem";
this.SimpleDocToolStripMenuItem.ShortcutKeys =
((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control |
System.Windows.Forms.Keys.S)));
this.SimpleDocToolStripMenuItem.Size = new
System.Drawing.Size(233, 22);
this.SimpleDocToolStripMenuItem.Text = "Простой документ";
this.SimpleDocToolStripMenuItem.Click += new
System.EventHandler(this.SimpleDocToolStripMenuItem_Click);
//
// TableDocToolStripMenuItem
//
this.TableDocToolStripMenuItem.Name =
"TableDocToolStripMenuItem";
this.TableDocToolStripMenuItem.ShortcutKeys =
((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control |
System.Windows.Forms.Keys.T)));
this.TableDocToolStripMenuItem.Size = new
System.Drawing.Size(233, 22);
this.TableDocToolStripMenuItem.Text = "Документ с таблицой";
this.TableDocToolStripMenuItem.Click += new
System.EventHandler(this.TableDocToolStripMenuItem_Click);
//
// ChartDocToolStripMenuItem
//
this.ChartDocToolStripMenuItem.Name =
"ChartDocToolStripMenuItem";
this.ChartDocToolStripMenuItem.ShortcutKeys =
((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control |
System.Windows.Forms.Keys.C)));
this.ChartDocToolStripMenuItem.Size = new
System.Drawing.Size(233, 22);
this.ChartDocToolStripMenuItem.Text = "Диаграмма";
this.ChartDocToolStripMenuItem.Click += new
System.EventHandler(this.ChartDocToolStripMenuItem_Click);
//
// panelControl
//
this.panelControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelControl.Location = new System.Drawing.Point(0, 24);
this.panelControl.Name = "panelControl";
this.panelControl.Size = new System.Drawing.Size(800, 426);
this.panelControl.TabIndex = 1;
//
// ThesaurusToolStripMenuItem
//
this.ThesaurusToolStripMenuItem.Name =
"ThesaurusToolStripMenuItem";
this.ThesaurusToolStripMenuItem.ShortcutKeys =
((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control |
System.Windows.Forms.Keys.I)));
this.ThesaurusToolStripMenuItem.Size = new
System.Drawing.Size(180, 22);
this.ThesaurusToolStripMenuItem.Text = "Справочник";
this.ThesaurusToolStripMenuItem.Click += new
System.EventHandler(this.ThesaurusToolStripMenuItem_Click);
//
// AddElementToolStripMenuItem
//
this.AddElementToolStripMenuItem.Name =
"AddElementToolStripMenuItem";
this.AddElementToolStripMenuItem.ShortcutKeys =
((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control |
System.Windows.Forms.Keys.A)));
this.AddElementToolStripMenuItem.Size = new
System.Drawing.Size(180, 22);
this.AddElementToolStripMenuItem.Text = "Добавить";
this.AddElementToolStripMenuItem.Click += new
System.EventHandler(this.AddElementToolStripMenuItem_Click);
//
// UpdElementToolStripMenuItem
//
this.UpdElementToolStripMenuItem.Name = "UpdElementToolStripMenuItem";
this.UpdElementToolStripMenuItem.ShortcutKeys =
((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control |
System.Windows.Forms.Keys.U)));
this.UpdElementToolStripMenuItem.Size = new
System.Drawing.Size(180, 22);
this.UpdElementToolStripMenuItem.Text = "Изменить";
this.UpdElementToolStripMenuItem.Click += new
System.EventHandler(this.UpdElementToolStripMenuItem_Click);
//
// DelElementToolStripMenuItem
//
this.DelElementToolStripMenuItem.Name =
"DelElementToolStripMenuItem";
this.DelElementToolStripMenuItem.ShortcutKeys =
((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control |
System.Windows.Forms.Keys.D)));
this.DelElementToolStripMenuItem.Size = new
System.Drawing.Size(180, 22);
this.DelElementToolStripMenuItem.Text = "Удалить";
this.DelElementToolStripMenuItem.Click += new
System.EventHandler(this.DelElementToolStripMenuItem_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.panelControl);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMain";
this.StartPosition =
System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Главная форма";
this.WindowState =
System.Windows.Forms.FormWindowState.Maximized;
this.KeyDown += new
System.Windows.Forms.KeyEventHandler(this.FormMain_KeyDown);
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip;
private System.Windows.Forms.ToolStripMenuItem ControlsStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem DocsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem SimpleDocToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem TableDocToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem ChartDocToolStripMenuItem;
private System.Windows.Forms.Panel panelControl;
private System.Windows.Forms.ToolStripMenuItem ActionsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem ThesaurusToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem AddElementToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem UpdElementToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem DelElementToolStripMenuItem;
}
}

View File

@ -0,0 +1,222 @@
using Plugins;
using System.Reflection;
using WinForms;
namespace WinFormsByPlugins
{
public partial class FormMain : Form
{
private readonly Dictionary<string, IPluginsConvention> _plugins;
private string _selectedPlugin;
public FormMain()
{
InitializeComponent();
_plugins = LoadPlugins();
_selectedPlugin = string.Empty;
}
private Dictionary<string, IPluginsConvention> LoadPlugins()
{
Dictionary<string, IPluginsConvention> plugins = new();
string currentDirectory = Directory.GetParent(Environment.CurrentDirectory)!.Parent!.Parent!.Parent!.FullName + "\\plugin";
string[] dllFiles = Directory.GetFiles(currentDirectory, "*.dll", SearchOption.AllDirectories);
foreach (string dllFile in dllFiles)
{
try
{
Assembly assembly = Assembly.LoadFrom(dllFile);
Type[] types = assembly.GetTypes();
foreach (Type type in types)
{
if (typeof(IPluginsConvention).IsAssignableFrom(type) && !type.IsInterface)
{
var plugin = (IPluginsConvention)Activator.CreateInstance(type)!;
plugins.Add(plugin.PluginName, plugin);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Îøèáêà ïðè çàãðóçêå ñáîðêè {dllFile}: {ex.Message}");
}
}
foreach (var plugin in plugins)
{
CreateMenuItem(plugin.Value.PluginName);
}
return plugins;
}
private void CreateMenuItem(string pluginName)
{
ToolStripMenuItem menuItem = new ToolStripMenuItem(pluginName);
menuItem.Click += (object? sender, EventArgs a) =>
{
_selectedPlugin = pluginName;
IPluginsConvention plugin = _plugins[pluginName];
UserControl userControl = plugin.GetControl;
if (userControl != null)
{
panelControl.Controls.Clear();
plugin.ReloadData();
userControl.Dock = DockStyle.Fill;
panelControl.Controls.Add(userControl);
}
};
ControlsStripMenuItem.DropDownItems.Add(menuItem);
}
private void FormMain_KeyDown(object sender, KeyEventArgs e)
{
if (string.IsNullOrEmpty(_selectedPlugin) ||
!_plugins.ContainsKey(_selectedPlugin))
{
return;
}
if (!e.Control)
{
return;
}
switch (e.KeyCode)
{
case Keys.I:
ShowThesaurus();
break;
case Keys.A:
AddNewElement();
break;
case Keys.U:
UpdateElement();
break;
case Keys.D:
DeleteElement();
break;
case Keys.S:
CreateSimpleDoc();
break;
case Keys.T:
CreateTableDoc();
break;
case Keys.C:
CreateChartDoc();
break;
}
}
private void ShowThesaurus()
{
_plugins[_selectedPlugin].GetThesaurus()?.Show();
}
private void AddNewElement()
{
var form = _plugins[_selectedPlugin].GetForm(null);
if (form != null && form.ShowDialog() == DialogResult.OK)
{
_plugins[_selectedPlugin].ReloadData();
}
}
private void UpdateElement()
{
var element = _plugins[_selectedPlugin].GetElement;
if (element == null)
{
MessageBox.Show("Íåò âûáðàííîãî ýëåìåíòà", "Îøèáêà",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var form = _plugins[_selectedPlugin].GetForm(element);
if (form != null && form.ShowDialog() == DialogResult.OK)
{
_plugins[_selectedPlugin].ReloadData();
}
}
private void DeleteElement()
{
if (MessageBox.Show("Óäàëèòü âûáðàííûé ýëåìåíò", "Óäàëåíèå",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
var element = _plugins[_selectedPlugin].GetElement;
if (element == null)
{
MessageBox.Show("Íåò âûáðàííîãî ýëåìåíòà", "Îøèáêà",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (_plugins[_selectedPlugin].DeleteElement(element))
{
_plugins[_selectedPlugin].ReloadData();
}
}
private void CreateSimpleDoc()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Word Documents (*.docx)|*.docx";
saveFileDialog.Title = "Âûáåðèòå ôàéë";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_plugins[_selectedPlugin].CreateSimpleDocument(new PluginsConventionSaveDocument() { FileName = saveFileDialog.FileName }))
{
MessageBox.Show("Äîêóìåíò ñîõðàíåí", "Ñîçäàíèå äîêóìåíòà", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Îøèáêà ïðè ñîçäàíèè äîêóìåíòà",
"Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void CreateTableDoc()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "PDF Files (*.pdf)|*.pdf";
saveFileDialog.Title = "Âûáåðèòå ôàéë";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_plugins[_selectedPlugin].CreateTableDocument(new PluginsConventionSaveDocument() { FileName = saveFileDialog.FileName }))
{
MessageBox.Show("Äîêóìåíò ñîõðàíåí", "Ñîçäàíèå äîêóìåíòà", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Îøèáêà ïðè ñîçäàíèè äîêóìåíòà",
"Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void CreateChartDoc()
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel Files (*.xlsx)|*.xlsx";
saveFileDialog.Title = "Âûáåðèòå ôàéë";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_plugins[_selectedPlugin].CreateChartDocument(new PluginsConventionSaveDocument() { FileName = saveFileDialog.FileName }))
{
MessageBox.Show("Äîêóìåíò ñîõðàíåí", "Ñîçäàíèå äîêóìåíòà", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Îøèáêà ïðè ñîçäàíèè äîêóìåíòà",
"Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void ThesaurusToolStripMenuItem_Click(object sender,
EventArgs e) => ShowThesaurus();
private void AddElementToolStripMenuItem_Click(object sender,
EventArgs e) => AddNewElement();
private void UpdElementToolStripMenuItem_Click(object sender,
EventArgs e) => UpdateElement();
private void DelElementToolStripMenuItem_Click(object sender,
EventArgs e) => DeleteElement();
private void SimpleDocToolStripMenuItem_Click(object sender,
EventArgs e) => CreateSimpleDoc();
private void TableDocToolStripMenuItem_Click(object sender, EventArgs
e) => CreateTableDoc();
private void ChartDocToolStripMenuItem_Click(object sender, EventArgs
e) => CreateChartDoc();
}
}

View File

@ -0,0 +1,120 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,17 @@
namespace WinFormsByPlugins
{
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 FormMain());
}
}
}

View File

@ -0,0 +1,16 @@
<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="..\Plugins\Plugins.csproj" />
<ProjectReference Include="..\WinForms\WinForms.csproj" />
</ItemGroup>
</Project>

Binary file not shown.

BIN
COP/plugin/Aspose.Words.dll Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
COP/plugin/EPPlus.dll Normal file

Binary file not shown.

BIN
COP/plugin/Humanizer.dll Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

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