Compare commits

...

27 Commits
main ... Lab3

Author SHA1 Message Date
GokaPek
d31a0e155a Сдано 2024-11-12 10:38:35 +04:00
GokaPek
d1a577e5d3 поправил дату на англ 2024-11-10 15:55:11 +04:00
GokaPek
8dd9655bee ВОЛОДЯ КУПИЛ МНЕ ЭКСЕЛЬ 2024-10-31 15:15:50 +04:00
GokaPek
2b6207f365 КУПИТЕ МНЕ ЛИЦЕНЗИЮ ЭКСЕЛЯ 2024-10-31 01:02:35 +04:00
GokaPek
5fdba2649f Пдфка создаётся 2024-10-31 00:02:20 +04:00
GokaPek
005a281753 начинаем встраивать вторую лабу 2024-10-30 22:52:41 +04:00
GokaPek
bfd19f346c работает 1 лаба у всех 2024-10-30 19:23:38 +04:00
GokaPek
5ae61a964d володя поправь 2024-10-30 18:54:45 +04:00
GokaPek
8baae1a495 не понятно как добавить мануфактуру 2024-10-30 18:23:56 +04:00
GokaPek
dee1447d89 пробная форма продуктов 2024-10-30 17:40:38 +04:00
GokaPek
d3bc885bc9 Продупление 2024-10-30 13:34:23 +04:00
GokaPek
b9e819f309 Финал 2 лаба 2024-10-01 11:57:07 +04:00
GokaPek
cbc230e0a2 сделан правильный мёрдж 2024-10-01 11:11:57 +04:00
GokaPek
f6990cd5a6 в слитых ячейках могут быть не те значения 2024-10-01 10:59:06 +04:00
GokaPek
4e81c3f101 удаление комментов 2024-10-01 10:26:35 +04:00
GokaPek
1cd9ae93c9 первый финал 2024-09-30 11:24:43 +04:00
GokaPek
0cd24d6b30 вторая задача 2024-09-30 11:06:19 +04:00
GokaPek
c17a7faddc две колонки хедеров 2024-09-30 10:56:46 +04:00
GokaPek
fc113983ea получилось! 2024-09-30 00:41:41 +04:00
GokaPek
31b37da456 шапка вертикальная, а данные нет 2024-09-30 00:02:59 +04:00
GokaPek
a6a440e181 строчки вместо столбцов 2024-09-29 23:00:02 +04:00
GokaPek
a24dbe6e5b Final 2024-09-17 12:40:52 +04:00
GokaPek
c3fcd0c80d 5 2024-09-16 00:08:22 +04:00
GokaPek
d2cbf15038 4 2024-09-15 23:58:52 +04:00
GokaPek
918cbc514b 3 2024-09-15 23:53:12 +04:00
GokaPek
11c1ae95fb second 2024-09-15 23:31:11 +04:00
GokaPek
7473b1e5d5 initial 2024-09-15 21:58:20 +04:00
56 changed files with 3801 additions and 0 deletions

15
ExecForm/ExecForm1.csproj Normal file
View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Library14Petrushin\Library14Petrushin.csproj" />
</ItemGroup>
</Project>

80
ExecForm/Form1.Designer.cs generated Normal file
View File

@ -0,0 +1,80 @@
namespace ExecForm
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
chooseList1 = new Library14Petrushin.ChooseList();
hierarchicalTreeView1 = new Library14Petrushin.HierarchicalTreeView();
textBoxRange1 = new Library14Petrushin.TextBoxRange();
SuspendLayout();
//
// chooseList1
//
chooseList1.Location = new Point(12, 12);
chooseList1.Name = "chooseList1";
chooseList1.SelectedValue = "";
chooseList1.Size = new Size(185, 190);
chooseList1.TabIndex = 0;
//
// hierarchicalTreeView1
//
hierarchicalTreeView1.Location = new Point(567, 2);
hierarchicalTreeView1.Name = "hierarchicalTreeView1";
hierarchicalTreeView1.SelectedNodeIndex = -1;
hierarchicalTreeView1.Size = new Size(266, 504);
hierarchicalTreeView1.TabIndex = 2;
//
// textBoxRange1
//
textBoxRange1.Location = new Point(254, 21);
textBoxRange1.MaxLength = null;
textBoxRange1.MinLength = null;
textBoxRange1.Name = "textBoxRange1";
textBoxRange1.Size = new Size(259, 118);
textBoxRange1.TabIndex = 3;
//
// Form1
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(834, 507);
Controls.Add(textBoxRange1);
Controls.Add(hierarchicalTreeView1);
Controls.Add(chooseList1);
Name = "Form1";
Text = "Form1";
ResumeLayout(false);
}
#endregion
private Library14Petrushin.ChooseList chooseList1;
private Library14Petrushin.HierarchicalTreeView hierarchicalTreeView1;
private Library14Petrushin.TextBoxRange textBoxRange1;
}
}

39
ExecForm/Form1.cs Normal file
View File

@ -0,0 +1,39 @@
using Library14Petrushin.Classes;
using Library14Petrushin;
namespace ExecForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Íàñòðîéêà êîìïîíåíòîâ
chooseList1.AddItemToList("Item 1");
chooseList1.AddItemToList("Item 2");
chooseList1.AddItemToList("Item 3");
textBoxRange1.MinLength = 3;
textBoxRange1.MaxLength = 10;
var hierarchy = new List<string> { "Department", "Position", "FullName" };
var alwaysNewBranch = new Dictionary<string, bool> { { "FullName", true } };
hierarchicalTreeView1.SetHierarchy(hierarchy, alwaysNewBranch);
var employees = new List<Employee>
{
new Employee { Department = "IT", Position = "Developer", FullName = "John Doe" },
new Employee { Department = "HR", Position = "Manager", FullName = "Jane Smith" }
};
// Çàïîëíåíèå äåðåâà ñ èñïîëüçîâàíèåì AddObjectToTree
foreach (var employee in employees)
{
hierarchicalTreeView1.AddObjectToTree(employee, hierarchy.Last());
}
}
}
}

120
ExecForm/Form1.resx Normal file
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>

17
ExecForm/Program.cs Normal file
View File

@ -0,0 +1,17 @@
namespace ExecForm
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
}

View File

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Library14Petrushin\Library14Petrushin.csproj" />
</ItemGroup>
</Project>

152
ExexForm2/Form1.Designer.cs generated Normal file
View File

@ -0,0 +1,152 @@
namespace ExexForm2
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
pdfImg1 = new Library14Petrushin.PdfImg(components);
btnSelectImages = new Button();
btnSelectDirectory = new Button();
btnCreatePdf = new Button();
txtDocumentTitle = new TextBox();
lstImages = new ListBox();
lblDirectory = new Label();
btnCrTb = new Button();
pdfColGroupTable1 = new Library14Petrushin.PdfColGroupTable();
pdfCirclDiagr1 = new Library14Petrushin.PdfCirclDiagr();
btnCircl = new Button();
SuspendLayout();
//
// btnSelectImages
//
btnSelectImages.Location = new Point(24, 28);
btnSelectImages.Name = "btnSelectImages";
btnSelectImages.Size = new Size(116, 50);
btnSelectImages.TabIndex = 0;
btnSelectImages.Text = "выбор изображения";
btnSelectImages.UseVisualStyleBackColor = true;
btnSelectImages.Click += btnSelectImages_Click;
//
// btnSelectDirectory
//
btnSelectDirectory.Location = new Point(24, 89);
btnSelectDirectory.Name = "btnSelectDirectory";
btnSelectDirectory.Size = new Size(116, 49);
btnSelectDirectory.TabIndex = 1;
btnSelectDirectory.Text = "выбор директории";
btnSelectDirectory.UseVisualStyleBackColor = true;
btnSelectDirectory.Click += btnSelectDirectory_Click;
//
// btnCreatePdf
//
btnCreatePdf.Location = new Point(24, 158);
btnCreatePdf.Name = "btnCreatePdf";
btnCreatePdf.Size = new Size(101, 48);
btnCreatePdf.TabIndex = 2;
btnCreatePdf.Text = "Создать";
btnCreatePdf.UseVisualStyleBackColor = true;
btnCreatePdf.Click += btnCreatePdf_Click;
//
// txtDocumentTitle
//
txtDocumentTitle.Location = new Point(24, 224);
txtDocumentTitle.Name = "txtDocumentTitle";
txtDocumentTitle.Size = new Size(101, 27);
txtDocumentTitle.TabIndex = 3;
//
// lstImages
//
lstImages.FormattingEnabled = true;
lstImages.Location = new Point(146, 28);
lstImages.Name = "lstImages";
lstImages.Size = new Size(179, 404);
lstImages.TabIndex = 4;
//
// lblDirectory
//
lblDirectory.AutoSize = true;
lblDirectory.Location = new Point(24, 280);
lblDirectory.Name = "lblDirectory";
lblDirectory.Size = new Size(50, 20);
lblDirectory.TabIndex = 5;
lblDirectory.Text = "label1";
//
// btnCrTb
//
btnCrTb.Location = new Point(349, 28);
btnCrTb.Name = "btnCrTb";
btnCrTb.Size = new Size(142, 29);
btnCrTb.TabIndex = 6;
btnCrTb.Text = "Создать таблицу";
btnCrTb.UseVisualStyleBackColor = true;
btnCrTb.Click += btnCreatePdfTable_Click;
//
// btnCircl
//
btnCircl.Location = new Point(606, 28);
btnCircl.Name = "btnCircl";
btnCircl.Size = new Size(161, 29);
btnCircl.TabIndex = 7;
btnCircl.Text = "Создать диаграмму";
btnCircl.UseVisualStyleBackColor = true;
btnCircl.Click += btnCreatePdfCircl_Click;
//
// Form1
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(btnCircl);
Controls.Add(btnCrTb);
Controls.Add(lblDirectory);
Controls.Add(lstImages);
Controls.Add(txtDocumentTitle);
Controls.Add(btnCreatePdf);
Controls.Add(btnSelectDirectory);
Controls.Add(btnSelectImages);
Name = "Form1";
Text = "Form1";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Library14Petrushin.PdfImg pdfImg1;
private Button btnSelectImages;
private Button btnSelectDirectory;
private Button btnCreatePdf;
private TextBox txtDocumentTitle;
private ListBox lstImages;
private Label lblDirectory;
private Button btnCrTb;
private Library14Petrushin.PdfColGroupTable pdfColGroupTable1;
private Library14Petrushin.PdfCirclDiagr pdfCirclDiagr1;
private Button btnCircl;
}
}

169
ExexForm2/Form1.cs Normal file
View File

@ -0,0 +1,169 @@
using Library14Petrushin;
using Library14Petrushin.Classes;
namespace ExexForm2
{
public partial class Form1 : Form
{
private PdfImg pdfImg;
private List<ImageData> selectedImages;
private string selectedDirectory;
private PdfColGroupTable pdfTable;
private PdfCirclDiagr pdfCirclDiagr;
public Form1()
{
InitializeComponent();
pdfImg = new PdfImg();
selectedImages = new List<ImageData>();
pdfTable = new PdfColGroupTable();
pdfCirclDiagr = new PdfCirclDiagr();
}
private void btnSelectImages_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp;*.gif";
openFileDialog.Multiselect = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
foreach (string fileName in openFileDialog.FileNames)
{
selectedImages.Add(new ImageData { ImagePath = fileName });
lstImages.Items.Add(fileName);
}
}
}
}
private void btnSelectDirectory_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
{
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
selectedDirectory = folderBrowserDialog.SelectedPath;
lblDirectory.Text = "Selected Directory: " + selectedDirectory;
}
}
}
private void btnCreatePdf_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtDocumentTitle.Text) || selectedImages.Count == 0 || string.IsNullOrEmpty(selectedDirectory))
{
MessageBox.Show("Please select images, directory, and enter a document title.");
return;
}
string fileName = Path.Combine(selectedDirectory, "output1.pdf");
pdfImg.CreatePdfDocument(fileName, txtDocumentTitle.Text, selectedImages);
MessageBox.Show("PDF document created successfully!");
}
// 2 -------------------------------------------
private void btnCreatePdfTable_Click(object sender, EventArgs e)
{
string selectDirTable = "";
string fileName = "";
using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
{
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
selectDirTable = folderBrowserDialog.SelectedPath;
}
}
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "PDF Files (*.pdf)|*.pdf";
saveFileDialog.DefaultExt = "pdf";
saveFileDialog.InitialDirectory = selectDirTable;
saveFileDialog.FileName = "output2.pdf";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
fileName = saveFileDialog.FileName;
}
}
if (!string.IsNullOrEmpty(fileName))
{
var generator = new PdfColGroupTable();
var data1 = new List<Person>
{
new Person { FirstName = "John", LastName = "Doe", Age = 30 },
new Person { FirstName = "Jane", LastName = "Smith", Age = 25 }
};
var commonHeaders = new List<string> { "Name", "", "" };
var headersNames = new List<(string, string)> {
("First Name","FirstName"),
("Last Name", "LastName"),
("Age", "Age")
};
var rowHeights = new List<double> { 20, 20 };
var mergeCells = new List<(int startRow, int endRow, int startColumn, int endColumn)>
{
(0, 1, 0, 0), // 0 è 1 ÿ÷åéêè ïî âåðòèêàëè ïåðâîé êîëîíêè
(2, 2, 0, 1)
};
generator.GeneratePdf(fileName, "Example Document", mergeCells, rowHeights, headersNames, commonHeaders, data1);
}
}
// 3 -------------------------------------------
private void btnCreatePdfCircl_Click(object sender, EventArgs e)
{
string selectDir = "";
string fileName = "";
using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
{
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
selectDir = folderBrowserDialog.SelectedPath;
}
}
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "PDF Files (*.pdf)|*.pdf";
saveFileDialog.DefaultExt = "pdf";
saveFileDialog.InitialDirectory = selectDir;
saveFileDialog.FileName = "output3.pdf";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
fileName = saveFileDialog.FileName;
}
}
if (!string.IsNullOrEmpty(fileName))
{
var pdfCirclDiagr = new PdfCirclDiagr();
List<ChartData> chartData = new List<ChartData>
{
new ChartData { SeriesName = "Series 1", Value = 10 },
new ChartData { SeriesName = "Series 2", Value = 20 },
new ChartData { SeriesName = "Series 3", Value = 30 },
new ChartData { SeriesName = "Series 4", Value = 40 }
};
pdfCirclDiagr.GeneratePdf(fileName, "Document Title", "Chart Title", LegendPosition.Right, chartData);
}
}
}
}

129
ExexForm2/Form1.resx Normal file
View File

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

17
ExexForm2/Program.cs Normal file
View File

@ -0,0 +1,17 @@
namespace ExexForm2
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
}

178
Laba3/MainForm.Designer.cs generated Normal file
View File

@ -0,0 +1,178 @@
namespace Laba3
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
menuStrip1 = new MenuStrip();
createToolStripMenuItem = new ToolStripMenuItem();
updateToolStripMenuItem = new ToolStripMenuItem();
deleteToolStripMenuItem = new ToolStripMenuItem();
manufacturerToolStripMenuItem = new ToolStripMenuItem();
documentsToolStripMenuItem = new ToolStripMenuItem();
pdfImageToolStripMenuItem = new ToolStripMenuItem();
exelTableToolStripMenuItem = new ToolStripMenuItem();
wordGistToolStripMenuItem = new ToolStripMenuItem();
outputTableResults = new Library15Gerimovich.OutputTableResults();
pdfImg = new Library14Petrushin.PdfImg(components);
wordDiagramComponent = new Library15Gerimovich.WordDiagramComponent(components);
componentTable = new WinFormsLibrary1.ComponentTable(components);
saveFileDialogPdf = new SaveFileDialog();
saveFileDialogWord = new SaveFileDialog();
saveFileDialogExel = new SaveFileDialog();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { createToolStripMenuItem, updateToolStripMenuItem, deleteToolStripMenuItem, manufacturerToolStripMenuItem, documentsToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(480, 28);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// createToolStripMenuItem
//
createToolStripMenuItem.Name = "createToolStripMenuItem";
createToolStripMenuItem.Size = new Size(66, 24);
createToolStripMenuItem.Text = "Create";
createToolStripMenuItem.Click += addToolStripMenuItem_Click;
//
// updateToolStripMenuItem
//
updateToolStripMenuItem.Name = "updateToolStripMenuItem";
updateToolStripMenuItem.Size = new Size(72, 24);
updateToolStripMenuItem.Text = "Update";
updateToolStripMenuItem.Click += editToolStripMenuItem_Click;
//
// deleteToolStripMenuItem
//
deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
deleteToolStripMenuItem.Size = new Size(67, 24);
deleteToolStripMenuItem.Text = "Delete";
deleteToolStripMenuItem.Click += deleteToolStripMenuItem_Click;
//
// manufacturerToolStripMenuItem
//
manufacturerToolStripMenuItem.Name = "manufacturerToolStripMenuItem";
manufacturerToolStripMenuItem.Size = new Size(111, 24);
manufacturerToolStripMenuItem.Text = "Manufacturer";
manufacturerToolStripMenuItem.Click += manufacturersToolStripMenuItem_Click;
//
// documentsToolStripMenuItem
//
documentsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { pdfImageToolStripMenuItem, exelTableToolStripMenuItem, wordGistToolStripMenuItem });
documentsToolStripMenuItem.Name = "documentsToolStripMenuItem";
documentsToolStripMenuItem.Size = new Size(98, 24);
documentsToolStripMenuItem.Text = "Documents";
//
// pdfImageToolStripMenuItem
//
pdfImageToolStripMenuItem.Name = "pdfImageToolStripMenuItem";
pdfImageToolStripMenuItem.Size = new Size(159, 26);
pdfImageToolStripMenuItem.Text = "Pdf Image";
pdfImageToolStripMenuItem.Click += createSimpleDocumentToolStripMenuItem_Click;
//
// exelTableToolStripMenuItem
//
exelTableToolStripMenuItem.Name = "exelTableToolStripMenuItem";
exelTableToolStripMenuItem.Size = new Size(159, 26);
exelTableToolStripMenuItem.Text = "Exel table";
exelTableToolStripMenuItem.Click += createCustomTableDocumentToolStripMenuItem_Click;
//
// wordGistToolStripMenuItem
//
wordGistToolStripMenuItem.Name = "wordGistToolStripMenuItem";
wordGistToolStripMenuItem.Size = new Size(159, 26);
wordGistToolStripMenuItem.Text = "Word gist";
wordGistToolStripMenuItem.Click += createChartDocumentToolStripMenuItem_Click;
//
// outputTableResults
//
outputTableResults.Location = new Point(12, 32);
outputTableResults.Margin = new Padding(3, 4, 3, 4);
outputTableResults.Name = "outputTableResults";
outputTableResults.SelectedRow = -1;
outputTableResults.Size = new Size(467, 308);
outputTableResults.TabIndex = 1;
//
// saveFileDialogPdf
//
saveFileDialogPdf.FileName = "Products.pdf";
saveFileDialogPdf.Filter = "PDF Files (*.pdf)|*.pdf";
saveFileDialogPdf.Title = "Save PDF Document";
//
// saveFileDialogWord
//
saveFileDialogWord.FileName = "Diagram.docx";
saveFileDialogWord.Filter = "Word Files (*.docx)|*.docx";
saveFileDialogWord.Title = "Save Word Document";
//
// saveFileDialogExel
//
saveFileDialogExel.FileName = "ProductReport.xlsx";
saveFileDialogExel.Filter = "Excel Files (*.xlsx)|*.xlsx";
saveFileDialogExel.Title = "Save Excel Document";
//
// MainForm
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(480, 351);
Controls.Add(outputTableResults);
Controls.Add(menuStrip1);
KeyPreview = true;
MainMenuStrip = menuStrip1;
Name = "MainForm";
Text = "Form1";
KeyDown += MainForm_KeyDown;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem createToolStripMenuItem;
private ToolStripMenuItem updateToolStripMenuItem;
private Library15Gerimovich.OutputTableResults outputTableResults;
private ToolStripMenuItem deleteToolStripMenuItem;
private ToolStripMenuItem manufacturerToolStripMenuItem;
private ToolStripMenuItem documentsToolStripMenuItem;
private ToolStripMenuItem pdfImageToolStripMenuItem;
private ToolStripMenuItem exelTableToolStripMenuItem;
private ToolStripMenuItem wordGistToolStripMenuItem;
private Library14Petrushin.PdfImg pdfImg;
private Library15Gerimovich.WordDiagramComponent wordDiagramComponent;
private WinFormsLibrary1.ComponentTable componentTable;
}
}

284
Laba3/MainForm.cs Normal file
View File

@ -0,0 +1,284 @@
using Data;
using Data.Repositories;
using View;
using System.Windows.Forms;
using Data.Models;
using Library14Petrushin;
using Library15Gerimovich.OfficePackage.HelperModels;
using Library15Gerimovich;
using WinFormsLibrary1;
using WinFormsLibrary1.Models;
using View.ViewModels;
namespace Laba3
{
public partial class MainForm : Form
{
private readonly IProductRepository _productRepository;
private readonly IManufacturerRepository _manufacturerRepository;
private SaveFileDialog saveFileDialogPdf;
private SaveFileDialog saveFileDialogWord;
private SaveFileDialog saveFileDialogExel;
public MainForm(IProductRepository productRepository, IManufacturerRepository manufacturerRepository)
{
InitializeComponent();
_productRepository = productRepository;
_manufacturerRepository = manufacturerRepository;
InitializeOutputTableResults();
LoadProducts();
}
private void InitializeOutputTableResults()
{
outputTableResults.ConfigureColumns(new List<ColumnInfo>
{
new ColumnInfo("", 0, false, "Id"),
new ColumnInfo("Name", 150, true, "Name"),
new ColumnInfo("ManufacturerNameManufacturerName", 150, true, "ManufacturerName"),
new ColumnInfo("DeliveryDate", 50, true, "DeliveryDate"),
});
}
private void LoadProducts()
{
var products = _productRepository.GetAllProducts();
outputTableResults.ClearGrid();
foreach (var product in products)
{
outputTableResults.InsertValue(product);
}
}
private void addToolStripMenuItem_Click(object sender, EventArgs e)
{
var productForm = new ProductForm(_productRepository, _manufacturerRepository);
if (productForm.ShowDialog() == DialogResult.OK)
{
LoadProducts();
}
}
private void editToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
var selectedProductId = outputTableResults.GetSelectedObject<Product>().Id;
var selectedProduct = _productRepository.GetProductById(selectedProductId);
var productForm = new ProductForm(_productRepository, _manufacturerRepository, selectedProduct);
if (productForm.ShowDialog() == DialogResult.OK)
{
LoadProducts();
}
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
{
var selectedProductId = outputTableResults.GetSelectedObject<Product>().Id;
if (MessageBox.Show("Are you sure you want to delete this product?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
_productRepository.DeleteProduct(selectedProductId);
LoadProducts();
}
}
private void manufacturersToolStripMenuItem_Click(object sender, EventArgs e)
{
var manufacturerForm = new ManufacturerForm(_manufacturerRepository);
manufacturerForm.ShowDialog();
}
private void createSimpleDocumentToolStripMenuItem_Click(object sender, EventArgs e)
{
// Получаем изображения из базы данных
var images = GetImagesFromDatabase();
if (images.Count > 0)
{
// Показываем диалоговое окно для выбора пути сохранения
if (saveFileDialogPdf.ShowDialog() == DialogResult.OK)
{
// Создаем компонент PdfImg
var pdfImg = new Library14Petrushin.PdfImg();
// Путь для сохранения PDF-документа
string fileName = saveFileDialogPdf.FileName;
// Заголовок документа
string documentTitle = "Product Images";
// Создаем PDF-документ
pdfImg.CreatePdfDocument(fileName, documentTitle, images);
// Уведомление об успешной загрузке
MessageBox.Show("PDF document created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("No images found in the database.");
}
}
private void createCustomTableDocumentToolStripMenuItem_Click(object sender, EventArgs e)
{
// Получаем все продукты из базы данных
var products = GetAllProducts();
if (products.Count > 0)
{
// Показываем диалоговое окно для выбора пути сохранения
if (saveFileDialogExel.ShowDialog() == DialogResult.OK)
{
// Создаем объекты MergeCell и Column
var mergeCells = new List<MergeCell>
{
new MergeCell("Product", new int[] {1, 2})
};
var columns = new List<Column>
{
new Column("Id", "Id", 10),
new Column("Name", "Name", 20),
new Column("ManufacturerName", "ManufacturerName", 20),
new Column("DeliveryDate", "DeliveryDate", 20)
};
// Создаем компонент ComponentTable
var componentTable = new ComponentTable();
// Конвертируем продукты в представление для таблицы
var tableItems = ProductTableItem.ConvertProductsToTableItems(products);
// Создаем документ Excel
componentTable.CreateDocument(saveFileDialogExel.FileName, "Product Report", mergeCells, columns, tableItems);
// Уведомление об успешной загрузке
MessageBox.Show("Excel document created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("No products found in the database.");
}
}
private void createChartDocumentToolStripMenuItem_Click(object sender, EventArgs e)
{
// Получаем данные о количестве продукции каждого производителя
var productCounts = GetProductCountsByManufacturer();
if (productCounts.Count > 0)
{
// Показываем диалоговое окно для выбора пути сохранения
if (saveFileDialogWord.ShowDialog() == DialogResult.OK)
{
// Создаем объект WordDiagramInfo
var diagramInfo = new WordDiagramInfo
{
FileName = saveFileDialogWord.FileName,
Title = "Product Count by Manufacturer",
ChartTitle = "Product Count",
LegendLocation = Library15Gerimovich.OfficePackage.HelperEnums.WordDiagramLegendLocation.Top,
Series = new WordDiagramSeries
{
SeriesName = "Product Count",
Data = productCounts
}
};
// Создаем диаграмму в Word
wordDiagramComponent.CreateDiagram(diagramInfo);
// Уведомление об успешной загрузке
MessageBox.Show("Word document with chart created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("No products found in the database.");
}
}
// бизнес логика
private void MainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control)
{
switch (e.KeyCode)
{
case Keys.A:
addToolStripMenuItem_Click(null, EventArgs.Empty);
break;
case Keys.U:
editToolStripMenuItem_Click(null, EventArgs.Empty);
break;
case Keys.D:
deleteToolStripMenuItem_Click(null, EventArgs.Empty);
break;
case Keys.S:
createSimpleDocumentToolStripMenuItem_Click(null, EventArgs.Empty);
break;
case Keys.T:
createCustomTableDocumentToolStripMenuItem_Click(null, EventArgs.Empty);
break;
case Keys.C:
createChartDocumentToolStripMenuItem_Click(null, EventArgs.Empty);
break;
}
}
}
private List<ImageData> GetImagesFromDatabase()
{
var images = new List<ImageData>();
var products = _productRepository.GetAllProducts();
foreach (var product in products)
{
if (product.Image != null)
{
// Создаем временный файл для сохранения изображения
string tempFilePath = Path.GetTempFileName();
File.WriteAllBytes(tempFilePath, product.Image);
// Добавляем путь к временному файлу в список
images.Add(new ImageData { ImagePath = tempFilePath });
}
}
return images;
}
private Dictionary<string, double> GetProductCountsByManufacturer()
{
var productCounts = new Dictionary<string, double>();
var products = _productRepository.GetAllProducts();
foreach (var product in products)
{
if (productCounts.ContainsKey(product.ManufacturerName))
{
productCounts[product.ManufacturerName]++;
}
else
{
productCounts[product.ManufacturerName] = 1;
}
}
return productCounts;
}
private List<Product> GetAllProducts()
{
return _productRepository.GetAllProducts().ToList();
}
}
}

141
Laba3/MainForm.resx Normal file
View File

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

64
Laba3/ManufacturerForm.Designer.cs generated Normal file
View File

@ -0,0 +1,64 @@
namespace View
{
partial class ManufacturerForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Location = new Point(12, 12);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.Size = new Size(711, 426);
dataGridView.TabIndex = 0;
dataGridView.CellValueChanged += dataGridView_CellValueChanged;
dataGridView.UserAddedRow += dataGridView_UserAddedRow;
dataGridView.UserDeletingRow += dataGridView_UserDeletingRow;
dataGridView.KeyDown += dataGridView_KeyDown;
//
// ManufacturerForm
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(731, 450);
Controls.Add(dataGridView);
Name = "ManufacturerForm";
Text = "ManufacturerForm";
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
}
}

95
Laba3/ManufacturerForm.cs Normal file
View File

@ -0,0 +1,95 @@
using Data.Models;
using Data.Repositories;
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 View
{
public partial class ManufacturerForm : Form
{
private readonly IManufacturerRepository _manufacturerRepository;
public ManufacturerForm(IManufacturerRepository manufacturerRepository)
{
InitializeComponent();
_manufacturerRepository = manufacturerRepository;
LoadManufacturers();
}
private void LoadManufacturers()
{
var manufacturers = _manufacturerRepository.GetAllManufacturers().ToList();
dataGridView.DataSource = manufacturers;
}
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
var manufacturer = dataGridView.Rows[e.RowIndex].DataBoundItem as Manufacturer;
if (manufacturer != null)
{
_manufacturerRepository.UpdateManufacturer(manufacturer);
}
}
}
private void dataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
var manufacturer = e.Row.DataBoundItem as Manufacturer;
if (manufacturer != null)
{
if (MessageBox.Show("Are you sure you want to delete this manufacturer?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
_manufacturerRepository.DeleteManufacturer(manufacturer.Id);
}
else
{
e.Cancel = true;
}
}
}
private void dataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
var manufacturer = new Manufacturer { Name = "" };
_manufacturerRepository.AddManufacturer(manufacturer);
LoadManufacturers();
}
// реализация через нажатие клавишь
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert)
{
var manufacturer = new Manufacturer { Name = "" };
_manufacturerRepository.AddManufacturer(manufacturer);
LoadManufacturers();
}
else if (e.KeyCode == Keys.Delete)
{
if (dataGridView.SelectedRows.Count > 0)
{
var selectedManufacturer = dataGridView.SelectedRows[0].DataBoundItem as Manufacturer;
if (selectedManufacturer != null)
{
if (MessageBox.Show("Are you sure you want to delete this manufacturer?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
_manufacturerRepository.DeleteManufacturer(selectedManufacturer.Id);
LoadManufacturers();
}
}
}
}
}
}
}

120
Laba3/ManufacturerForm.resx Normal file
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>

121
Laba3/ProductForm.Designer.cs generated Normal file
View File

@ -0,0 +1,121 @@
namespace Laba3
{
partial class ProductForm
{
/// <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()
{
dtpDeliveryDate = new WinFormsLibrary1.DateInputControl();
cmbManufacturer = new WinFormsLibrary1.ComboBoxUserControl();
txtName = new Library14Petrushin.TextBoxRange();
pbImage = new PictureBox();
button1 = new Button();
button2 = new Button();
((System.ComponentModel.ISupportInitialize)pbImage).BeginInit();
SuspendLayout();
//
// dtpDeliveryDate
//
dtpDeliveryDate.DateFormat = null;
dtpDeliveryDate.Location = new Point(13, 137);
dtpDeliveryDate.Margin = new Padding(4, 5, 4, 5);
dtpDeliveryDate.Name = "dtpDeliveryDate";
dtpDeliveryDate.Size = new Size(186, 110);
dtpDeliveryDate.TabIndex = 0;
//
// cmbManufacturer
//
cmbManufacturer.Location = new Point(12, 218);
cmbManufacturer.Margin = new Padding(4, 5, 4, 5);
cmbManufacturer.Name = "cmbManufacturer";
cmbManufacturer.SelectedValue = "";
cmbManufacturer.Size = new Size(201, 40);
cmbManufacturer.TabIndex = 1;
//
// txtName
//
txtName.Location = new Point(12, 12);
txtName.MaxLength = null;
txtName.MinLength = null;
txtName.Name = "txtName";
txtName.Size = new Size(315, 108);
txtName.TabIndex = 2;
//
// pbImage
//
pbImage.Location = new Point(320, 32);
pbImage.Name = "pbImage";
pbImage.Size = new Size(451, 344);
pbImage.TabIndex = 3;
pbImage.TabStop = false;
//
// button1
//
button1.Location = new Point(320, 399);
button1.Name = "button1";
button1.Size = new Size(110, 29);
button1.TabIndex = 4;
button1.Text = "Choose img";
button1.UseVisualStyleBackColor = true;
button1.Click += btnBrowse_Click;
//
// button2
//
button2.Location = new Point(12, 326);
button2.Name = "button2";
button2.Size = new Size(94, 29);
button2.TabIndex = 5;
button2.Text = "Save";
button2.UseVisualStyleBackColor = true;
button2.Click += btnSave_Click;
//
// ProductForm
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(button2);
Controls.Add(button1);
Controls.Add(pbImage);
Controls.Add(txtName);
Controls.Add(cmbManufacturer);
Controls.Add(dtpDeliveryDate);
Name = "ProductForm";
Text = "ProductForm";
((System.ComponentModel.ISupportInitialize)pbImage).EndInit();
ResumeLayout(false);
}
#endregion
private WinFormsLibrary1.DateInputControl dtpDeliveryDate;
private WinFormsLibrary1.ComboBoxUserControl cmbManufacturer;
private Library14Petrushin.TextBoxRange txtName;
private PictureBox pbImage;
private Button button1;
private Button button2;
}
}

116
Laba3/ProductForm.cs Normal file
View File

@ -0,0 +1,116 @@
using Data;
using Data.Models;
using Data.Repositories;
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;
namespace Laba3
{
public partial class ProductForm : Form
{
private readonly IProductRepository _productRepository;
private readonly IManufacturerRepository _manufacturerRepository;
private Product _product;
private bool _isNewProduct;
private const int MINL = 3;
private const int MAXL= 10;
public ProductForm(IProductRepository productRepository, IManufacturerRepository manufacturerRepository, Product product = null)
{
InitializeComponent();
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
_productRepository = productRepository;
_manufacturerRepository = manufacturerRepository;
var manufacturers = _manufacturerRepository.GetAllManufacturers().Select(m => m.Name).ToList();
// cmbManufacturer.Data = manufacturers;
foreach (var manufacturer in manufacturers)
{
cmbManufacturer.AddItem(manufacturer);
}
_product = product;
_isNewProduct = product == null;
txtName.MinLength = MINL;
txtName.MaxLength = MAXL;
dtpDeliveryDate.DateFormat = "dd MMMM yyyy";
if (!_isNewProduct)
{
txtName.InputValue = _product.Name;
cmbManufacturer.SelectedValue = _product.ManufacturerName;
dtpDeliveryDate.Date = _product.DeliveryDate;
if (_product.Image != null)
{
using (var ms = new MemoryStream(_product.Image))
{
pbImage.Image = Image.FromStream(ms);
}
}
}
}
private void btnBrowse_Click(object sender, EventArgs e)
{
using (var openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
pbImage.Image = Image.FromFile(openFileDialog.FileName);
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(txtName.InputValue))
{
MessageBox.Show("Name is required.");
return;
}
if (_isNewProduct)
{
_product = new Product();
}
_product.Name = txtName.InputValue;
_product.ManufacturerName = cmbManufacturer.SelectedValue.ToString();
_product.DeliveryDate = dtpDeliveryDate.Date;
if (pbImage.Image != null)
{
using (var ms = new MemoryStream())
{
pbImage.Image.Save(ms, pbImage.Image.RawFormat);
_product.Image = ms.ToArray();
}
}
if (_isNewProduct)
{
_productRepository.AddProduct(_product);
}
else
{
_productRepository.UpdateProduct(_product);
}
DialogResult = DialogResult.OK;
Close();
}
}
}

120
Laba3/ProductForm.resx Normal file
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>

25
Laba3/Program.cs Normal file
View File

@ -0,0 +1,25 @@
using Data.Repositories;
using Data;
namespace Laba3
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
// Ñîçäàíèå ýêçåìïëÿðîâ ðåïîçèòîðèåâ
var dbContext = new ApplicationDbContext();
var productRepository = new ProductRepository(dbContext);
var manufacturerRepository = new ManufacturerRepository(dbContext);
// Ïåðåäà÷à ðåïîçèòîðèåâ â êîíñòðóêòîð MainForm
Application.Run(new MainForm(productRepository, manufacturerRepository));
}
}
}

28
Laba3/View.csproj Normal file
View File

@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Library15Gerimovich" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.10" />
<PackageReference Include="WinFormsLibrary1" Version="1.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Library14Petrushin\Library14Petrushin.csproj" />
<ProjectReference Include="..\Models\Data.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,27 @@
using Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace View.ViewModels
{
public class ProductTableItem
{
public string Id { get; set; }
public string Name { get; set; }
public string ManufacturerName { get; set; }
public string DeliveryDate { get; set; }
public static List<ProductTableItem> ConvertProductsToTableItems(List<Product> products)
{
return products.Select(p => new ProductTableItem
{
Id = p.Id.ToString(),
Name = p.Name,
ManufacturerName = p.ManufacturerName,
DeliveryDate = p.DeliveryDate.ToShortDateString()
}).ToList();
}
}
}

5
Laba3/appsettings.json Normal file
View File

@ -0,0 +1,5 @@
{
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Port=5432;Database=kop;Username=postgres;Password=postgres"
}
}

View File

@ -0,0 +1,58 @@
namespace Library14Petrushin
{
partial class ChooseList
{
/// <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()
{
checkedListBox1 = new CheckedListBox();
SuspendLayout();
//
// checkedListBox1
//
checkedListBox1.FormattingEnabled = true;
checkedListBox1.Location = new Point(3, 3);
checkedListBox1.Name = "checkedListBox1";
checkedListBox1.Size = new Size(179, 180);
checkedListBox1.TabIndex = 0;
checkedListBox1.ItemCheck += CheckedListBox1_ItemCheck;
checkedListBox1.SelectedIndexChanged += SelectedIndexChanged;
//
// ChooseList
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(checkedListBox1);
Name = "ChooseList";
Size = new Size(186, 192);
ResumeLayout(false);
}
#endregion
private CheckedListBox checkedListBox1;
}
}

View File

@ -0,0 +1,71 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace Library14Petrushin
{
public partial class ChooseList : UserControl
{
public event EventHandler? SelectedValueChanged;
public string SelectedValue
{
get
{
return checkedListBox1.SelectedItem?.ToString() ?? string.Empty;
}
set
{
int index = checkedListBox1.Items.IndexOf(value);
if (index >= 0)
{
checkedListBox1.SelectedIndex = index;
}
else
{
checkedListBox1.ClearSelected();
}
}
}
public ChooseList()
{
InitializeComponent();
}
public void AddItemToList(string item)
{
checkedListBox1.Items.Add(item);
}
private void SelectedIndexChanged(object sender, EventArgs e)
{
SelectedValueChanged?.Invoke(this, e);
}
private void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Checked)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (i != e.Index)
{
checkedListBox1.SetItemChecked(i, false);
}
}
}
}
public void ClearComboBox()
{
checkedListBox1.Items.Clear();
}
}
}

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,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library14Petrushin.Classes
{
public class ChartData
{
public string? SeriesName { get; set; }
public double Value { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library14Petrushin.Classes
{
public class Employee
{
public string? Department { get; set; }
public string? Position { get; set; }
public string? FullName { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library14Petrushin.Classes
{
public enum LegendPosition
{
Top,
Bottom,
Left,
Right
}
}

View File

@ -0,0 +1,9 @@
namespace Library14Petrushin
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
}

View File

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

View File

@ -0,0 +1,55 @@
namespace Library14Petrushin
{
partial class HierarchicalTreeView
{
/// <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()
{
treeView1 = new TreeView();
SuspendLayout();
//
// treeView1
//
treeView1.Location = new Point(3, 3);
treeView1.Name = "treeView1";
treeView1.Size = new Size(258, 496);
treeView1.TabIndex = 0;
//
// TreeViewIerarch
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(treeView1);
Name = "TreeViewIerarch";
Size = new Size(264, 502);
ResumeLayout(false);
}
#endregion
private TreeView treeView1;
}
}

View File

@ -0,0 +1,96 @@
using Library14Petrushin.Classes;
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 Library14Petrushin
{
public partial class HierarchicalTreeView : UserControl
{
private List<string> hierarchy;
private Dictionary<string, bool> alwaysNewBranch;
public HierarchicalTreeView()
{
InitializeComponent();
hierarchy = new List<string>();
alwaysNewBranch = new Dictionary<string, bool>();
}
public void SetHierarchy(List<string> hierarchy, Dictionary<string, bool> alwaysNewBranch)
{
this.hierarchy = hierarchy;
this.alwaysNewBranch = alwaysNewBranch;
}
public void AddObjectToTree<T>(T obj, string stopAtProperty)
{
TreeNode currentNode = treeView1.Nodes.Count > 0 ? treeView1.Nodes[0] : treeView1.Nodes.Add("");
foreach (var property in hierarchy)
{
var value = obj.GetType().GetProperty(property).GetValue(obj, null).ToString();
bool createNewBranch = alwaysNewBranch.ContainsKey(property) && alwaysNewBranch[property];
var childNode = currentNode.Nodes.Cast<TreeNode>().FirstOrDefault(n => n.Text == value);
if (childNode == null || createNewBranch)
{
childNode = currentNode.Nodes.Add(value);
}
currentNode = childNode;
if (property == stopAtProperty)
{
break;
}
}
}
public int SelectedNodeIndex
{
get
{
return treeView1.SelectedNode?.Index ?? -1;
}
set
{
if (value >= 0 && value < treeView1.Nodes.Count)
{
treeView1.SelectedNode = treeView1.Nodes[value];
}
}
}
public T GetSelectedObject<T>() where T : new()
{
if (treeView1.SelectedNode == null)
{
throw new InvalidOperationException("Узел не выбран");
}
var node = treeView1.SelectedNode;
if (node.Nodes.Count != 0)
{
throw new InvalidOperationException("Узел не конечный, сформировать класс нельзя");
}
var obj = new T();
foreach (var property in hierarchy)
{
var value = node.Text;
obj.GetType().GetProperty(property).SetValue(obj, value);
node = node.Parent;
if (node == null)
{
break;
}
}
return obj;
}
}
}

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,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="PDFsharp" Version="6.1.1" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.35013.160
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Library14Petrushin", "Library14Petrushin.csproj", "{64A09BF4-7D97-49DE-8AB8-E9C23B75A62D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "View", "..\Laba3\View.csproj", "{F342448F-F458-45A7-B335-EAD594D6B7A4}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Data", "..\Models\Data.csproj", "{DC70937E-903F-4BAA-A774-80D01EC5B75A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{64A09BF4-7D97-49DE-8AB8-E9C23B75A62D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{64A09BF4-7D97-49DE-8AB8-E9C23B75A62D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{64A09BF4-7D97-49DE-8AB8-E9C23B75A62D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{64A09BF4-7D97-49DE-8AB8-E9C23B75A62D}.Release|Any CPU.Build.0 = Release|Any CPU
{F342448F-F458-45A7-B335-EAD594D6B7A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F342448F-F458-45A7-B335-EAD594D6B7A4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F342448F-F458-45A7-B335-EAD594D6B7A4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F342448F-F458-45A7-B335-EAD594D6B7A4}.Release|Any CPU.Build.0 = Release|Any CPU
{DC70937E-903F-4BAA-A774-80D01EC5B75A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DC70937E-903F-4BAA-A774-80D01EC5B75A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DC70937E-903F-4BAA-A774-80D01EC5B75A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DC70937E-903F-4BAA-A774-80D01EC5B75A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {2A1168BB-4009-411F-98CD-BE56BE8D07AF}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,36 @@
namespace Library14Petrushin
{
partial class PdfCirclDiagr
{
/// <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,95 @@
using Library14Petrushin.Classes;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library14Petrushin
{
public partial class PdfCirclDiagr : Component
{
public void GeneratePdf(
string fileName,
string documentTitle,
string chartTitle,
LegendPosition legendPosition,
List<ChartData> chartData)
{
// Проверка на заполненность входных данных
if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(documentTitle) ||
string.IsNullOrEmpty(chartTitle) || chartData == null || !chartData.Any())
{
throw new ArgumentException("Все входные данные должны быть заполнены.");
}
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Verdana", 10);
gfx.DrawString(documentTitle, new XFont("Verdana", 16, XFontStyleEx.Bold), XBrushes.Black, new XRect(0, 0, page.Width, 50), XStringFormats.Center);
gfx.DrawString(chartTitle, font, XBrushes.Black, new XRect(50, 50, page.Width - 100, 30), XStringFormats.Center);
DrawPieChart(gfx, new XRect(50, 100, 300, 300), chartData, legendPosition);
// Сохранение документа
document.Save(fileName);
}
private void DrawPieChart(XGraphics gfx, XRect rect, List<ChartData> chartData, LegendPosition legendPosition)
{
double total = chartData.Sum(d => d.Value);
double startAngle = 0;
int legendX = 0;
int legendY = 0;
// Определение расположения легенды
switch (legendPosition)
{
case LegendPosition.Top:
legendX = (int)rect.X + (int)rect.Width / 2;
legendY = (int)rect.Y - 50;
break;
case LegendPosition.Bottom:
legendX = (int)rect.X + (int)rect.Width / 2;
legendY = (int)rect.Y + (int)rect.Height + 20;
break;
case LegendPosition.Left:
legendX = (int)rect.X - 100;
legendY = (int)rect.Y + (int)rect.Height / 2;
break;
case LegendPosition.Right:
legendX = (int)rect.X + (int)rect.Width + 20;
legendY = (int)rect.Y + (int)rect.Height / 2;
break;
}
// Отрисовка секторов диаграммы и легенды
foreach (var data in chartData)
{
double sweepAngle = 360 * (data.Value / total);
gfx.DrawPie(GetRandomBrush(), rect, startAngle, sweepAngle);
startAngle += sweepAngle;
gfx.DrawString(data.SeriesName, new XFont("Verdana", 8), XBrushes.Black, new XPoint(legendX, legendY));
legendY += 20;
}
}
private XBrush GetRandomBrush()
{
Random random = new Random();
return new XSolidBrush(XColor.FromArgb(random.Next(256), random.Next(256), random.Next(256)));
}
}
}

View File

@ -0,0 +1,36 @@
namespace Library14Petrushin
{
partial class PdfColGroupTable
{
/// <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,109 @@
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library14Petrushin
{
public partial class PdfColGroupTable : Component
{
public void GeneratePdf<T>(
string fileName,
string documentTitle,
List<(int startRow, int endRow, int startColumn, int endColumn)> mergeCells,
List<double> rowHeights,
List<(string, string)> headersNames,
List<string> commonHeaders,
List<T> data)
{
// Проверка на заполненность входных данных
if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(documentTitle) ||
mergeCells == null || rowHeights == null || headersNames == null || data == null)
{
throw new ArgumentException("Все входные данные должны быть заполнены.");
}
// Проверка на соответствие количества строк и высот строк
if (rowHeights.Count != data.Count)
{
throw new ArgumentException("Количество высот строк должно совпадать с количеством строк данных.");
}
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Verdana", 10);
gfx.DrawString(documentTitle, new XFont("Verdana", 16, XFontStyleEx.Bold), XBrushes.Black, new XRect(0, 0, page.Width, 50), XStringFormats.Center);
// Отрисовка таблицы
double margin = 50; // Отступ от краев страницы
double x = margin;
double y = 70;
double rowHeight = 20; // Фиксированная высота строки
double columnWidth = (page.Width - 2 * margin) / (headersNames.Count + 1); // Ширина столбца
// Отрисовка шапки
for (int col = 0; col < commonHeaders.Count; col++)
{
gfx.DrawString(commonHeaders[col], font, XBrushes.Black, new XRect(x, y + col * rowHeight, columnWidth, rowHeight), XStringFormats.CenterLeft);
gfx.DrawRectangle(XPens.Black, new XRect(x, y + col * rowHeight, columnWidth, rowHeight)); // Добавляем рамку
}
x += columnWidth;
for (int col = 0; col < headersNames.Count; col++)
{
gfx.DrawString(headersNames[col].Item1, font, XBrushes.Black, new XRect(x, y + col * rowHeight, columnWidth, rowHeight), XStringFormats.CenterLeft);
gfx.DrawRectangle(XPens.Black, new XRect(x, y + col * rowHeight, columnWidth, rowHeight)); // Добавляем рамку
}
x += columnWidth;
// Отрисовка данных
for (int col = 0; col < data.Count; col++)
{
for (int row = 0; row < headersNames.Count; row++)
{
var item = data[col];
var property = item.GetType().GetProperty(headersNames[row].Item2);
if (property != null)
{
var value = property.GetValue(item)?.ToString() ?? string.Empty;
gfx.DrawString(value, font, XBrushes.Black, new XRect(x + col * columnWidth, y + row * rowHeight, columnWidth, rowHeight), XStringFormats.CenterLeft);
gfx.DrawRectangle(XPens.Black, new XRect(x + col * columnWidth, y + row * rowHeight, columnWidth, rowHeight)); // Добавляем рамку
}
}
}
// Объединение ячеек
foreach (var (startRow, endRow, startColumn, endColumn) in mergeCells)
{
double mergeX = margin + (startColumn * columnWidth);
double mergeWidth = (endColumn - startColumn + 1) * columnWidth;
double mergeY = 70 + (startRow * rowHeight);
double mergeHeight = (endRow - startRow + 1) * rowHeight;
gfx.DrawRectangle(XPens.Black, XBrushes.White, new XRect(mergeX, mergeY, mergeWidth, mergeHeight));
if (endColumn == 0)
{
gfx.DrawString(commonHeaders[startRow], font, XBrushes.Black, new XRect(mergeX, mergeY, mergeWidth, mergeHeight), XStringFormats.Center);
}
else
{
gfx.DrawString(headersNames[startRow].Item1, font, XBrushes.Black, new XRect(mergeX, mergeY, mergeWidth, mergeHeight), XStringFormats.Center);
}
}
document.Save(fileName);
}
}
}

36
Library14Petrushin/PdfImg.Designer.cs generated Normal file
View File

@ -0,0 +1,36 @@
namespace Library14Petrushin
{
partial class PdfImg
{
/// <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,81 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
namespace Library14Petrushin
{
public partial class PdfImg : Component
{
public PdfImg()
{
InitializeComponent();
}
public PdfImg(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreatePdfDocument(string fileName, string documentTitle, List<ImageData> images)
{
if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(documentTitle) || images == null || images.Count == 0)
{
throw new ArgumentException("Все входные данные должны быть заполнены.");
}
PdfDocument document = new PdfDocument();
PdfPage firstPage = document.AddPage();
XGraphics gfxFirstPage = XGraphics.FromPdfPage(firstPage);
XFont font = new XFont("Arial", 20, XFontStyleEx.BoldItalic);
// Рисуем заголовок на первой странице
gfxFirstPage.DrawString(documentTitle, font, XBrushes.Black, new XRect(0, 0, firstPage.Width, 50), XStringFormats.Center);
// Добавляем изображение на первую страницу
if (images.Count > 0)
{
using (XImage img = XImage.FromFile(images[0].ImagePath))
{
double imageWidth = img.PixelWidth * 72 / img.HorizontalResolution;
double imageHeight = img.PixelHeight * 72 / img.VerticalResolution;
double scale = Math.Min(firstPage.Width / imageWidth, (firstPage.Height - 50) / imageHeight); // Учитываем высоту заголовка
double imageX = (firstPage.Width - imageWidth * scale) / 2; // Центрируем изображение по горизонтали
double imageY = 50; // Начинаем рисовать изображение под заголовком
gfxFirstPage.DrawImage(img, imageX, imageY, imageWidth * scale, imageHeight * scale);
}
}
// Добавляем остальные изображения на новые страницы
for (int i = 1; i < images.Count; i++)
{
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
using (XImage img = XImage.FromFile(images[i].ImagePath))
{
double imageWidth = img.PixelWidth * 72 / img.HorizontalResolution;
double imageHeight = img.PixelHeight * 72 / img.VerticalResolution;
double scale = Math.Min(page.Width / imageWidth, page.Height / imageHeight);
gfx.DrawImage(img, 0, 0, imageWidth * scale, imageHeight * scale);
}
}
document.Save(fileName);
}
}
public class ImageData
{
public string ImagePath { get; set; }
}
}

View File

@ -0,0 +1,68 @@
namespace Library14Petrushin
{
partial class TextBoxRange
{
/// <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()
{
textBox1 = new TextBox();
label1 = new Label();
SuspendLayout();
//
// textBox1
//
textBox1.Location = new Point(3, 14);
textBox1.Name = "textBox1";
textBox1.Size = new Size(243, 27);
textBox1.TabIndex = 0;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(3, 54);
label1.Name = "label1";
label1.Size = new Size(50, 20);
label1.TabIndex = 1;
label1.Text = "label1";
//
// TextBoxRange
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(label1);
Controls.Add(textBox1);
Name = "TextBoxRange";
Size = new Size(252, 86);
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBox1;
private Label label1;
}
}

View File

@ -0,0 +1,67 @@
using Library14Petrushin.Exeptions;
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 Library14Petrushin
{
public partial class TextBoxRange : UserControl
{
public int ?MinLength { get; set; }
public int ?MaxLength { get; set; }
public event EventHandler? ValueChanged;
public string InputValue
{
get
{
if (MinLength == null && MaxLength == null)
{
throw new RangeException("Диапазон не задан.");
}
if (textBox1.Text.Length < MinLength || textBox1.Text.Length > MaxLength)
{
throw new RangeException("Введенное значение не входит в диапазон.");
}
return textBox1.Text;
}
set
{
if (MinLength != null && MaxLength != null)
{
if (value.Length >= MinLength && value.Length <= MaxLength)
{
textBox1.Text = value;
ValueChanged?.Invoke(this, EventArgs.Empty);
}
}
}
}
public TextBoxRange()
{
InitializeComponent();
textBox1.TextChanged += TextBox1_TextChanged;
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
ValueChanged?.Invoke(this, e);
if (MinLength != null && MaxLength != null)
{
if (textBox1.Text.Length < MinLength || textBox1.Text.Length > MaxLength)
{
textBox1.ForeColor = Color.Red;
}
else
{
textBox1.ForeColor = Color.Black;
}
}
}
}
}

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,21 @@
using Data.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data
{
public class ApplicationDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Manufacturer> Manufacturers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseNpgsql("Host=localhost;Port=5432;Database=cop;Username=postgres;Password=postgres");
}
}
}

19
Models/Data.csproj Normal file
View File

@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.10">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.10" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,78 @@
// <auto-generated />
using System;
using Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20241029070533_Init")]
partial class Init
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Models.Manufacturer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.HasKey("Id");
b.ToTable("Manufacturers");
});
modelBuilder.Entity("Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("DeliveryDate")
.HasColumnType("date");
b.Property<byte[]>("Image")
.IsRequired()
.HasColumnType("bytea");
b.Property<string>("ManufacturerName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.HasKey("Id");
b.ToTable("Products");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,55 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Data.Migrations
{
/// <inheritdoc />
public partial class Init : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Manufacturers",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Manufacturers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
Image = table.Column<byte[]>(type: "bytea", nullable: false),
ManufacturerName = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
DeliveryDate = table.Column<DateTime>(type: "date", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Manufacturers");
migrationBuilder.DropTable(
name: "Products");
}
}
}

View File

@ -0,0 +1,75 @@
// <auto-generated />
using System;
using Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.10")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("Models.Manufacturer", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.HasKey("Id");
b.ToTable("Manufacturers");
});
modelBuilder.Entity("Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateTime>("DeliveryDate")
.HasColumnType("date");
b.Property<byte[]>("Image")
.IsRequired()
.HasColumnType("bytea");
b.Property<string>("ManufacturerName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.HasKey("Id");
b.ToTable("Products");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data.Models
{
public class Manufacturer
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
}
}

30
Models/Models/Product.cs Normal file
View File

@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data.Models
{
public class Product
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
public byte[] Image { get; set; }
[Required]
[MaxLength(100)]
public string ManufacturerName { get; set; }
[Required]
[Column(TypeName = "date")]
public DateTime DeliveryDate { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data.Repositories
{
public interface IManufacturerRepository
{
IEnumerable<Manufacturer> GetAllManufacturers();
Manufacturer GetManufacturerById(int id);
void AddManufacturer(Manufacturer manufacturer);
void UpdateManufacturer(Manufacturer manufacturer);
void DeleteManufacturer(int id);
}
}

View File

@ -0,0 +1,18 @@
using Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data.Repositories
{
public interface IProductRepository
{
IEnumerable<Product> GetAllProducts();
Product GetProductById(int id);
void AddProduct(Product product);
void UpdateProduct(Product product);
void DeleteProduct(int id);
}
}

View File

@ -0,0 +1,51 @@
using Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data.Repositories
{
public class ManufacturerRepository : IManufacturerRepository
{
private readonly ApplicationDbContext _context;
public ManufacturerRepository(ApplicationDbContext context)
{
_context = context;
}
public IEnumerable<Manufacturer> GetAllManufacturers()
{
return _context.Manufacturers.ToList();
}
public Manufacturer GetManufacturerById(int id)
{
return _context.Manufacturers.Find(id);
}
public void AddManufacturer(Manufacturer manufacturer)
{
_context.Manufacturers.Add(manufacturer);
_context.SaveChanges();
}
public void UpdateManufacturer(Manufacturer manufacturer)
{
_context.Manufacturers.Update(manufacturer);
_context.SaveChanges();
}
public void DeleteManufacturer(int id)
{
var manufacturer = _context.Manufacturers.Find(id);
if (manufacturer != null)
{
_context.Manufacturers.Remove(manufacturer);
_context.SaveChanges();
}
}
}
}

View File

@ -0,0 +1,51 @@
using Data.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data.Repositories
{
public class ProductRepository : IProductRepository
{
private readonly ApplicationDbContext _context;
public ProductRepository(ApplicationDbContext context)
{
_context = context;
}
public IEnumerable<Product> GetAllProducts()
{
return _context.Products.ToList();
}
public Product GetProductById(int id)
{
return _context.Products.Find(id);
}
public void AddProduct(Product product)
{
_context.Products.Add(product);
_context.SaveChanges();
}
public void UpdateProduct(Product product)
{
_context.Products.Update(product);
_context.SaveChanges();
}
public void DeleteProduct(int id)
{
var product = _context.Products.Find(id);
if (product != null)
{
_context.Products.Remove(product);
_context.SaveChanges();
}
}
}
}