9 Commits

Author SHA1 Message Date
Вячеслав Иванов
b9a7d832f3 ок 2024-10-03 14:17:59 +04:00
Вячеслав Иванов
424ef89446 donnnneeeee 3 2024-10-03 00:31:12 +04:00
Вячеслав Иванов
b98ed5c3af промежуточные 2024-09-19 13:46:00 +04:00
Вячеслав Иванов
60f5141fe7 в процессе.. 2024-09-19 10:33:18 +04:00
Вячеслав Иванов
a887e43aba done 2024-09-18 14:28:52 +04:00
Вячеслав Иванов
a29a9928ea иии раз... 2024-09-15 21:56:24 +04:00
Вячеслав Иванов
af6c379c97 save 2024-09-15 21:44:25 +04:00
Вячеслав Иванов
7ce94d7ae7 laba 2 2024-09-15 20:16:55 +04:00
Вячеслав Иванов
3058978306 done 2024-09-06 00:05:36 +04:00
64 changed files with 4237 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.BusinessLogicContracts;
using EnterpriseContracts.StorageContracts;
using EnterpriseContracts.ViewModels;
namespace EnterpriseBusinessLogic.BusinessLogics
{
public class EmployeeLogic : IEmployeeLogic
{
private readonly IEmployeeStorage _empStorage;
public EmployeeLogic(IEmployeeStorage empStorage)
{
_empStorage = empStorage;
}
public List<EmployeeViewModel> Read(EmployeeBindingModel? model)
{
if (model == null)
{
return _empStorage.GetFullList();
}
return model.Id.HasValue
? new List<EmployeeViewModel> { _empStorage.GetElement(model) }
: _empStorage.GetFilteredList(model);
}
public void CreateOrUpdate(EmployeeBindingModel model)
{
var element = _empStorage.GetElement(new EmployeeBindingModel
{
Id = model.Id
});
if (element != null)
{
_empStorage.Update(model);
}
else
{
_empStorage.Insert(model);
}
}
public void Delete(EmployeeBindingModel model)
{
var element = _empStorage.GetElement(new EmployeeBindingModel { Id = model.Id });
if (element == null)
{
throw new Exception("Id don't exists");
}
_empStorage.Delete(model);
}
}
}

View File

@@ -0,0 +1,60 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.BusinessLogicContracts;
using EnterpriseContracts.StorageContracts;
using EnterpriseContracts.ViewModels;
namespace EnterpriseBusinessLogic.BusinessLogics
{
public class SubdivisionLogic : ISubdivisionLogic
{
private readonly ISubdivisionStorage _subdivisionStorage;
public SubdivisionLogic(ISubdivisionStorage subdivisionStorage)
{
_subdivisionStorage = subdivisionStorage;
}
public List<SubdivisionViewModel> Read(SubdivisionBindingModel? model)
{
if (model == null)
{
return _subdivisionStorage.GetFullList();
}
return model.Id != 0 ?
new List<SubdivisionViewModel> { _subdivisionStorage.GetElement(model) } :
_subdivisionStorage.GetFilteredList(model);
}
public void CreateOrUpdate(SubdivisionBindingModel model)
{
var element = _subdivisionStorage.GetElement(new SubdivisionBindingModel
{
Name = model.Name
});
if (element != null && element.Id != model.Id)
{
throw new Exception("This name is exists!");
}
if (model.Id != 0)
{
_subdivisionStorage.Update(model);
}
else
{
_subdivisionStorage.Insert(model);
}
}
public bool Delete(SubdivisionBindingModel model)
{
var element = _subdivisionStorage.GetElement(new SubdivisionBindingModel { Id = model.Id });
if (element == null)
{
return false;
}
_subdivisionStorage.Delete(model);
return true;
}
}
}

View File

@@ -0,0 +1,7 @@
namespace EnterpriseBusinessLogic
{
public class Class1
{
}
}

View File

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

View File

@@ -0,0 +1,12 @@
namespace EnterpriseContracts.BindingModels
{
public class EmployeeBindingModel
{
public int? Id { get; set; }
public string Fio { get; set; } = string.Empty;
public int Experience { get; set; }
public string Subdivision { get; set; } = string.Empty;
public string Posts { get; set; } = string.Empty;
public (int, int)? ExperienceStep { get; set; }
}
}

View File

@@ -0,0 +1,8 @@
namespace EnterpriseContracts.BindingModels
{
public class SubdivisionBindingModel
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,12 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.ViewModels;
namespace EnterpriseContracts.BusinessLogicContracts
{
public interface IEmployeeLogic
{
List<EmployeeViewModel> Read(EmployeeBindingModel? model);
void CreateOrUpdate(EmployeeBindingModel model);
void Delete(EmployeeBindingModel model);
}
}

View File

@@ -0,0 +1,12 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.ViewModels;
namespace EnterpriseContracts.BusinessLogicContracts
{
public interface ISubdivisionLogic
{
List<SubdivisionViewModel> Read(SubdivisionBindingModel? model);
void CreateOrUpdate(SubdivisionBindingModel model);
bool Delete(SubdivisionBindingModel model);
}
}

View File

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

View File

@@ -0,0 +1,15 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.ViewModels;
namespace EnterpriseContracts.StorageContracts
{
public interface IEmployeeStorage
{
List<EmployeeViewModel> GetFullList();
List<EmployeeViewModel> GetFilteredList(EmployeeBindingModel model);
EmployeeViewModel? GetElement(EmployeeBindingModel model);
void Insert(EmployeeBindingModel model);
void Update(EmployeeBindingModel model);
void Delete(EmployeeBindingModel model);
}
}

View File

@@ -0,0 +1,15 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.ViewModels;
namespace EnterpriseContracts.StorageContracts
{
public interface ISubdivisionStorage
{
List<SubdivisionViewModel> GetFullList();
List<SubdivisionViewModel> GetFilteredList(SubdivisionBindingModel model);
SubdivisionViewModel? GetElement(SubdivisionBindingModel? model);
void Insert(SubdivisionBindingModel model);
void Update(SubdivisionBindingModel model);
void Delete(SubdivisionBindingModel model);
}
}

View File

@@ -0,0 +1,13 @@
namespace EnterpriseContracts.ViewModels
{
public class EmployeeViewModel
{
public int Id { get; set; }
public string Fio { get; set; } = string.Empty;
public int Experience { get; set; }
public string Subdivision { get; set; } = string.Empty;
public string Posts { get; set; } = string.Empty;
public EmployeeViewModel() { }
}
}

View File

@@ -0,0 +1,8 @@
namespace EnterpriseContracts.ViewModels
{
public class SubdivisionViewModel
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
}

View File

@@ -0,0 +1,21 @@
using EnterpriseDataBaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace EnterpriseDataBaseImplement
{
public class EnterpriseDataBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-2EI1EJE\SQLEXPRESS;Initial Catalog=EnterpriseDatabase;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Employee> Employees { set; get; }
public virtual DbSet<Subdivision> Subdivisions { set; get; }
public virtual DbSet<EmployeePosts> EmployeePosts { set; get; }
}
}

View File

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

View File

@@ -0,0 +1,102 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.StorageContracts;
using EnterpriseContracts.ViewModels;
using EnterpriseDataBaseImplement.Models;
namespace EnterpriseDataBaseImplement.Implements
{
public class EmployeeStorage : IEmployeeStorage
{
public List<EmployeeViewModel> GetFullList()
{
var context = new EnterpriseDataBase();
return context.Employees
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<EmployeeViewModel> GetFilteredList(EmployeeBindingModel model)
{
var context = new EnterpriseDataBase();
if (!model.ExperienceStep.HasValue)
{
return new();
}
return context.Employees
.Where(x => model.ExperienceStep.Value.Item1 <= x.Experience &&
model.ExperienceStep.Value.Item2 >= x.Experience)
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public EmployeeViewModel? GetElement(EmployeeBindingModel model)
{
if (model == null || !model.Id.HasValue)
{
return null;
}
using var context = new EnterpriseDataBase();
var x = context.Employees
.ToList()
.FirstOrDefault(rec => rec.Id == model.Id);
return x?.GetViewModel;
}
public void Insert(EmployeeBindingModel model)
{
var context = new EnterpriseDataBase();
var transaction = context.Database.BeginTransaction();
try
{
var x = Employee.Create(model);
context.Employees.Add(x);
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
public void Update(EmployeeBindingModel model)
{
var context = new EnterpriseDataBase();
var transaction = context.Database.BeginTransaction();
try
{
var x = context.Employees.FirstOrDefault(rec => rec.Id == model.Id);
if (x == null)
{
throw new Exception("Not found");
}
x.Update(model);
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
public void Delete(EmployeeBindingModel model)
{
var context = new EnterpriseDataBase();
var x = context.Employees.FirstOrDefault(rec => rec.Id == model.Id);
if (x != null)
{
context.Employees.Remove(x);
context.SaveChanges();
}
else
{
throw new Exception("Id isn't exists");
}
}
}
}

View File

@@ -0,0 +1,97 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.StorageContracts;
using EnterpriseContracts.ViewModels;
using EnterpriseDataBaseImplement.Models;
namespace EnterpriseDataBaseImplement.Implements
{
public class SubdivisionStorage : ISubdivisionStorage
{
public List<SubdivisionViewModel> GetFullList()
{
var context = new EnterpriseDataBase();
return context.Subdivisions
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public List<SubdivisionViewModel> GetFilteredList(SubdivisionBindingModel model)
{
var context = new EnterpriseDataBase();
return context.Subdivisions
.Where(x => x.Name.Contains(model.Name))
.ToList()
.Select(x => x.GetViewModel)
.ToList();
}
public SubdivisionViewModel? GetElement(SubdivisionBindingModel? model)
{
if (model == null)
{
return null;
}
using var context = new EnterpriseDataBase();
var x = context.Subdivisions
.ToList()
.FirstOrDefault(rec => rec.Name == model.Name || rec.Id == model.Id);
return x?.GetViewModel;
}
public void Insert(SubdivisionBindingModel model)
{
var context = new EnterpriseDataBase();
var transaction = context.Database.BeginTransaction();
try
{
var x = Subdivision.Create(model);
context.Subdivisions.Add(x);
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
public void Update(SubdivisionBindingModel model)
{
var context = new EnterpriseDataBase();
var transaction = context.Database.BeginTransaction();
try
{
var x = context.Subdivisions.FirstOrDefault(rec => rec.Id == model.Id);
if (x == null)
{
throw new Exception("Not found");
}
x.Update(model);
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
}
public void Delete(SubdivisionBindingModel model)
{
var context = new EnterpriseDataBase();
var x = context.Subdivisions.FirstOrDefault(rec => rec.Id == model.Id);
if (x != null)
{
context.Subdivisions.Remove(x);
context.SaveChanges();
}
else
{
throw new Exception("Id isn't exists");
}
}
}
}

View File

@@ -0,0 +1,74 @@
// <auto-generated />
using EnterpriseDataBaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace EnterpriseDataBaseImplement.Migrations
{
[DbContext(typeof(EnterpriseDataBase))]
[Migration("20240915172215_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("EnterpriseDataBaseImplement.Models.Employee", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Experience")
.HasColumnType("int");
b.Property<string>("Fio")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Posts")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subdivision")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Employees");
});
modelBuilder.Entity("EnterpriseDataBaseImplement.Models.Subdivision", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Subdivisions");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,53 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace EnterpriseDataBaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Employees",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Fio = table.Column<string>(type: "nvarchar(max)", nullable: false),
Experience = table.Column<int>(type: "int", nullable: false),
Posts = table.Column<string>(type: "nvarchar(max)", nullable: false),
Subdivision = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Employees", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Subdivisions",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Subdivisions", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Employees");
migrationBuilder.DropTable(
name: "Subdivisions");
}
}
}

View File

@@ -0,0 +1,71 @@
// <auto-generated />
using EnterpriseDataBaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace EnterpriseDataBaseImplement.Migrations
{
[DbContext(typeof(EnterpriseDataBase))]
partial class EnterpriseDataBaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.12")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("EnterpriseDataBaseImplement.Models.Employee", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("Experience")
.HasColumnType("int");
b.Property<string>("Fio")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Posts")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Subdivision")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Employees");
});
modelBuilder.Entity("EnterpriseDataBaseImplement.Models.Subdivision", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Subdivisions");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,61 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.ViewModels;
namespace EnterpriseDataBaseImplement.Models
{
public class Employee
{
public int Id { get; set; }
public string Fio { get; set; } = string.Empty;
public int Experience { get; set; }
public string Posts { get; set; } = string.Empty;
public string Subdivision { get; set; } = string.Empty;
public static Employee? Create(EmployeeBindingModel? model)
{
if (model == null)
{
return null;
}
return new()
{
Fio = model.Fio,
Experience = model.Experience,
Posts = model.Posts,
Subdivision = model.Subdivision
};
}
public static Employee Create(EmployeeViewModel model)
{
return new Employee
{
Id = model.Id,
Fio = model.Fio,
Experience = model.Experience,
Posts = model.Posts,
Subdivision = model.Subdivision
};
}
public void Update(EmployeeBindingModel? model)
{
if (model == null)
{
return;
}
Posts = model.Posts;
Subdivision = model.Subdivision;
}
public EmployeeViewModel GetViewModel => new()
{
Id = Id,
Fio = Fio,
Experience = Experience,
Subdivision = Subdivision,
Posts = Posts,
};
}
}

View File

@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnterpriseDataBaseImplement.Models
{
public class EmployeePosts
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public string Posts { get; set; } = string.Empty;
[Required]
public virtual Employee? Employee { get; set; }
}
}

View File

@@ -0,0 +1,55 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.ViewModels;
namespace EnterpriseDataBaseImplement.Models
{
public class Subdivision
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public static Subdivision? Create(SubdivisionBindingModel? model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
Name = model.Name
};
}
public static Subdivision? Create(SubdivisionViewModel? model)
{
if (model == null)
{
return null;
}
return new()
{
Id = model.Id,
Name = model.Name
};
}
public void Update(SubdivisionBindingModel? model)
{
if (model == null)
{
return;
}
if (!string.IsNullOrEmpty(model.Name))
{
Name = model.Name;
}
}
public SubdivisionViewModel GetViewModel => new()
{
Id = Id,
Name = Name
};
}
}

65
KOP/Ivanov_App/Directory.Designer.cs generated Normal file
View File

@@ -0,0 +1,65 @@
namespace Ivanov_App
{
partial class Directory
{
/// <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.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView.Location = new System.Drawing.Point(0, 0);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowTemplate.Height = 25;
this.dataGridView.Size = new System.Drawing.Size(414, 261);
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);
//
// Directory
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(414, 261);
this.Controls.Add(this.dataGridView);
this.Name = "Directory";
this.Text = "Directory";
this.Load += new System.EventHandler(this.Directory_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
}
}

127
KOP/Ivanov_App/Directory.cs Normal file
View File

@@ -0,0 +1,127 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.BusinessLogicContracts;
using System.ComponentModel;
namespace Ivanov_App
{
public partial class Directory : Form
{
private readonly ISubdivisionLogic _logicS;
BindingList<SubdivisionBindingModel> list;
public Directory(ISubdivisionLogic logicS)
{
InitializeComponent();
_logicS = logicS;
dataGridView.AllowUserToDeleteRows = true;
list = new BindingList<SubdivisionBindingModel>();
}
private void LoadData()
{
try
{
var list1 = _logicS.Read(null);
list.Clear();
foreach (var item in list1)
{
list.Add(new()
{
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, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Directory_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)
{
_logicS.CreateOrUpdate(new()
{
Id = Convert.ToInt32(dataGridView.CurrentRow.Cells[0].Value),
Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue
});
}
else
{
_logicS.CreateOrUpdate(new()
{
Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue
});
}
}
else
{
MessageBox.Show("Empty name", "Error", 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());
dataGridView.DataSource = new List<SubdivisionBindingModel>(list);
dataGridView.CurrentCell = dataGridView.Rows[0].Cells[1];
return;
}
if (dataGridView.Rows[^1].Cells[1].Value != null)
{
list.Add(new());
dataGridView.DataSource = new List<SubdivisionBindingModel>(list);
dataGridView.CurrentCell = dataGridView.Rows[^1].Cells[1];
return;
}
}
if (e.KeyData == Keys.Delete)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Confirm deleting", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
try
{
if (!_logicS.Delete(new()
{
Id = id
}))
{
throw new Exception("Error on delete");
}
dataGridView.Rows.RemoveAt(dataGridView.SelectedRows[0].Index);
LoadData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
}
}

View File

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

169
KOP/Ivanov_App/EmployerForm.Designer.cs generated Normal file
View File

@@ -0,0 +1,169 @@
namespace Ivanov_App
{
partial class EmployerForm
{
/// <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.textBoxFio = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.customInputRangeNumber = new MyCustomComponents.CustomInputRangeNumber();
this.dropDownList = new CustomComponent.DropDownList();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.textBoxPosts = new System.Windows.Forms.TextBox();
this.buttonCreate = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// textBoxFio
//
this.textBoxFio.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxFio.Location = new System.Drawing.Point(41, 6);
this.textBoxFio.Name = "textBoxFio";
this.textBoxFio.Size = new System.Drawing.Size(284, 23);
this.textBoxFio.TabIndex = 0;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(23, 15);
this.label1.TabIndex = 1;
this.label1.Text = "Fio";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 43);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(64, 15);
this.label2.TabIndex = 2;
this.label2.Text = "Experience";
//
// customInputRangeNumber
//
this.customInputRangeNumber.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.customInputRangeNumber.AutoSize = true;
this.customInputRangeNumber.AutoValidate = System.Windows.Forms.AutoValidate.Disable;
this.customInputRangeNumber.CausesValidation = false;
this.customInputRangeNumber.Location = new System.Drawing.Point(82, 35);
this.customInputRangeNumber.MaxValue = null;
this.customInputRangeNumber.MinValue = null;
this.customInputRangeNumber.Name = "customInputRangeNumber";
this.customInputRangeNumber.Size = new System.Drawing.Size(243, 31);
this.customInputRangeNumber.TabIndex = 3;
this.customInputRangeNumber.Value = null;
//
// dropDownList
//
this.dropDownList.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dropDownList.Location = new System.Drawing.Point(82, 72);
this.dropDownList.Name = "dropDownList";
this.dropDownList.SelectedValue = "";
this.dropDownList.Size = new System.Drawing.Size(243, 29);
this.dropDownList.TabIndex = 4;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 78);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(68, 15);
this.label3.TabIndex = 5;
this.label3.Text = "Subdivision";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(12, 109);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(35, 15);
this.label4.TabIndex = 6;
this.label4.Text = "Posts";
//
// textBoxPosts
//
this.textBoxPosts.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxPosts.Location = new System.Drawing.Point(53, 107);
this.textBoxPosts.Name = "textBoxPosts";
this.textBoxPosts.Size = new System.Drawing.Size(272, 23);
this.textBoxPosts.TabIndex = 7;
//
// buttonCreate
//
this.buttonCreate.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.buttonCreate.Location = new System.Drawing.Point(12, 141);
this.buttonCreate.Name = "buttonCreate";
this.buttonCreate.Size = new System.Drawing.Size(313, 26);
this.buttonCreate.TabIndex = 8;
this.buttonCreate.Text = "Create";
this.buttonCreate.UseVisualStyleBackColor = true;
this.buttonCreate.Click += new System.EventHandler(this.ButtonCreate_Click);
//
// EmployerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(337, 179);
this.Controls.Add(this.buttonCreate);
this.Controls.Add(this.textBoxPosts);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.dropDownList);
this.Controls.Add(this.customInputRangeNumber);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBoxFio);
this.Name = "EmployerForm";
this.Text = "EmployerForm";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.EmployerForm_FormClosed);
this.Load += new System.EventHandler(this.EmployerForm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxFio;
private Label label1;
private Label label2;
private MyCustomComponents.CustomInputRangeNumber customInputRangeNumber;
private CustomComponent.DropDownList dropDownList;
private Label label3;
private Label label4;
private TextBox textBoxPosts;
private Button buttonCreate;
}
}

View File

@@ -0,0 +1,103 @@
using DocumentFormat.OpenXml.InkML;
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.BusinessLogicContracts;
using EnterpriseContracts.ViewModels;
using EnterpriseDataBaseImplement;
using EnterpriseDataBaseImplement.Models;
using System.Data;
namespace Ivanov_App
{
public partial class EmployerForm : Form
{
private readonly IEmployeeLogic _logic;
private readonly ISubdivisionLogic _logicS;
public int? Id { get; set; }
public EmployerForm(IEmployeeLogic logic, ISubdivisionLogic logicS)
{
InitializeComponent();
_logic = logic;
_logicS = logicS;
customInputRangeNumber.MinValue = 1;
customInputRangeNumber.MaxValue = 30;
customInputRangeNumber.Value = 1;
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
try
{
_logic.CreateOrUpdate(new EmployeeBindingModel
{
Id = Id,
Fio = textBoxFio.Text,
Subdivision = dropDownList.SelectedValue,
Posts = textBoxPosts.Text,
Experience = (int)customInputRangeNumber.Value
});
var context = new EnterpriseDataBase();
var employee = context.Employees.FirstOrDefault(e => e.Fio == textBoxFio.Text);
if (employee == null)
{
throw new Exception("Employee not found or not created.");
}
var employeePosts = new EmployeePosts
{
EmployeeId = employee.Id,
Posts = textBoxPosts.Text
};
context.EmployeePosts.Add(employeePosts);
context.SaveChanges();
MessageBox.Show("Successfully created employee and associated posts.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void EmployerForm_Load(object sender, EventArgs e)
{
List<SubdivisionViewModel>? viewS = _logicS.Read(null);
if (viewS != null)
{
dropDownList.Items.AddRange(viewS.Select(x => x.Name).ToArray());
}
if (Id.HasValue)
{
try
{
EmployeeViewModel? view = _logic.Read(new EmployeeBindingModel { Id = Id.Value })?[0];
if (view != null)
{
textBoxFio.Text = view.Fio;
dropDownList.SelectedValue = view.Subdivision;
customInputRangeNumber.Value = view.Experience;
textBoxPosts.Text = view.Posts;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void EmployerForm_FormClosed(object sender, FormClosedEventArgs e)
{
DialogResult = DialogResult.Cancel;
}
}
}

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>

173
KOP/Ivanov_App/FormMain.Designer.cs generated Normal file
View File

@@ -0,0 +1,173 @@
namespace Ivanov_App
{
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.components = new System.ComponentModel.Container();
this.listBoxMany = new CustomComponent.ListBoxMany();
this.excelTable = new Ivanov_components.ExcelTable(this.components);
this.componentDiagramToPdf = new CustomComponent.ComponentDiagramToPdf(this.components);
this.wordWithTable = new MyCustomComponent.WordWithTable(this.components);
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.actionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.createEmployerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editEmployerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.deleteEmployerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.excelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.wordToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.pdfToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.directoryToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// listBoxMany
//
this.listBoxMany.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.listBoxMany.Dock = System.Windows.Forms.DockStyle.Fill;
this.listBoxMany.Location = new System.Drawing.Point(0, 24);
this.listBoxMany.Name = "listBoxMany";
this.listBoxMany.SelectedIndex = -1;
this.listBoxMany.Size = new System.Drawing.Size(895, 453);
this.listBoxMany.TabIndex = 1;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.actionToolStripMenuItem,
this.directoryToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(895, 24);
this.menuStrip1.TabIndex = 2;
this.menuStrip1.Text = "menuStrip1";
//
// actionToolStripMenuItem
//
this.actionToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.createEmployerToolStripMenuItem,
this.editEmployerToolStripMenuItem,
this.deleteEmployerToolStripMenuItem,
this.excelToolStripMenuItem,
this.wordToolStripMenuItem,
this.pdfToolStripMenuItem});
this.actionToolStripMenuItem.Name = "actionToolStripMenuItem";
this.actionToolStripMenuItem.Size = new System.Drawing.Size(54, 20);
this.actionToolStripMenuItem.Text = "Action";
//
// createEmployerToolStripMenuItem
//
this.createEmployerToolStripMenuItem.Name = "createEmployerToolStripMenuItem";
this.createEmployerToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A)));
this.createEmployerToolStripMenuItem.Size = new System.Drawing.Size(203, 22);
this.createEmployerToolStripMenuItem.Text = "Create Employer";
this.createEmployerToolStripMenuItem.Click += new System.EventHandler(this.CreateEmployerToolStripMenuItem_Click);
//
// editEmployerToolStripMenuItem
//
this.editEmployerToolStripMenuItem.Name = "editEmployerToolStripMenuItem";
this.editEmployerToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.U)));
this.editEmployerToolStripMenuItem.Size = new System.Drawing.Size(203, 22);
this.editEmployerToolStripMenuItem.Text = "Edit Employer";
this.editEmployerToolStripMenuItem.Click += new System.EventHandler(this.EditEmployerToolStripMenuItem_Click_1);
//
// deleteEmployerToolStripMenuItem
//
this.deleteEmployerToolStripMenuItem.Name = "deleteEmployerToolStripMenuItem";
this.deleteEmployerToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D)));
this.deleteEmployerToolStripMenuItem.Size = new System.Drawing.Size(203, 22);
this.deleteEmployerToolStripMenuItem.Text = "Delete Employer";
this.deleteEmployerToolStripMenuItem.Click += new System.EventHandler(this.DeleteEmployerToolStripMenuItem_Click_1);
//
// excelToolStripMenuItem
//
this.excelToolStripMenuItem.Name = "excelToolStripMenuItem";
this.excelToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.excelToolStripMenuItem.Size = new System.Drawing.Size(203, 22);
this.excelToolStripMenuItem.Text = "Excel";
this.excelToolStripMenuItem.Click += new System.EventHandler(this.ExcelToolStripMenuItem_Click);
//
// wordToolStripMenuItem
//
this.wordToolStripMenuItem.Name = "wordToolStripMenuItem";
this.wordToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.T)));
this.wordToolStripMenuItem.Size = new System.Drawing.Size(203, 22);
this.wordToolStripMenuItem.Text = "Word";
this.wordToolStripMenuItem.Click += new System.EventHandler(this.WordToolStripMenuItem_Click);
//
// pdfToolStripMenuItem
//
this.pdfToolStripMenuItem.Name = "pdfToolStripMenuItem";
this.pdfToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.pdfToolStripMenuItem.Size = new System.Drawing.Size(203, 22);
this.pdfToolStripMenuItem.Text = "Pdf";
this.pdfToolStripMenuItem.Click += new System.EventHandler(this.PdfToolStripMenuItem_Click);
//
// directoryToolStripMenuItem
//
this.directoryToolStripMenuItem.Checked = true;
this.directoryToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked;
this.directoryToolStripMenuItem.Name = "directoryToolStripMenuItem";
this.directoryToolStripMenuItem.Size = new System.Drawing.Size(67, 20);
this.directoryToolStripMenuItem.Text = "Directory";
this.directoryToolStripMenuItem.Click += new System.EventHandler(this.DirectoryToolStripMenuItem_Click);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(895, 477);
this.Controls.Add(this.listBoxMany);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMain";
this.Text = "Bazunov Application";
this.Load += new System.EventHandler(this.FormMain_Load);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private MyCustomComponents.CustomTreeCell customTreeCell1;
private CustomComponent.ListBoxMany listBoxMany;
private Ivanov_components.ExcelTable excelTable;
private CustomComponent.ComponentDiagramToPdf componentDiagramToPdf;
private MyCustomComponent.WordWithTable wordWithTable;
private MenuStrip menuStrip1;
private ToolStripMenuItem actionToolStripMenuItem;
private ToolStripMenuItem createEmployerToolStripMenuItem;
private ToolStripMenuItem editEmployerToolStripMenuItem;
private ToolStripMenuItem deleteEmployerToolStripMenuItem;
private ToolStripMenuItem excelToolStripMenuItem;
private ToolStripMenuItem wordToolStripMenuItem;
private ToolStripMenuItem pdfToolStripMenuItem;
private ToolStripMenuItem directoryToolStripMenuItem;
}
}

220
KOP/Ivanov_App/FormMain.cs Normal file
View File

@@ -0,0 +1,220 @@
using EnterpriseContracts.BindingModels;
using EnterpriseContracts.BusinessLogicContracts;
using EnterpriseContracts.ViewModels;
using EnterpriseDataBaseImplement;
using MyCustomComponent;
using MyCustomComponents.Models;
using System.Data;
using Unity;
namespace Ivanov_App
{
public partial class FormMain : Form
{
private readonly IEmployeeLogic _LogicE;
private readonly ISubdivisionLogic _LogicS;
public FormMain(IEmployeeLogic logicE, ISubdivisionLogic logicS)
{
InitializeComponent();
_LogicE = logicE;
_LogicS = logicS;
}
private void DropComponents()
{
Controls.Clear();
InitializeComponent();
}
private List<string> originalStrings = new();
private void LoadData()
{
try
{
DropComponents();
listBoxMany.SetLayout("{Id} {Subdivision} {Fio} {Experience}", "{", "}");
var list = _LogicE.Read(null) ?? throw new Exception("Error on read");
originalStrings.Clear();
for (int i = 0; i < list.Count; i++)
{
string originalString = $"{list[i].Subdivision} {list[i].Id} {list[i].Fio} {list[i].Experience}";
originalStrings.Add(originalString);
listBoxMany.AddItemInList(list[i], i, "Id");
listBoxMany.AddItemInList(list[i], i, "Subdivision");
listBoxMany.AddItemInList(list[i], i, "Fio");
listBoxMany.AddItemInList(list[i], i, "Experience");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void CreateEmployerToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = Program.Container.Resolve<EmployerForm>();
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
private void EditEmployerToolStripMenuItem_Click_1(object sender, EventArgs e)
{
var form = Program.Container.Resolve<EmployerForm>();
form.Id = Convert.ToInt32(listBoxMany.GetItemFromList<EmployeeViewModel>().Id);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
LoadData();
}
private void DeleteEmployerToolStripMenuItem_Click_1(object sender, EventArgs e)
{
if (MessageBox.Show("Delete record", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
var ent = listBoxMany.GetItemFromList<EmployeeViewModel>();
try
{
int id = Convert.ToInt32(ent.Id);
_LogicE.Delete(new EmployeeBindingModel { Id = id });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
private void ExcelToolStripMenuItem_Click(object sender, EventArgs e)
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "xlsx|*.xlsx" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Success", "Ready", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
var context = new EnterpriseDataBase();
var employeeId = listBoxMany.GetItemFromList<EmployeeViewModel>().Id;
var employee = context.Employees.FirstOrDefault(e => e.Id == employeeId);
if (employee == null)
{
MessageBox.Show("Сотрудник не найден.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var lastFivePosts = context.EmployeePosts.Where(p => p.EmployeeId == employeeId).OrderByDescending(p => p.Id)
.Take(5).Select(p => p.Posts).ToArray();
var Data = new string[1, 5];
for (int i = 0; i < lastFivePosts.Length; i++)
{
Data[0, i] = lastFivePosts[i];
}
for (int i = lastFivePosts.Length; i < 5; i++)
{
Data[0, i] = string.Empty;
}
excelTable.CreateDoc(new Ivanov_components.Models.TableConfig
{
FilePath = fileName,
Header = "Последние 5 должностей",
Data = new List<string[,]> { Data }
});
}
private void WordToolStripMenuItem_Click(object sender, EventArgs e)
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "docx|*.docx" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Success", "Ready", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
var list = _LogicE.Read(null);
var wordWithTable = new WordWithTable();
wordWithTable.CreateDoc(new WordWithTableDataConfig<EmployeeViewModel>
{
FilePath = fileName,
Header = "Table:",
UseUnion = true,
ColumnsRowsWidth = new List<(int, int)> { (0, 5), (0, 5), (0, 10), (0, 10) },
ColumnUnion = new List<(int StartIndex, int Count)> { (2, 2) },
Headers = new List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)>
{
(0, 0, "Id", "Id"),
(1, 0, "Fio", "Fio"),
(2, 0, "Work", ""),
(2, 1, "Subdivision", "Subdivision"),
(3, 1, "Experience", "Experience"),
},
Data = list
});
}
private void PdfToolStripMenuItem_Click(object sender, EventArgs e)
{
string fileName = "";
using (var dialog = new SaveFileDialog { Filter = "pdf|*.pdf" })
{
if (dialog.ShowDialog() == DialogResult.OK)
{
fileName = dialog.FileName.ToString();
MessageBox.Show("Success", "Ready", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
var listEmp = _LogicE.Read(null);
var listSubd = _LogicS.Read(null);
var Data = new Dictionary<string, List<(string Name, double Value)>>();
foreach (var item in listSubd)
{
var listSorted = listEmp.Where(x => x.Subdivision.Equals(item.Name));
var x = (
listSorted.Where(y => y.Experience >= 1 && y.Experience < 5).Count(),
listSorted.Where(y => y.Experience >= 5 && y.Experience < 10).Count(),
listSorted.Where(y => y.Experience >= 10 && y.Experience < 20).Count(),
listSorted.Where(y => y.Experience >= 20 && y.Experience < 30).Count());
Data.Add(item.Name, new() { ("1-5", x.Item1), ("5-10", x.Item2), ("10-20", x.Item3), ("20-30", x.Item4) });
}
componentDiagramToPdf.CreateDoc(new()
{
FilePath = fileName,
Header = "Chart",
ChartTitle = "Chart",
Data = Data
});
}
private void DirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
var form = Program.Container.Resolve<Directory>();
form.ShowDialog();
}
}
}

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,31 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<AllowUnsafeBlocks>False</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="CustomComponent" Version="1.0.0" />
<PackageReference Include="Ivanov_components" Version="1.0.0" />
<PackageReference Include="Ivanov_visual_components" 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="MyCustomComponent" Version="1.0.0" />
<PackageReference Include="MyCustomComponents" Version="1.0.0" />
<PackageReference Include="Unity" Version="5.11.10" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\EnterpriseBusinessLogic\EnterpriseBusinessLogic.csproj" />
<ProjectReference Include="..\EnterpriseContracts\EnterpriseContracts.csproj" />
<ProjectReference Include="..\EnterpriseDataBaseImplement\EnterpriseDataBaseImplement.csproj" />
</ItemGroup>
</Project>

40
KOP/Ivanov_App/Program.cs Normal file
View File

@@ -0,0 +1,40 @@
using EnterpriseBusinessLogic.BusinessLogics;
using EnterpriseContracts.BusinessLogicContracts;
using EnterpriseContracts.StorageContracts;
using EnterpriseDataBaseImplement.Implements;
using Unity.Lifetime;
using Unity;
namespace Ivanov_App
{
internal static class Program
{
private static IUnityContainer? container = null;
public static IUnityContainer Container { get { container ??= BuildUnityContainer(); return container; } }
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(Container.Resolve<FormMain>());
}
private static IUnityContainer BuildUnityContainer()
{
var currentContainer = new UnityContainer();
currentContainer.RegisterType<IEmployeeStorage, EmployeeStorage>(new HierarchicalLifetimeManager());
currentContainer.RegisterType<ISubdivisionStorage, SubdivisionStorage>(new HierarchicalLifetimeManager());
currentContainer.RegisterType<IEmployeeLogic, EmployeeLogic>(new HierarchicalLifetimeManager());
currentContainer.RegisterType<ISubdivisionLogic, SubdivisionLogic>(new HierarchicalLifetimeManager());
currentContainer.RegisterType<EmployerForm>();
currentContainer.RegisterType<Directory>();
return currentContainer;
}
}
}

View File

@@ -0,0 +1,36 @@
namespace Ivanov_components
{
partial class ExcelGistogram
{
/// <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,29 @@
using Ivanov_components.Helpers;
using Ivanov_components.Models;
using System.ComponentModel;
namespace Ivanov_components
{
public partial class ExcelGistogram : Component
{
public ExcelGistogram()
{
InitializeComponent();
}
public ExcelGistogram(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateDoc(ChartConfig config)
{
config.CheckFields();
IContext creator = new WorkWithExcel();
creator.CreateHeader(config.Header);
creator.CreateBarChart(config);
creator.SaveDoc(config.FilePath);
}
}
}

View File

@@ -0,0 +1,36 @@
namespace Ivanov_components
{
partial class ExcelTable
{
/// <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,36 @@
using Ivanov_components.Helpers;
using Ivanov_components.Models;
using System.ComponentModel;
namespace Ivanov_components
{
public partial class ExcelTable : Component
{
public ExcelTable()
{
InitializeComponent();
}
public ExcelTable(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateDoc(TableConfig config)
{
config.CheckFields();
IContext creator = new WorkWithExcel();
creator.CreateHeader(config.Header);
if (config.Data != null)
{
foreach (var datum in config.Data)
{
creator.CreateTable(datum);
}
}
creator.SaveDoc(config.FilePath);
}
}
}

View File

@@ -0,0 +1,36 @@
namespace Ivanov_components
{
partial class ExcelWithCustomTable
{
/// <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,55 @@
using Ivanov_components.Helpers;
using Ivanov_components.Models;
using System.ComponentModel;
namespace Ivanov_components
{
public partial class ExcelWithCustomTable : Component
{
public ExcelWithCustomTable()
{
InitializeComponent();
}
public ExcelWithCustomTable(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateDoc<T>(TableWithHeaderConfig<T> config)
{
config.CheckFields();
config.ColumnsRowsDataCount = (config.ColumnsRowsWidth.Count, config.Data.Count + 1);
IContext creator = new WorkWithExcel();
creator.CreateHeader(config.Header);
creator.CreateTableWithHeader();
creator.CreateMultiHeader(config);
var array = new string[config.Data.Count, config.Headers.Count];
for (var j = 0; j < config.Data.Count; j++)
{
for (var i = 0; i < config.Headers.Count; i++)
{
(int, int, string, string) first = (0, 0, null, null)!;
foreach (var x in config.Headers.Where(x => x.ColumnIndex == i))
{
first = x;
break;
}
var (_, _, _, name) = first;
if (name != null)
{
object? value = config.Data[j]?.GetType().GetProperty(name)!.GetValue(config.Data[j], null);
array[j, i] = value == null
? config.NullReplace
: value.ToString();
}
}
}
creator.LoadDataToTableWithMultiHeader(array, config.ColumnsRowsWidth[1].Row);
creator.SaveDoc(config.FilePath);
}
}
}

View File

@@ -0,0 +1,453 @@
using System.Globalization;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml;
using Ivanov_components.Models;
using static System.String;
using Index = DocumentFormat.OpenXml.Drawing.Charts.Index;
using Orientation = DocumentFormat.OpenXml.Drawing.Charts.Orientation;
namespace Ivanov_components.Helpers
{
public static class ChartGenerator
{
private static uint _order;
private static uint _index = 1u;
public static DocumentFormat.OpenXml.Drawing.Charts.Chart GenerateBarChart(ChartConfig config)
{
var axisId = new AxisId
{
Val = (UInt32Value)97045504u
};
var axisId2 = new AxisId
{
Val = (UInt32Value)97055488u
};
var barChart = new BarChart();
barChart.Append(new BarDirection
{
Val = (EnumValue<BarDirectionValues>)BarDirectionValues.Column
});
barChart.Append(new BarGrouping
{
Val = (EnumValue<BarGroupingValues>)BarGroupingValues.Clustered
});
if (config.Data != null)
{
barChart.Append(
GenerateBarChartSeries(config.Data.First().Key, config.Data.First().Value));
}
barChart.Append(axisId);
barChart.Append(axisId2);
var outline = new Outline
{
Width = (Int32Value)25400
};
outline.Append(new NoFill());
var shapeProperties = new DocumentFormat.OpenXml.Drawing.Charts.ShapeProperties();
shapeProperties.Append(new NoFill());
shapeProperties.Append(outline);
var plotArea = new PlotArea();
plotArea.Append(new Layout());
plotArea.Append(barChart);
plotArea.Append(GenerateCategoryAxis(axisId, AxisPositionValues.Bottom, axisId2));
plotArea.Append(GenerateValueAxis(axisId2, AxisPositionValues.Left, axisId));
plotArea.Append(shapeProperties);
return GenerateChart(config.ChartTitle, plotArea, config.LegendLocation);
}
private static DocumentFormat.OpenXml.Drawing.Charts.Chart GenerateChart(
string titleText,
OpenXmlElement plotArea,
Location legendLocation)
{
var chart = new DocumentFormat.OpenXml.Drawing.Charts.Chart();
if (IsNullOrWhiteSpace(titleText))
{
chart.Append(GenerateTitle(titleText));
}
else
{
chart.Append(new AutoTitleDeleted
{
Val = (BooleanValue)true
});
}
var position = legendLocation switch
{
Location.Top => LegendPositionValues.Top,
Location.Right => LegendPositionValues.Right,
Location.Left => LegendPositionValues.Left,
_ => LegendPositionValues.Bottom,
};
chart.Append(plotArea);
chart.Append(GenerateLegend(position));
chart.Append(new PlotVisibleOnly
{
Val = (BooleanValue)true
});
return chart;
}
private static Title GenerateTitle(string titleText)
{
var run = new Run();
run.Append(new RunProperties
{
FontSize = (Int32Value)1100
});
run.Append(new Text(titleText));
var paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(new DefaultRunProperties
{
FontSize = (Int32Value)1100
});
var paragraph = new Paragraph();
paragraph.Append(paragraphProperties);
paragraph.Append(run);
var richText = new RichText();
richText.Append(new BodyProperties());
richText.Append(new ListStyle());
richText.Append(paragraph);
var chartText = new ChartText();
chartText.Append(richText);
var title = new Title();
title.Append(chartText);
title.Append(new Layout());
title.Append(new Overlay
{
Val = (BooleanValue)false
});
return title;
}
private static BarChartSeries GenerateBarChartSeries(
string seriesName,
IReadOnlyCollection<(string Name, double Value)> data)
{
var barChartSeries = new BarChartSeries();
barChartSeries.Append(new Index
{
Val = (UInt32Value)_index
});
barChartSeries.Append(new Order
{
Val = (UInt32Value)_order
});
barChartSeries.Append(GenerateSeriesText(seriesName));
barChartSeries.Append(GenerateCategoryAxisData(data.Select(c => c.Name).ToArray()));
barChartSeries.Append(GenerateValues(data.Select(v => v.Value).ToArray()));
_index++; _order++;
return barChartSeries;
}
private static SeriesText GenerateSeriesText(string seriesName)
{
var stringPoint = new StringPoint
{
Index = (UInt32Value)0u
};
stringPoint.Append(new NumericValue
{
Text = seriesName
});
var stringCache = new StringCache();
stringCache.Append(new PointCount
{
Val = (UInt32Value)1u
});
stringCache.Append(stringPoint);
var stringReference = new StringReference();
stringReference.Append(stringCache);
var seriesText = new SeriesText();
seriesText.Append(stringReference);
return seriesText;
}
private static CategoryAxisData GenerateCategoryAxisData(IReadOnlyList<string> data)
{
var num = (uint)data.Count;
var stringCache = GenerateStringCache(num);
for (var num2 = 0u; num2 < num; num2++)
{
stringCache.Append(GenerateStringPoint(num2, data[(int)num2]));
}
var stringReference = new StringReference();
stringReference.Append(stringCache);
var categoryAxisData = new CategoryAxisData();
categoryAxisData.Append(stringReference);
return categoryAxisData;
}
private static Values GenerateValues(double[] data)
{
var num = (uint)data.Length;
var numberingCache = GenerateNumberingCache(num);
for (var num2 = 0u; num2 < num; num2++)
{
numberingCache.Append(GenerateNumericPoint(num2, data[num2]
.ToString(CultureInfo.CurrentCulture)));
}
var numberReference = new NumberReference();
numberReference.Append(numberingCache);
var values = new Values();
values.Append(numberReference);
return values;
}
private static NumberingCache GenerateNumberingCache(uint numPoints)
{
var numberingCache = new NumberingCache();
numberingCache.Append(new FormatCode
{
Text = "General"
});
numberingCache.Append(new PointCount
{
Val = (UInt32Value)numPoints
});
return numberingCache;
}
private static StringCache GenerateStringCache(uint numPoints)
{
var stringCache = new StringCache();
stringCache.Append(new PointCount
{
Val = (UInt32Value)numPoints
});
return stringCache;
}
private static NumericPoint GenerateNumericPoint(UInt32Value idx, string text)
{
var numericPoint = new NumericPoint
{
Index = idx
};
numericPoint.Append(new NumericValue
{
Text = text
});
return numericPoint;
}
private static StringPoint GenerateStringPoint(UInt32Value idx, string text)
{
var stringPoint = new StringPoint
{
Index = idx
};
stringPoint.Append(new NumericValue
{
Text = text
});
return stringPoint;
}
private static CategoryAxis GenerateCategoryAxis(
UnsignedIntegerType axisId,
AxisPositionValues axisPosition,
UnsignedIntegerType crossingAxisId)
{
var scaling = new Scaling();
scaling.Append(new Orientation
{
Val = (EnumValue<OrientationValues>)OrientationValues.MinMax
});
var solidFill = new SolidFill();
solidFill.Append(new RgbColorModelHex
{
Val = (HexBinaryValue)"000000"
});
var defaultRunProperties = new DefaultRunProperties
{
FontSize = (Int32Value)1000,
Bold = (BooleanValue)false,
Italic = (BooleanValue)false,
Underline = (EnumValue<TextUnderlineValues>)TextUnderlineValues.None,
Strike = (EnumValue<TextStrikeValues>)TextStrikeValues.NoStrike,
Baseline = (Int32Value)0
};
defaultRunProperties.Append(solidFill);
var paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(defaultRunProperties);
var paragraph = new Paragraph();
paragraph.Append(paragraphProperties);
paragraph.Append(new EndParagraphRunProperties());
var textProperties = new TextProperties();
textProperties.Append(new BodyProperties
{
Rotation = (Int32Value)(-1800000),
Vertical = (EnumValue<TextVerticalValues>)TextVerticalValues.Horizontal
});
textProperties.Append(new ListStyle());
textProperties.Append(paragraph);
var categoryAxis = new CategoryAxis();
categoryAxis.Append(new AxisId
{
Val = axisId.Val
});
categoryAxis.Append(scaling);
categoryAxis.Append(new AxisPosition
{
Val = (EnumValue<AxisPositionValues>)axisPosition
});
categoryAxis.Append(new NumberingFormat
{
FormatCode = (StringValue)"General",
SourceLinked = (BooleanValue)true
});
categoryAxis.Append(new TickLabelPosition
{
Val = (EnumValue<TickLabelPositionValues>)TickLabelPositionValues.Low
});
categoryAxis.Append(GenerateChartShapeProperties(3175));
categoryAxis.Append(textProperties);
categoryAxis.Append(new CrossingAxis
{
Val = crossingAxisId.Val
});
categoryAxis.Append(new Crosses
{
Val = (EnumValue<CrossesValues>)CrossesValues.AutoZero
});
categoryAxis.Append(new AutoLabeled
{
Val = (BooleanValue)true
});
categoryAxis.Append(new LabelAlignment
{
Val = (EnumValue<LabelAlignmentValues>)LabelAlignmentValues.Center
});
categoryAxis.Append(new LabelOffset
{
Val = (UInt16Value)(ushort)100
});
categoryAxis.Append(new TickLabelSkip
{
Val = (Int32Value)1
});
categoryAxis.Append(new TickMarkSkip
{
Val = (Int32Value)1
});
return categoryAxis;
}
private static ValueAxis GenerateValueAxis(
UnsignedIntegerType axisId,
AxisPositionValues position,
UnsignedIntegerType crossingAxisId)
{
var scaling = new Scaling();
scaling.Append(new Orientation
{
Val = (EnumValue<OrientationValues>)OrientationValues.MinMax
});
var paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(new DefaultRunProperties());
var paragraph = new Paragraph();
paragraph.Append(paragraphProperties);
paragraph.Append(new EndParagraphRunProperties());
var textProperties = new TextProperties();
textProperties.Append(new BodyProperties());
textProperties.Append(new ListStyle());
textProperties.Append(paragraph);
var valueAxis = new ValueAxis();
valueAxis.Append(new AxisId
{
Val = axisId.Val
});
valueAxis.Append(scaling);
valueAxis.Append(new Delete
{
Val = (BooleanValue)false
});
valueAxis.Append(new AxisPosition
{
Val = (EnumValue<AxisPositionValues>)position
});
valueAxis.Append(new MajorGridlines());
valueAxis.Append(new NumberingFormat
{
FormatCode = (StringValue)"General",
SourceLinked = (BooleanValue)false
});
valueAxis.Append(new MajorTickMark
{
Val = (EnumValue<TickMarkValues>)TickMarkValues.None
});
valueAxis.Append(new TickLabelPosition
{
Val = (EnumValue<TickLabelPositionValues>)TickLabelPositionValues.NextTo
});
valueAxis.Append(GenerateChartShapeProperties(9525));
valueAxis.Append(textProperties);
valueAxis.Append(new CrossingAxis
{
Val = crossingAxisId.Val
});
valueAxis.Append(new Crosses
{
Val = (EnumValue<CrossesValues>)CrossesValues.AutoZero
});
valueAxis.Append(new CrossBetween
{
Val = (EnumValue<CrossBetweenValues>)CrossBetweenValues.Between
});
return valueAxis;
}
private static ChartShapeProperties GenerateChartShapeProperties(int width)
{
var solidFill = new SolidFill();
solidFill.Append(new RgbColorModelHex
{
Val = (HexBinaryValue)"000000"
});
var outline = new Outline
{
Width = (Int32Value)width
};
outline.Append(solidFill);
outline.Append(new PresetDash
{
Val = (EnumValue<PresetLineDashValues>)PresetLineDashValues.Solid
});
var chartShapeProperties = new ChartShapeProperties();
chartShapeProperties.Append(outline);
return chartShapeProperties;
}
private static Legend GenerateLegend(LegendPositionValues position)
{
var paragraphProperties = new ParagraphProperties();
paragraphProperties.Append(new DefaultRunProperties());
var paragraph = new Paragraph();
paragraph.Append(paragraphProperties);
paragraph.Append(new EndParagraphRunProperties());
var textProperties = new TextProperties();
textProperties.Append(new BodyProperties());
textProperties.Append(new ListStyle());
textProperties.Append(paragraph);
var legend = new Legend();
legend.Append(new LegendPosition
{
Val = (EnumValue<LegendPositionValues>)position
});
legend.Append(new Layout());
legend.Append(new Overlay
{
Val = (BooleanValue)false
});
legend.Append(textProperties);
return legend;
}
}
}

View File

@@ -0,0 +1,12 @@
using Ivanov_components.Models;
namespace Ivanov_components.Helpers
{
public interface IContext : ICreator
{
void CreateTable(string[,] data);
void CreateTableWithHeader();
void CreateMultiHeader<T>(TableWithHeaderConfig<T> config);
void LoadDataToTableWithMultiHeader(string[,] data, int rowHeight);
}
}

View File

@@ -0,0 +1,11 @@
using Ivanov_components.Models;
namespace Ivanov_components.Helpers
{
public interface ICreator
{
void CreateHeader(string header);
void SaveDoc(string filepath);
void CreateBarChart(ChartConfig config);
}
}

View File

@@ -0,0 +1,414 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using Ivanov_components.Models;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using DocumentFormat.OpenXml.Drawing;
namespace Ivanov_components.Helpers
{
public class WorkWithExcel : IContext
{
private uint _index;
private SheetData? _sheetData;
private uint _startRowIndex;
private Columns? _columns;
private DocumentFormat.OpenXml.Drawing.Charts.Chart? _chart;
private SheetData SheetData => _sheetData ??= new SheetData();
private Columns Columns => _columns ??= new Columns();
public void CreateBarChart(ChartConfig config)
{
_chart = ChartGenerator.GenerateBarChart(config);
}
public void CreateMultiHeader<T>(TableWithHeaderConfig<T> config)
{
var counter = 1u;
var num = 2;
if (config.ColumnsRowsWidth != null)
{
foreach (var item in config.ColumnsRowsWidth.Where(x => x.Column > 0))
{
Columns.Append(new Column
{
Min = (UInt32Value)counter,
Max = (UInt32Value)counter,
Width = (DoubleValue)(item.Column * num),
CustomWidth = (BooleanValue)true
});
counter++;
}
counter = _startRowIndex;
num = 5;
if ((from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == counter
select r).Any())
{
var row = (from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == counter
select r).First();
row.Height = (DoubleValue)(config.ColumnsRowsWidth[0].Row * num);
row.CustomHeight = (BooleanValue)true;
}
else
{
SheetData.Append(new Row
{
RowIndex = (UInt32Value)counter,
Height = (DoubleValue)(config.ColumnsRowsWidth[0].Row * num),
CustomHeight = (BooleanValue)true
});
}
}
const uint styleIndex = 2u;
if (config.Headers == null) return;
{
var num3 = config.Headers.Count(x => x.ColumnIndex > 0);
CreateCell(0, _startRowIndex,
config.Headers.FirstOrDefault<(int, int, string, string)>
(((int ColumnIndex, int RowIndex, string Header, string PropertyName) x)
=> x is { ColumnIndex: 0, RowIndex: 0 }).Item3, styleIndex);
for (var i = 0; i < num3; i++)
{
CreateCell(i + 1, _startRowIndex, config.Headers.FirstOrDefault<(int, int, string, string)>
(((int ColumnIndex, int RowIndex, string Header, string PropertyName) x)
=> x.ColumnIndex == i + 1 && x.RowIndex == 0).Item3, styleIndex);
}
}
}
private static void GenerateStyle(OpenXmlPartContainer workbookPart)
{
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
var fonts = new DocumentFormat.OpenXml.Spreadsheet.Fonts
{
Count = (UInt32Value)2u,
KnownFonts = BooleanValue.FromBoolean(value: true)
};
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize
{
Val = (DoubleValue)11.0
},
FontName = new FontName
{
Val = (StringValue)"Calibri"
},
FontFamilyNumbering = new FontFamilyNumbering
{
Val = (Int32Value)2
},
FontScheme = new DocumentFormat.OpenXml.Spreadsheet.FontScheme
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize
{
Val = (DoubleValue)11.0
},
FontName = new FontName
{
Val = (StringValue)"Calibri"
},
FontFamilyNumbering = new FontFamilyNumbering
{
Val = (Int32Value)2
},
FontScheme = new DocumentFormat.OpenXml.Spreadsheet.FontScheme
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
},
Bold = new Bold()
});
workbookStylesPart.Stylesheet.Append(fonts);
var fills = new Fills
{
Count = (UInt32Value)1u
};
fills.Append(new DocumentFormat.OpenXml.Spreadsheet.Fill
{
PatternFill = new DocumentFormat.OpenXml.Spreadsheet.PatternFill
{
PatternType = new EnumValue<PatternValues>(PatternValues.None)
}
});
workbookStylesPart.Stylesheet.Append(fills);
var borders = new Borders
{
Count = (UInt32Value)2u
};
borders.Append(new Border
{
LeftBorder = new DocumentFormat.OpenXml.Spreadsheet.LeftBorder(),
RightBorder = new DocumentFormat.OpenXml.Spreadsheet.RightBorder(),
TopBorder = new DocumentFormat.OpenXml.Spreadsheet.TopBorder(),
BottomBorder = new DocumentFormat.OpenXml.Spreadsheet.BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
borders.Append(new Border
{
LeftBorder = new DocumentFormat.OpenXml.Spreadsheet.LeftBorder
{
Style = (EnumValue<BorderStyleValues>)BorderStyleValues.Thin
},
RightBorder = new DocumentFormat.OpenXml.Spreadsheet.RightBorder
{
Style = (EnumValue<BorderStyleValues>)BorderStyleValues.Thin
},
TopBorder = new DocumentFormat.OpenXml.Spreadsheet.TopBorder
{
Style = (EnumValue<BorderStyleValues>)BorderStyleValues.Thin
},
BottomBorder = new DocumentFormat.OpenXml.Spreadsheet.BottomBorder
{
Style = (EnumValue<BorderStyleValues>)BorderStyleValues.Thin
}
});
workbookStylesPart.Stylesheet.Append(borders);
var cellFormats = new CellFormats
{
Count = (UInt32Value)3u
};
cellFormats.Append(new CellFormat
{
NumberFormatId = (UInt32Value)0u,
FormatId = (UInt32Value)0u,
FontId = (UInt32Value)0u,
BorderId = (UInt32Value)0u,
FillId = (UInt32Value)0u
});
cellFormats.Append(new CellFormat
{
NumberFormatId = (UInt32Value)0u,
FormatId = (UInt32Value)0u,
FontId = (UInt32Value)0u,
BorderId = (UInt32Value)1u,
FillId = (UInt32Value)0u
});
cellFormats.Append(new CellFormat
{
NumberFormatId = (UInt32Value)0u,
FormatId = (UInt32Value)0u,
FontId = (UInt32Value)1u,
BorderId = (UInt32Value)1u,
FillId = (UInt32Value)0u,
Alignment = new Alignment
{
Horizontal = (EnumValue<HorizontalAlignmentValues>)HorizontalAlignmentValues.Center,
Vertical = (EnumValue<VerticalAlignmentValues>)VerticalAlignmentValues.Center,
WrapText = (BooleanValue)true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
public void CreateHeader(string header)
{
_index = 1u;
var cell = CreateCell("A", _index);
var run = new DocumentFormat.OpenXml.Spreadsheet.Run();
run.Append(new DocumentFormat.OpenXml.Spreadsheet.Text(header));
run.RunProperties = new DocumentFormat.OpenXml.Spreadsheet.RunProperties(new Bold());
var inlineString = new InlineString();
inlineString.Append(run);
cell.Append(inlineString);
cell.DataType = (EnumValue<CellValues>)CellValues.InlineString;
_index++;
}
public void CreateTable(string[,] data)
{
for (var i = 0; i < data.GetLength(0); i++)
{
for (var j = 0; j < data.GetLength(1); j++)
{
CreateCell(j, (uint)(i + _index), data[i, j], 2u);
}
}
_index += (uint)data.GetLength(0);
}
private Cell CreateCell(string columnName, uint rowIndex)
{
var columnName2 = columnName;
var text = columnName2 + rowIndex;
Row row;
if ((from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == rowIndex
select r).Any())
{
row = (from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == rowIndex
select r).First();
}
else
{
row = new Row
{
RowIndex = (UInt32Value)rowIndex
};
SheetData.Append(row);
}
var cell = row.Elements<Cell>().FirstOrDefault(c => c.CellReference!.Value == columnName2 + rowIndex);
if (cell != null) return cell;
var referenceChild = row.Elements<Cell>()
.FirstOrDefault(
item => item.CellReference!.Value!.Length == text.Length &&
string.Compare(item.CellReference!.Value, text, StringComparison.OrdinalIgnoreCase) > 0);
cell = new Cell
{
CellReference = (StringValue)text
};
row.InsertBefore(cell, referenceChild);
return cell;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber++;
var num = columnNumber;
var text = string.Empty;
while (num > 0)
{
var num2 = (num - 1) % 26;
text = Convert.ToChar(65 + num2) + text;
num = (num - num2) / 26;
}
return text;
}
private void CreateCell(int columnIndex, uint rowIndex, string text, uint styleIndex)
{
var cell = CreateCell(GetExcelColumnName(columnIndex), rowIndex);
cell.CellValue = new CellValue(text);
cell.DataType = (EnumValue<CellValues>)CellValues.String;
cell.StyleIndex = (UInt32Value)styleIndex;
}
public void SaveDoc(string filepath)
{
if (string.IsNullOrEmpty(filepath))
{
throw new ArgumentNullException("File name is empty");
}
if (SheetData == null)
{
throw new ArgumentNullException("Dock body is empty! Nothing to save!");
}
using var spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
var workbookPart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookPart);
workbookPart.Workbook = new Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns != null)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(SheetData);
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet
{
Id = (StringValue)spreadsheetDocument.WorkbookPart!.GetIdOfPart(worksheetPart),
SheetId = (UInt32Value)1u,
Name = (StringValue)"List 1"
};
sheets.Append(sheet);
if (_chart == null) return;
var drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
worksheetPart.Worksheet.Append(new Drawing
{
Id = (StringValue)worksheetPart.GetIdOfPart(drawingsPart)
});
worksheetPart.Worksheet.Save();
var chartPart = drawingsPart.AddNewPart<ChartPart>();
chartPart.ChartSpace = new ChartSpace();
chartPart.ChartSpace.Append(new EditingLanguage
{
Val = new StringValue("en-US")
});
chartPart.ChartSpace.Append(_chart);
chartPart.ChartSpace.Save();
drawingsPart.WorksheetDrawing = new WorksheetDrawing();
var twoCellAnchor = drawingsPart.WorksheetDrawing.AppendChild(new TwoCellAnchor());
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.FromMarker(new ColumnId("2"), new ColumnOffset("581025"), new RowId("2"), new RowOffset("114300")));
twoCellAnchor.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.ToMarker(new ColumnId("17"), new ColumnOffset("276225"), new RowId("32"), new RowOffset("0")));
var graphicFrame = twoCellAnchor.AppendChild(new DocumentFormat.OpenXml.Drawing.Spreadsheet.GraphicFrame());
graphicFrame.Macro = (StringValue)"";
graphicFrame.Append(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameProperties(new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualDrawingProperties
{
Id = new UInt32Value(2u),
Name = (StringValue)"Chart 1"
}, new DocumentFormat.OpenXml.Drawing.Spreadsheet.NonVisualGraphicFrameDrawingProperties()));
graphicFrame.Append(new Transform(new Offset
{
X = (Int64Value)0L,
Y = (Int64Value)0L
}, new Extents
{
Cx = (Int64Value)0L,
Cy = (Int64Value)0L
}));
graphicFrame.Append(new Graphic(new GraphicData(new ChartReference
{
Id = (StringValue)drawingsPart.GetIdOfPart(chartPart)
})
{
Uri = (StringValue)"http://schemas.openxmlformats.org/drawingml/2006/chart"
}));
twoCellAnchor.Append(new ClientData());
drawingsPart.WorksheetDrawing.Save();
}
public void CreateTableWithHeader()
{
_startRowIndex = _index;
}
public void LoadDataToTableWithMultiHeader(string[,] data, int rowHeight)
{
const int num = 5;
for (var i = 0u; i < data.GetLength(0); i++)
{
if ((from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == i + 1
select r).Any())
{
var row = (from r in SheetData.Elements<Row>()
where (uint)r.RowIndex == i + 1
select r).First();
row.Height = (DoubleValue)(rowHeight * num);
row.CustomHeight = (BooleanValue)true;
}
else
{
SheetData.Append(new Row
{
RowIndex = (UInt32Value)(i + 1),
Height = (DoubleValue)(rowHeight * num),
CustomHeight = (BooleanValue)true
});
}
}
_startRowIndex++;
for (var j = 0; j < data.GetLength(0); j++)
{
for (var k = 0; k < data.GetLength(1); k++)
{
CreateCell(k, _startRowIndex, data[j, k], k == 0 ? 2u : 1u);
}
_startRowIndex++;
}
}
}
}

View File

@@ -0,0 +1,15 @@
<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="DocumentFormat.OpenXml" Version="3.1.0" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,19 @@
using DocumentFormat.OpenXml.Spreadsheet;
namespace Ivanov_components.Models
{
public class ChartConfig : DocumentConfig
{
public string ChartTitle { get; init; } = string.Empty;
public Location LegendLocation { get; init; }
public Dictionary<string, List<(string Name, double Value)>>? Data { get; init; }
public void CheckFields()
{
if (Data == null || Data.Count == 0)
{
throw new ArgumentNullException("Data count is null");
}
}
}
}

View File

@@ -0,0 +1,8 @@
namespace Ivanov_components.Models
{
public class DocumentConfig
{
public string FilePath { get; init; } = string.Empty;
public string Header { get; init; } = string.Empty;
}
}

View File

@@ -0,0 +1,10 @@
namespace Ivanov_components.Models
{
public enum Location
{
Left,
Right,
Top,
Bottom
}
}

View File

@@ -0,0 +1,15 @@
namespace Ivanov_components.Models
{
public class TableConfig : DocumentConfig
{
public List<string[,]>? Data { get; init; }
public void CheckFields()
{
if (Data == null || Data.Count == 0 || Data.All(x => x.Length == 0))
{
throw new ArgumentNullException("Data is null");
}
}
}
}

View File

@@ -0,0 +1,27 @@
namespace Ivanov_components.Models
{
public class TableWithHeaderConfig<T> : DocumentConfig
{
public (int Columns, int Rows) ColumnsRowsDataCount { get; set; }
public List<(int Column, int Row)>? ColumnsRowsWidth { get; init; }
public List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)>? Headers { get; init; }
public List<T>? Data { get; init; }
public string NullReplace { get; set; } = "null";
public void CheckFields()
{
if (Data == null || Data.Count == 0)
{
throw new ArgumentNullException("No data");
}
if (ColumnsRowsWidth is null || ColumnsRowsWidth.Count == 0)
{
throw new ArgumentNullException("Rows width invalid");
}
if (Headers is null || Headers.Count == 0)
{
throw new ArgumentNullException("Header data invalid");
}
}
}
}

View File

@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ivanov_visual_components
{
public class ColumnsConfiguratoin
{
public int ColumnsCount { get; set; }
public string[] NameColumn { get; set; }
public int[] Width { get; set; }
public bool[] Visible { get; set; }
public string[] PropertiesObject { get; set; }
}
}

View File

@@ -0,0 +1,74 @@
namespace Ivanov_visual_components
{
partial class DateBoxWithNull
{
/// <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.CheckBoxNull = new System.Windows.Forms.CheckBox();
this.TextBoxDate = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// CheckBoxNull
//
this.CheckBoxNull.AutoSize = true;
this.CheckBoxNull.Location = new System.Drawing.Point(3, 7);
this.CheckBoxNull.Name = "CheckBoxNull";
this.CheckBoxNull.Size = new System.Drawing.Size(15, 14);
this.CheckBoxNull.TabIndex = 0;
this.CheckBoxNull.UseVisualStyleBackColor = true;
this.CheckBoxNull.CheckedChanged += new System.EventHandler(this.CheckBoxNull_CheckedChanged);
//
// TextBoxDate
//
this.TextBoxDate.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.TextBoxDate.Location = new System.Drawing.Point(24, 3);
this.TextBoxDate.Name = "TextBoxDate";
this.TextBoxDate.Size = new System.Drawing.Size(271, 23);
this.TextBoxDate.TabIndex = 1;
this.TextBoxDate.TextChanged += new System.EventHandler(this.TextBoxDate_TextChanged);
//
// DateBoxWithNull
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ControlLight;
this.Controls.Add(this.TextBoxDate);
this.Controls.Add(this.CheckBoxNull);
this.Name = "DateBoxWithNull";
this.Size = new System.Drawing.Size(298, 29);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private CheckBox CheckBoxNull;
private TextBox TextBoxDate;
}
}

View File

@@ -0,0 +1,86 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace Ivanov_visual_components
{
public partial class DateBoxWithNull : UserControl
{
public EventHandler? _changeEvent;
public EventHandler? _checkBoxEvent;
public Exception? Error;
public DateBoxWithNull()
{
InitializeComponent();
}
public DateTime? Value
{
get
{
Error = null;
if (!CheckBoxNull.Checked)
{
if (string.IsNullOrEmpty(TextBoxDate.Text))
{
Error = new NotFilledException("Text box can't be empty, click checkbox if value must be empty!");
return null;
}
if (DateTime.TryParseExact(TextBoxDate.Text, "dd/MM/yyyy", null, DateTimeStyles.None, out DateTime parsedDate))
{
return parsedDate;
}
else
{
Error = new ParseException($"Wrong format <{TextBoxDate.Text}>!");
return null;
}
}
return null;
}
set
{
if (value is null)
{
CheckBoxNull.Checked = true;
}
else
{
TextBoxDate.Text = value?.ToString("dd/MM/yyyy");
CheckBoxNull.Checked = false;
}
}
}
public event EventHandler CheckBoxEvent
{
add { _checkBoxEvent += value; }
remove { _checkBoxEvent += value; }
}
public event EventHandler ChangeEvent
{
add { _changeEvent += value; }
remove { _changeEvent += value; }
}
private void TextBoxDate_TextChanged(object sender, EventArgs e)
{
_changeEvent?.Invoke(sender, e);
}
private void CheckBoxNull_CheckedChanged(object sender, EventArgs e)
{
TextBoxDate.Enabled = !CheckBoxNull.Checked;
_checkBoxEvent?.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,62 @@
namespace Ivanov_visual_components
{
partial class ItemList
{
/// <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.ListBoxCustom = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// ListBoxCustom
//
this.ListBoxCustom.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.ListBoxCustom.FormattingEnabled = true;
this.ListBoxCustom.ItemHeight = 15;
this.ListBoxCustom.Location = new System.Drawing.Point(0, 0);
this.ListBoxCustom.Name = "ListBoxCustom";
this.ListBoxCustom.Size = new System.Drawing.Size(272, 259);
this.ListBoxCustom.TabIndex = 0;
this.ListBoxCustom.SelectedIndexChanged += new System.EventHandler(this.ListBoxCustom_SelectedIndexChanged);
//
// ItemList
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.ListBoxCustom);
this.Name = "ItemList";
this.Size = new System.Drawing.Size(272, 265);
this.ResumeLayout(false);
}
#endregion
private ListBox ListBoxCustom;
}
}

View File

@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Ivanov_visual_components
{
public partial class ItemList : UserControl
{
private EventHandler? _changeEvent;
public ListBox.ObjectCollection Items => ListBoxCustom.Items;
public ItemList()
{
InitializeComponent();
}
public void Clear()
{
ListBoxCustom.Items.Clear();
}
public event EventHandler ChangeEvent
{
add
{
_changeEvent += value;
}
remove
{
_changeEvent -= value;
}
}
public string? SelectedElement
{
get
{
return (ListBoxCustom.SelectedIndex != -1 && ListBoxCustom.SelectedItem != null)
? ListBoxCustom.SelectedItem.ToString()
: string.Empty;
}
set
{
if (!string.IsNullOrEmpty(value))
{
int index = ListBoxCustom.FindString(value);
if (index == -1) return;
ListBoxCustom.SetSelected(index, true);
}
}
}
private void ListBoxCustom_SelectedIndexChanged(object sender, EventArgs e)
{
_changeEvent?.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,72 @@
namespace Ivanov_visual_components
{
partial class ItemTable
{
/// <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.DataGridViewItems = new System.Windows.Forms.DataGridView();
((System.ComponentModel.ISupportInitialize)(this.DataGridViewItems)).BeginInit();
this.SuspendLayout();
//
// DataGridViewItems
//
this.DataGridViewItems.AllowUserToAddRows = false;
this.DataGridViewItems.AllowUserToDeleteRows = false;
this.DataGridViewItems.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.DataGridViewItems.BackgroundColor = System.Drawing.SystemColors.ButtonFace;
this.DataGridViewItems.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.DataGridViewItems.GridColor = System.Drawing.SystemColors.ActiveCaptionText;
this.DataGridViewItems.Location = new System.Drawing.Point(0, 0);
this.DataGridViewItems.MultiSelect = false;
this.DataGridViewItems.Name = "DataGridViewItems";
this.DataGridViewItems.ReadOnly = true;
this.DataGridViewItems.RowHeadersVisible = false;
this.DataGridViewItems.RowTemplate.Height = 25;
this.DataGridViewItems.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.DataGridViewItems.ShowEditingIcon = false;
this.DataGridViewItems.Size = new System.Drawing.Size(548, 358);
this.DataGridViewItems.TabIndex = 0;
//
// ItemTable
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.DataGridViewItems);
this.Name = "ItemTable";
this.Size = new System.Drawing.Size(548, 358);
((System.ComponentModel.ISupportInitialize)(this.DataGridViewItems)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView DataGridViewItems;
}
}

View File

@@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Ivanov_visual_components
{
public partial class ItemTable : UserControl
{
public ItemTable()
{
InitializeComponent();
}
public int SelectedRow
{
get
{
return DataGridViewItems.SelectedRows[0].Index;
}
set
{
if (DataGridViewItems.SelectedRows.Count <= value || value < 0)
{
throw new ArgumentException(string.Format("{0} is an invalid row index.", value));
}
else
{
DataGridViewItems.ClearSelection();
DataGridViewItems.Rows[value].Selected = true;
}
}
}
public void ClearDataGrid()
{
DataGridViewItems.DataSource = null;
DataGridViewItems.Rows.Clear();
}
public void ConfigColumn(ColumnsConfiguratoin columnsData)
{
DataGridViewItems.ColumnCount = columnsData.ColumnsCount;
for (int i = 0; i < columnsData.ColumnsCount; i++)
{
DataGridViewItems.Columns[i].Name = columnsData.NameColumn[i];
DataGridViewItems.Columns[i].Width = columnsData.Width[i];
DataGridViewItems.Columns[i].Visible = columnsData.Visible[i];
DataGridViewItems.Columns[i].DataPropertyName = columnsData.PropertiesObject[i];
}
}
public T GetSelectedObjectInRow<T>() where T : class, new()
{
T val = new();
var propertiesObj = typeof(T).GetProperties();
foreach (var properties in propertiesObj)
{
bool propIsExist = false;
int columnIndex = 0;
for (; columnIndex < DataGridViewItems.Columns.Count; columnIndex++)
{
if (DataGridViewItems.Columns[columnIndex].DataPropertyName.ToString() == properties.Name)
{
propIsExist = true;
break;
}
}
if (propIsExist)
{
object value = DataGridViewItems.SelectedRows[0].Cells[columnIndex].Value;
properties.SetValue(val, Convert.ChangeType(value, properties?.PropertyType));
};
}
return val;
}
public void AddItem<T>(T item, int RowIndex, int ColumnIndex)
{
if (item == null)
{
return;
}
string propertyName = DataGridViewItems.Columns[ColumnIndex].DataPropertyName.ToString();
string? value = item.GetType().GetProperty(propertyName)?.GetValue(item)?.ToString();
if (RowIndex >= DataGridViewItems.Rows.Count)
{
DataGridViewItems.RowCount = RowIndex + 1;
}
DataGridViewItems.Rows[RowIndex].Cells[ColumnIndex].Value = value;
}
}
}

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,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ivanov_visual_components
{
public class NotFilledException : Exception
{
public NotFilledException() { }
public NotFilledException(string message) : base(message) { }
public NotFilledException(string message, Exception inner) : base(message, inner) { }
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ivanov_visual_components
{
public class ParseException : Exception
{
public ParseException() { }
public ParseException(string message) : base(message) { }
public ParseException(string message, Exception innerException) : base(message, innerException) { }
}
}

43
KOP/KOP.sln Normal file
View File

@@ -0,0 +1,43 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.35122.118
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ivanov_App", "Ivanov_App\Ivanov_App.csproj", "{64CD7137-E0BF-4F35-8F33-B07AFED1393F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnterpriseContracts", "EnterpriseContracts\EnterpriseContracts.csproj", "{196E0D33-EA70-42F0-AF4F-BD66843AB836}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnterpriseBusinessLogic", "EnterpriseBusinessLogic\EnterpriseBusinessLogic.csproj", "{45AFE8E1-F8F4-4D8C-8385-00E2C370EB3C}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EnterpriseDataBaseImplement", "EnterpriseDataBaseImplement\EnterpriseDataBaseImplement.csproj", "{FAFF75D4-135E-40E3-BC83-A3B41C3D167E}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{64CD7137-E0BF-4F35-8F33-B07AFED1393F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{64CD7137-E0BF-4F35-8F33-B07AFED1393F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{64CD7137-E0BF-4F35-8F33-B07AFED1393F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{64CD7137-E0BF-4F35-8F33-B07AFED1393F}.Release|Any CPU.Build.0 = Release|Any CPU
{196E0D33-EA70-42F0-AF4F-BD66843AB836}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{196E0D33-EA70-42F0-AF4F-BD66843AB836}.Debug|Any CPU.Build.0 = Debug|Any CPU
{196E0D33-EA70-42F0-AF4F-BD66843AB836}.Release|Any CPU.ActiveCfg = Release|Any CPU
{196E0D33-EA70-42F0-AF4F-BD66843AB836}.Release|Any CPU.Build.0 = Release|Any CPU
{45AFE8E1-F8F4-4D8C-8385-00E2C370EB3C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{45AFE8E1-F8F4-4D8C-8385-00E2C370EB3C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{45AFE8E1-F8F4-4D8C-8385-00E2C370EB3C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{45AFE8E1-F8F4-4D8C-8385-00E2C370EB3C}.Release|Any CPU.Build.0 = Release|Any CPU
{FAFF75D4-135E-40E3-BC83-A3B41C3D167E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FAFF75D4-135E-40E3-BC83-A3B41C3D167E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FAFF75D4-135E-40E3-BC83-A3B41C3D167E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FAFF75D4-135E-40E3-BC83-A3B41C3D167E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1A537B19-2DD7-4FCC-9CFD-9A7FAEE5D675}
EndGlobalSection
EndGlobal