Compare commits

...

12 Commits

Author SHA1 Message Date
a.puchkina
0523ce7467 сдала 3 лабу! 2024-11-12 08:59:49 +04:00
a.puchkina
f18b475248 ура ура 3 лаба 2024-11-11 19:40:06 +04:00
a.puchkina
3729d74f4f все готово, спать 2024-10-28 23:31:04 +04:00
a.puchkina
caaa65f204 pdf с картинками 2024-10-28 21:17:45 +04:00
a.puchkina
17c1521e2a ыть 2024-10-28 20:45:12 +04:00
a.puchkina
30b3ef6a2d что-то с чем-то 2024-10-28 18:56:11 +04:00
a.puchkina
019751daa5 сдала 2 лабу 2024-10-15 14:03:10 +04:00
a.puchkina
fc9e59165f лаба 3, часть 1 2024-10-15 00:34:02 +04:00
a.puchkina
97b6b89c3a Исправила всякое в ListBox, сделала формочку, исправила ошибку при создании pdf с изображением, починила дерево, ну короче всего по-немножку 2024-10-03 20:36:56 +04:00
a.puchkina
e9ccb205f5 лаба 2, формочка осталась 2024-09-30 23:07:42 +04:00
a.puchkina
6639c7be4d правочки (сдано) 2024-09-17 11:47:53 +04:00
a.puchkina
cd2b5a857b пык мык готово вроде 2024-09-16 23:10:50 +04:00
66 changed files with 4603 additions and 7 deletions

View File

@ -3,7 +3,11 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.7.34024.191
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "COP_5", "COP_5\COP_5.csproj", "{58462D33-6017-4160-B57C-59E3C03C0654}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "COP_5", "COP_5\COP_5.csproj", "{58462D33-6017-4160-B57C-59E3C03C0654}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinFormsApp", "WinFormsApp\WinFormsApp.csproj", "{82CFE6F8-94F2-45E0-B6C2-59E036235BB9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LibraryAccountingApp_lab3", "LibraryAccountingApp_lab3\LibraryAccountingApp_lab3.csproj", "{6B665435-1A86-44B4-B4C9-B0F29559314D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -15,6 +19,14 @@ Global
{58462D33-6017-4160-B57C-59E3C03C0654}.Debug|Any CPU.Build.0 = Debug|Any CPU
{58462D33-6017-4160-B57C-59E3C03C0654}.Release|Any CPU.ActiveCfg = Release|Any CPU
{58462D33-6017-4160-B57C-59E3C03C0654}.Release|Any CPU.Build.0 = Release|Any CPU
{82CFE6F8-94F2-45E0-B6C2-59E036235BB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{82CFE6F8-94F2-45E0-B6C2-59E036235BB9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{82CFE6F8-94F2-45E0-B6C2-59E036235BB9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{82CFE6F8-94F2-45E0-B6C2-59E036235BB9}.Release|Any CPU.Build.0 = Release|Any CPU
{6B665435-1A86-44B4-B4C9-B0F29559314D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6B665435-1A86-44B4-B4C9-B0F29559314D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6B665435-1A86-44B4-B4C9-B0F29559314D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6B665435-1A86-44B4-B4C9-B0F29559314D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -5,6 +5,18 @@
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
<Content Remove="C:\Users\annap\.nuget\packages\pdfsharp.standard\1.51.15\contentFiles\any\netstandard2.0\SharpZipLib\ReadMe.txt" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ComponentsLibraryNet60" Version="1.0.0" />
<PackageReference Include="FedComponentLib" Version="1.0.0" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="PDFSharp.Standard" Version="1.51.15" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,60 @@
using System.Windows.Forms;
namespace COP_5
{
partial class ChooseCheckedListBox
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
checkedListBox = new CheckedListBox();
SuspendLayout();
//
// checkedListBox
//
checkedListBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
checkedListBox.FormattingEnabled = true;
checkedListBox.Location = new Point(3, 3);
checkedListBox.Name = "checkedListBox";
checkedListBox.Size = new Size(144, 130);
checkedListBox.TabIndex = 0;
checkedListBox.ItemCheck += CheckedListBox_ItemCheck;
//
// UserControlChooseList
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(checkedListBox);
Name = "UserControlChooseList";
Size = new Size(150, 138);
ResumeLayout(false);
}
#endregion
private CheckedListBox checkedListBox;
}
}

View File

@ -0,0 +1,62 @@
using System.Windows.Forms;
namespace COP_5
{
public partial class ChooseCheckedListBox : UserControl
{
public ChooseCheckedListBox()
{
InitializeComponent();
}
public event EventHandler? SelectedValueChanged;
private void CheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Checked)
{
for (int i = 0; i < checkedListBox.Items.Count; i++)
{
if (i != e.Index)
{
checkedListBox.SetItemChecked(i, false);
}
}
}
}
public string SelectedValue
{
get
{
return checkedListBox.SelectedItem?.ToString() ?? string.Empty;
}
set
{
int index = checkedListBox.Items.IndexOf(value);
if (index >= 0)
{
checkedListBox.SelectedIndex = index;
}
else
{
checkedListBox.ClearSelected();
}
}
}
public void AddItemToList(string item)
{
if (item == null)
{
return;
}
checkedListBox.Items.Add(item);
}
public void ClearComboBox()
{
checkedListBox.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

@ -1,6 +0,0 @@
namespace COP_5
{
public class Class1
{
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace COP_5.Exceptions
{
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,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace COP_5.Exceptions
{
public class TreeViewException : Exception
{
public TreeViewException() { }
public TreeViewException(string message) : base(message) { }
public TreeViewException(string message, Exception inner) : base(message, inner) { }
}
}

36
COP_5/COP_5/PdfForDiagram.Designer.cs generated Normal file
View File

@ -0,0 +1,36 @@
namespace COP_5
{
partial class PdfForDiagram
{
/// <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,111 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Shapes;
using MigraDoc.Rendering;
using System.ComponentModel;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using COP_5.PdfHelper;
namespace COP_5
{
public partial class PdfForDiagram : Component
{
public PdfForDiagram()
{
InitializeComponent();
}
public PdfForDiagram(IContainer container)
{
container.Add(this);
InitializeComponent();
}
private Document _document;
private Chart _chart;
private Document Document
{
get
{
if (_document == null)
{
_document = new Document();
}
return _document;
}
}
public void CreateHeader(string header)
{
var section = Document.AddSection();
var paragraph = section.AddParagraph(header);
paragraph.Format.Font.Color = Colors.Black;
paragraph.Format.Font.Bold = true;
}
private void ConfigChart(DiagramPdfInfo info)
{
((Shape)_chart).Width = Unit.FromCentimeter(16.0);
((Shape)_chart).Height = Unit.FromCentimeter(12.0);
_chart.TopArea.AddParagraph(info.ChartTitle);
_chart.XAxis.MajorTickMark = (TickMarkType)2;
_chart.YAxis.MajorTickMark = (TickMarkType)2;
_chart.YAxis.HasMajorGridlines = true;
_chart.PlotArea.LineFormat.Width = new Unit(1);
_chart.PlotArea.LineFormat.Visible = true;
switch (info.LegendLocation)
{
case PdfParagraphAlignmentType.Left:
_chart.LeftArea.AddLegend();
break;
case PdfParagraphAlignmentType.Right:
_chart.RightArea.AddLegend();
break;
case PdfParagraphAlignmentType.Top:
_chart.TopArea.AddLegend();
break;
case PdfParagraphAlignmentType.Bottom:
_chart.BottomArea.AddLegend();
break;
}
}
public void CreatePieChart(DiagramPdfInfo info)
{
_chart = new Chart(ChartType.Pie2D);
foreach (var kvp in info.Data)
{
Series series = _chart.SeriesCollection.AddSeries();
series.Name = kvp.Key;
series.Add(kvp.Value.Select(x => x.Value).ToArray()); // Используем Value для данных
}
_chart.XValues.AddXSeries().Add(info.Data.First().Value.Select(x => x.Name).ToArray()); // Используем Date для оси X
ConfigChart(info);
}
public void SaveDoc(string filepath)
{
if (string.IsNullOrEmpty(filepath))
throw new ArgumentNullException(nameof(filepath), "File path cannot be null or empty.");
if (_document == null)
throw new ArgumentNullException(nameof(_document), "Document is not created.");
if (_chart != null)
_document.LastSection.Add(_chart);
PdfDocumentRenderer documentRenderer = new PdfDocumentRenderer(true)
{
Document = _document
};
documentRenderer.RenderDocument();
documentRenderer.PdfDocument.Save(filepath);
}
public void CreateDoc(DiagramPdfInfo info)
{
info.CheckFields();
CreateHeader(info.Header);
CreatePieChart(info);
SaveDoc(info.FilePath);
}
}
}

36
COP_5/COP_5/PdfForImages.Designer.cs generated Normal file
View File

@ -0,0 +1,36 @@
namespace COP_5
{
partial class PdfForImages
{
/// <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
}
}

134
COP_5/COP_5/PdfForImages.cs Normal file
View File

@ -0,0 +1,134 @@
using System.ComponentModel;
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using COP_5.PdfHelper;
using System.Text;
namespace COP_5
{
public partial class PdfForImages : Component
{
private Document _document = null;
private Section _section = null;
private List<byte[]> _images = null;
private Document Document
{
get
{
if (_document == null)
{
_document = new Document();
}
return _document;
}
}
private Section Section
{
get
{
if (_section == null)
{
_section = Document.AddSection();
}
return _section;
}
}
private List<byte[]> Images
{
get
{
if (_images == null)
{
_images = new List<byte[]>();
}
return _images;
}
}
public PdfForImages()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
InitializeComponent();
}
public PdfForImages(IContainer container)
{
container.Add(this);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
InitializeComponent();
}
public void CreatePdf(ImagePdfInfo info)
{
ClearDocument();
info.CheckFields();
CreateHeader(info.Header);
foreach (var image in info.Images)
{
CreateImage(image);
}
SavePdf(info.FilePath);
}
private void ClearDocument()
{
_document = new Document();
_section = _document.AddSection();
}
private void CreateHeader(string header)
{
var paragraph = Section.AddParagraph(header);
paragraph.Format.Font.Name = "Arial";
paragraph.Format.Font.Bold = true;
paragraph.Format.Font.Size = 20;
paragraph.Format.SpaceAfter = 10;
}
private void SavePdf(string filepath)
{
if (string.IsNullOrWhiteSpace(filepath))
{
throw new ArgumentNullException("Имя файла не задано");
}
if (_document == null || _section == null)
{
throw new ArgumentNullException("Документ не сформирован, сохранять нечего");
}
var pdfRenderer = new PdfDocumentRenderer(true)
{
Document = _document,
};
pdfRenderer.RenderDocument();
pdfRenderer.Save(filepath);
}
public void CreateImage(byte[] image)
{
if (image == null || image.Length == 0)
{
throw new ArgumentNullException("Картинка не загружена");
}
Images.Add(image);
var imageFileName = Path.GetTempFileName();
File.WriteAllBytes(imageFileName, image);
var img = Section.AddImage(imageFileName);
img.Width = Unit.FromCentimeter(15);
img.LockAspectRatio = true;
Section.AddParagraph();
}
}
}

36
COP_5/COP_5/PdfForTables.Designer.cs generated Normal file
View File

@ -0,0 +1,36 @@
namespace COP_5
{
partial class PdfForTables
{
/// <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
}
}

103
COP_5/COP_5/PdfForTables.cs Normal file
View File

@ -0,0 +1,103 @@
using System.ComponentModel;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using System.Reflection;
using COP_5.PdfHelper;
using COP_5.TestClasses;
namespace COP_5
{
public partial class PdfForTables : Component
{
public void CreatePdf<T>(TablePdfInfo<T> info)
{
info.CheckFields();
// Создание документа
var document = new Document();
var section = document.AddSection();
// Установка заголовка
var titleParagraph = section.AddParagraph(info.Title);
titleParagraph.Format.Alignment = ParagraphAlignment.Center;
titleParagraph.Format.Font.Size = 16;
titleParagraph.Format.Font.Bold = true;
titleParagraph.Format.SpaceAfter = 20;
// Создание таблицы
var table = section.AddTable();
table.Borders.Width = 0.75;
// Создание столбцов
for (int i = 0; i < info.Data.Count + 2; i++)
{
var column = table.AddColumn(Unit.FromCentimeter(3)); // Ширину можно настроить
column.Format.Alignment = ParagraphAlignment.Center;
}
// Создание заголовков
int rowNum = 0;
foreach (var kvp in info.Headers)
{
string key = kvp.Key;
List<(string Name, string Value)> values = kvp.Value;
if (values.Count == 0)
{
var row = table.AddRow();
row.Height = Unit.FromCentimeter(info.RowHeights[rowNum]); // Высота строки
row.Cells[0].AddParagraph(key);
row.Cells[0].MergeRight = 1;
rowNum++;
}
else
{
var row = table.AddRow();
row.Height = Unit.FromCentimeter(info.RowHeights[rowNum]); // Высота строки
row.Cells[0].AddParagraph(key);
row.Cells[0].MergeDown = values.Count - 1;
rowNum++;
for (int i = 0; i < values.Count; i++)
{
rowNum = 0;
row.Height = Unit.FromCentimeter(info.RowHeights[rowNum]);
row.Cells[1].AddParagraph(values[i].Value);
if (i < values.Count - 1)
row = table.AddRow();
}
rowNum++;
}
}
// Заполнение данных
int colIndex = 0;
foreach (var item in info.Data)
{
int rowIndex = 0;
Type type = typeof(Human);
PropertyInfo[] properties = type.GetProperties();
foreach (var property in properties)
{
// Здесь предполагается, что у вас есть объект table, который представляет таблицу в PDF
// и метод AddParagraph для добавления текста в ячейку таблицы
table.Rows[rowIndex].Cells[colIndex + 2].AddParagraph(property.GetValue(item).ToString());
rowIndex++;
}
colIndex++;
}
// Рендеринг документа в PDF
var pdfRenderer = new PdfDocumentRenderer(true)
{
Document = document
};
pdfRenderer.RenderDocument();
pdfRenderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -0,0 +1,21 @@
namespace COP_5.PdfHelper
{
public class DiagramPdfInfo
{
public string FilePath { get; set; }
public string Header { get; set; }
public string ChartTitle { get; set; }
public PdfParagraphAlignmentType LegendLocation { get; set; }
public Dictionary<string, List<(string Name, double Value)>> Data { get; set; }
public void CheckFields()
{
if (string.IsNullOrEmpty(FilePath))
throw new ArgumentNullException(nameof(FilePath), "Путь к файлу не может быть null или пустым.");
if (string.IsNullOrEmpty(Header))
throw new ArgumentNullException(nameof(Header), "Заголовок не может быть null или пустым.");
if (Data == null || !Data.Any())
throw new ArgumentNullException(nameof(Data), "Данные не могут быть null или пустыми.");
}
}
}

View File

@ -0,0 +1,17 @@
namespace COP_5.PdfHelper
{
public class ImagePdfInfo
{
public string FilePath { get; set; }
public string Header { get; set; }
public List<byte[]> Images { get; set; }
public void CheckFields()
{
if (string.IsNullOrWhiteSpace(FilePath) || string.IsNullOrWhiteSpace(Header) || Images == null || Images.Count == 0)
{
throw new ArgumentException("Все поля должны быть заполнены.");
}
}
}
}

View File

@ -0,0 +1,10 @@
namespace COP_5.PdfHelper
{
public enum PdfParagraphAlignmentType
{
Left,
Right,
Top,
Bottom
}
}

View File

@ -0,0 +1,50 @@
namespace COP_5.PdfHelper
{
public class TablePdfInfo<T>
{
public string FileName { get; set; }
public string Title { get; set; }
public List<double> RowHeights { get; set; }
public Dictionary<string, List<(string Name, string Value)>> Headers { get; set; }
//public List<string> PropertiesPerRow { get; set; }
public List<T> Data { get; set; }
public void CheckFields()
{
if (string.IsNullOrWhiteSpace(FileName))
throw new ArgumentException("Имя файла не может быть пустым.", nameof(FileName));
if (string.IsNullOrWhiteSpace(Title))
throw new ArgumentException("Название документа не может быть пустым.", nameof(Title));
if (Headers == null || Headers.Count == 0)
throw new ArgumentException("Заголовки для шапки не могут быть пустыми.", nameof(Headers));
if (Data == null || Data.Count == 0)
throw new ArgumentException("Данные для таблицы не могут быть пустыми.", nameof(Data));
if (RowHeights == null || RowHeights.Count == 0)
throw new ArgumentException("Высоты строк не могут быть пустыми.", nameof(RowHeights));
/*if (PropertiesPerRow.Any(string.IsNullOrWhiteSpace))
throw new ArgumentException("Список названий свойств не может содержать пустые строки.", nameof(PropertiesPerRow));
if (RowHeights.Count != PropertiesPerRow.Count)
throw new ArgumentException("Количество высот строк должно соответствовать количеству названий свойств.", nameof(RowHeights));
if (Data.Count != PropertiesPerRow.Count)
throw new ArgumentException("Количество данных должно соответствовать количеству названий свойств.", nameof(Data));*/
foreach (var kvp in Headers)
{
if (string.IsNullOrWhiteSpace(kvp.Key))
throw new ArgumentException("Ключ в данных не может быть пустым или содержать только пробелы.", nameof(Data));
foreach (var item in kvp.Value)
{
if (string.IsNullOrWhiteSpace(item.Name))
throw new ArgumentException("Имя в данных не может быть пустым или содержать только пробелы.", nameof(Data));
}
}
}
}
}

58
COP_5/COP_5/RangeTextBox.Designer.cs generated Normal file
View File

@ -0,0 +1,58 @@
namespace COP_5
{
partial class RangeTextBox
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
textBox = new TextBox();
SuspendLayout();
//
// textBox
//
textBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
textBox.Location = new Point(3, 3);
textBox.Name = "textBox";
textBox.Size = new Size(246, 23);
textBox.TabIndex = 0;
textBox.TextChanged += textBox_TextChanged;
//
// RangeTextBox
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(textBox);
Name = "RangeTextBox";
Size = new Size(252, 33);
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBox;
}
}

View File

@ -0,0 +1,84 @@
using COP_5.Exceptions;
using System;
namespace COP_5
{
public partial class RangeTextBox : UserControl
{
public int? max = 0;
public int? min = 0;
public int? MinLength
{
get
{
return max;
}
set
{
if (value == null || value <= 0) return;
max = value;
}
}
public int? MaxLength
{
get
{
return min;
}
set
{
if (value == null || value < 0) return;
min = value;
}
}
public event EventHandler? ChangedValue;
public string? TextBoxValue
{
get
{
if (MinLength == null && MaxLength == null)
{
throw new RangeException("Диапазон не задан.");
}
if (textBox.Text.Length < MinLength || textBox.Text.Length > MaxLength)
{
throw new RangeException("Введенное значение не входит в диапазон.");
}
return textBox.Text;
}
set
{
if (MinLength != null && MaxLength != null)
{
if (value.Length >= MinLength && value.Length <= MaxLength)
{
textBox.Text = value;
}
}
}
}
public RangeTextBox()
{
InitializeComponent();
}
private void textBox_TextChanged(object sender, EventArgs e)
{
ChangedValue?.Invoke(this, e);
if (MinLength != null && MaxLength != null)
{
if (textBox.Text.Length < MinLength || textBox.Text.Length > MaxLength)
{
textBox.ForeColor = System.Drawing.Color.Red;
}
else
{
textBox.ForeColor = System.Drawing.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,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace COP_5.TestClasses
{
public class Employee
{
public string? Department { get; set; }
public string? Post { get; set; }
public string? Name { get; set; }
public Employee() { }
public Employee(string department, string post, string name)
{
Department = department;
Post = post;
Name = name;
}
}
}

View File

@ -0,0 +1,16 @@
namespace COP_5.TestClasses
{
public class Human
{
public string Name { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public Human() { }
public Human(string name, string surname, int age)
{
Name = name;
Surname = surname;
Age = age;
}
}
}

56
COP_5/COP_5/TreeView.Designer.cs generated Normal file
View File

@ -0,0 +1,56 @@
namespace COP_5
{
partial class TreeView
{
/// <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 System.Windows.Forms.TreeView();
SuspendLayout();
//
// treeView1
//
treeView1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
treeView1.Location = new Point(3, 3);
treeView1.Name = "treeView1";
treeView1.Size = new Size(258, 257);
treeView1.TabIndex = 0;
//
// TreeView
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(treeView1);
Name = "TreeView";
Size = new Size(264, 263);
ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TreeView treeView1;
}
}

103
COP_5/COP_5/TreeView.cs Normal file
View File

@ -0,0 +1,103 @@
using COP_5.Exceptions;
using COP_5.TestClasses;
namespace COP_5
{
public partial class TreeView : UserControl
{
private List<string> hierarchy;
private Dictionary<string, bool> newBranch;
public TreeView()
{
InitializeComponent();
hierarchy = new List<string>();
newBranch = new Dictionary<string, bool>();
}
public void SetHierarchy(List<string> hierarchy, Dictionary<string, bool> newBranch)
{
this.hierarchy = hierarchy;
this.newBranch = newBranch;
}
public void Clear()
{
treeView1.Nodes.Clear();
}
public void AddObjectToTree<T>(T obj, string stopAtProperty)
{
//TreeNode currentNode = treeView1.Nodes.Cast<TreeNode>().FirstOrDefault();
TreeNode currentNode = null;
foreach (var property in hierarchy)
{
var value = obj.GetType().GetProperty(property).GetValue(obj, null).ToString();
bool createNewBranch = newBranch.ContainsKey(property) && newBranch[property];
if (currentNode == null)
{
//currentNode = treeView1.Nodes.Add(value);
currentNode = treeView1.Nodes.Cast<TreeNode>().FirstOrDefault(n => n.Text == value);
if (currentNode == null || createNewBranch)
{
currentNode = treeView1.Nodes.Add(value);
}
}
else
{
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 TreeViewException("Узел равен null");
}
if (treeView1.SelectedNode.Nodes.Count > 0)
{
throw new TreeViewException("Невозможно получить объект из этого узла");
}
var node = treeView1.SelectedNode;
var obj = new T();
var properties = new Stack<string>(hierarchy);
while (node != null && properties.Count > 0)
{
var property = properties.Pop();
var value = node.Text;
obj.GetType().GetProperty(property).SetValue(obj, value);
node = node.Parent;
}
return obj;
}
}
}

120
COP_5/COP_5/TreeView.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>

View File

@ -0,0 +1,87 @@
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts;
using LibraryAccountingApp_lab3.Contracts.SearchModels;
using LibraryAccountingApp_lab3.Contracts.StorageContracts;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
namespace LibraryAccountingApp_lab3.BusinessLogic
{
public class AuthorLogic : IAuthorLogic
{
private readonly IAuthorStorage _authorStorage;
public AuthorLogic(IAuthorStorage authorStorage)
{
_authorStorage = authorStorage;
}
public List<AuthorViewModel>? ReadList(AuthorSearchModel? model)
{
var list = model == null ? _authorStorage.GetFullList() : _authorStorage.GetFilteredList(model);
if (list == null)
{
return null;
}
return list;
}
public AuthorViewModel? ReadElement(AuthorSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
var element = _authorStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public bool Create(AuthorBindingModel model)
{
CheckModel(model);
if (_authorStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Update(AuthorBindingModel model)
{
CheckModel(model);
if (_authorStorage.Update(model) == null)
{
return false;
}
return true;
}
public bool Delete(AuthorBindingModel model)
{
CheckModel(model, false);
if (_authorStorage.Delete(model) == null)
{
return false;
}
return true;
}
private void CheckModel(AuthorBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Нет автора", nameof(model.Name));
}
}
}
}

View File

@ -0,0 +1,90 @@
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts;
using LibraryAccountingApp_lab3.Contracts.SearchModels;
using LibraryAccountingApp_lab3.Contracts.StorageContracts;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
namespace LibraryAccountingApp_lab3.BusinessLogic
{
public class BookLogic : IBookLogic
{
private readonly IBookStorage _bookStorage;
public BookLogic(IBookStorage bookStorage)
{
_bookStorage = bookStorage;
}
public List<BookViewModel>? ReadList(BookSearchModel? model)
{
var list = model == null ? _bookStorage.GetFullList() : _bookStorage.GetFilteredList(model);
if (list == null)
{
return null;
}
return list;
}
public BookViewModel? ReadElement(BookSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
var element = _bookStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public bool Create(BookBindingModel model)
{
CheckModel(model);
if (_bookStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Update(BookBindingModel model)
{
CheckModel(model);
if (_bookStorage.Update(model) == null)
{
return false;
}
return true;
}
public bool Delete(BookBindingModel model)
{
CheckModel(model, false);
if (_bookStorage.Delete(model) == null)
{
return false;
}
return true;
}
private void CheckModel(BookBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Title))
{
throw new ArgumentNullException("Нет названия книги", nameof(model.Title));
}
if (string.IsNullOrEmpty(model.Date))
{
throw new ArgumentNullException("Нет даты", nameof(model.Date));
}
}
}
}

View File

@ -0,0 +1,10 @@
using LibraryAccountingApp_lab3.DataModels;
namespace LibraryAccountingApp_lab3.Contracts.BindingModels
{
public class AuthorBindingModel : IAuthorModel
{
public int Id { get; set; }
public string Name { get; set; } = String.Empty;
}
}

View File

@ -0,0 +1,16 @@
using LibraryAccountingApp_lab3.DataModels;
namespace LibraryAccountingApp_lab3.Contracts.BindingModels
{
public class BookBindingModel : IBookModel
{
public int Id { get; set; }
public string Title { get; set; }
public int AuthorId { get; set; }
public string Date { get; set; }
public byte[] Image { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.SearchModels;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
namespace LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts
{
public interface IAuthorLogic
{
List<AuthorViewModel>? ReadList(AuthorSearchModel? model);
AuthorViewModel? ReadElement(AuthorSearchModel model);
bool Create(AuthorBindingModel model);
bool Update(AuthorBindingModel model);
bool Delete(AuthorBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.SearchModels;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
namespace LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts
{
public interface IBookLogic
{
List<BookViewModel>? ReadList(BookSearchModel? model);
BookViewModel? ReadElement(BookSearchModel model);
bool Create(BookBindingModel model);
bool Update(BookBindingModel model);
bool Delete(BookBindingModel model);
}
}

View File

@ -0,0 +1,7 @@
namespace LibraryAccountingApp_lab3.Contracts.SearchModels
{
public class AuthorSearchModel
{
public int? Id { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace LibraryAccountingApp_lab3.Contracts.SearchModels
{
public class BookSearchModel
{
public int? Id { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.SearchModels;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
namespace LibraryAccountingApp_lab3.Contracts.StorageContracts
{
public interface IAuthorStorage
{
List<AuthorViewModel> GetFullList();
List<AuthorViewModel> GetFilteredList(AuthorSearchModel model);
AuthorViewModel? GetElement(AuthorSearchModel model);
AuthorViewModel? Insert(AuthorBindingModel model);
AuthorViewModel? Update(AuthorBindingModel model);
AuthorViewModel? Delete(AuthorBindingModel model);
}
}

View File

@ -0,0 +1,16 @@
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.SearchModels;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
namespace LibraryAccountingApp_lab3.Contracts.StorageContracts
{
public interface IBookStorage
{
List<BookViewModel> GetFullList();
List<BookViewModel> GetFilteredList(BookSearchModel model);
BookViewModel? GetElement(BookSearchModel model);
BookViewModel? Insert(BookBindingModel model);
BookViewModel? Update(BookBindingModel model);
BookViewModel? Delete(BookBindingModel model);
}
}

View File

@ -0,0 +1,14 @@
using LibraryAccountingApp_lab3.DataModels;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace LibraryAccountingApp_lab3.Contracts.ViewModels
{
public class AuthorViewModel : IAuthorModel
{
public int Id { get; set; }
[DisplayName("Имя")]
public string Name { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,23 @@
using LibraryAccountingApp_lab3.DataModels;
using System.ComponentModel;
namespace LibraryAccountingApp_lab3.Contracts.ViewModels
{
public class BookViewModel : IBookModel
{
[DisplayName("Id")]
public int Id { get; set; }
[DisplayName("Название")]
public string Title { get; set; } = string.Empty;
public int AuthorId { get; set; }
[DisplayName("Автор")]
public string AuthorName { get; set; } = string.Empty;
[DisplayName("Дата издания")]
public string Date { get; set; } = string.Empty;
[DisplayName("Обложка")]
public byte[] Image { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace LibraryAccountingApp_lab3.DataModels
{
public interface IAuthorModel : IId
{
string Name { get; set; }
}
}

View File

@ -0,0 +1,10 @@
namespace LibraryAccountingApp_lab3.DataModels
{
public interface IBookModel : IId
{
string Title { get; }
public int AuthorId { get; }
string Date { get; }
public byte[] Image { get; }
}
}

View File

@ -0,0 +1,7 @@
namespace LibraryAccountingApp_lab3.DataModels
{
public interface IId
{
int Id { get; }
}
}

View File

@ -0,0 +1,83 @@
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.SearchModels;
using LibraryAccountingApp_lab3.Contracts.StorageContracts;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
using LibraryAccountingApp_lab3.DatabaseImplement.Models;
namespace LibraryAccountingApp_lab3.DatabaseImplement.Implements
{
public class AuthorStorage : IAuthorStorage
{
public List<AuthorViewModel> GetFullList()
{
using var context = new LibraryDatabase();
return context.Authors
.Select(x => x.GetViewModel)
.ToList();
}
public List<AuthorViewModel> GetFilteredList(AuthorSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new LibraryDatabase();
return context.Authors
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
public AuthorViewModel? GetElement(AuthorSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new LibraryDatabase();
return context.Authors
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public AuthorViewModel? Insert(AuthorBindingModel model)
{
var newAuthor = Author.Create(model);
if (newAuthor == null)
{
return null;
}
using var context = new LibraryDatabase();
context.Authors.Add(newAuthor);
context.SaveChanges();
return newAuthor.GetViewModel;
}
public AuthorViewModel? Update(AuthorBindingModel model)
{
using var context = new LibraryDatabase();
var component = context.Authors.FirstOrDefault(x => x.Id == model.Id);
if (component == null)
{
return null;
}
component.Update(model);
context.SaveChanges();
return component.GetViewModel;
}
public AuthorViewModel? Delete(AuthorBindingModel model)
{
using var context = new LibraryDatabase();
var element = context.Authors.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Authors.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,94 @@
using DocumentFormat.OpenXml.Bibliography;
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.SearchModels;
using LibraryAccountingApp_lab3.Contracts.StorageContracts;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
using LibraryAccountingApp_lab3.DatabaseImplement.Models;
using Microsoft.EntityFrameworkCore;
namespace LibraryAccountingApp_lab3.DatabaseImplement.Implements
{
public class BookStorage : IBookStorage
{
public List<BookViewModel> GetFullList()
{
using (var context = new LibraryDatabase())
{
return context.Books
.Include(x => x.Author)
.Select(x => x.GetViewModel)
.ToList();
}
}
public List<BookViewModel> GetFilteredList(BookSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
var context = new LibraryDatabase();
return context.Books
.Include(x => x.Author)
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
public BookViewModel? GetElement(BookSearchModel model)
{
if (!model.Id.HasValue)
{
return null;
}
using var context = new LibraryDatabase();
return context.Books
.Include(x => x.Author)
.FirstOrDefault(x => x.Id == model.Id)
?.GetViewModel;
}
public BookViewModel? Insert(BookBindingModel model)
{
using var context = new LibraryDatabase();
var newBook = Book.Create(context, model);
if (newBook == null)
{
return null;
}
context.Books.Add(newBook);
context.SaveChanges();
return newBook.GetViewModel;
}
public BookViewModel? Update(BookBindingModel model)
{
using var context = new LibraryDatabase();
var book = context.Books.FirstOrDefault(x => x.Id == model.Id);
if (book == null)
{
return null;
}
book.Update(model, context);
context.SaveChanges();
return book.GetViewModel;
}
public BookViewModel? Delete(BookBindingModel model)
{
using var context = new LibraryDatabase();
var element = context.Books
.Include (x => x.Author)
.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Books.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,21 @@
using Microsoft.EntityFrameworkCore;
using LibraryAccountingApp_lab3.DatabaseImplement.Models;
namespace LibraryAccountingApp_lab3.DatabaseImplement
{
public class LibraryDatabase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=PC-Anna\SQLEXPRESS;Initial Catalog=LibraryAppCOP5;Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
//optionsBuilder.UseNpgsql("Host=localhost;Database=LibraryAppCOP;Username=postgres;Password=postgres");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Book> Books { set; get; }
public virtual DbSet<Author> Authors{ set; get; }
}
}

View File

@ -0,0 +1,48 @@
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
using LibraryAccountingApp_lab3.DataModels;
using System.ComponentModel.DataAnnotations;
namespace LibraryAccountingApp_lab3.DatabaseImplement.Models
{
public class Author : IAuthorModel
{
public int Id { get; private set; }
[Required]
public string Name { get; set; } = string.Empty;
public static Author? Create(AuthorBindingModel? model)
{
if (model == null)
{
return null;
}
return new Author()
{
Id = model.Id,
Name = model.Name,
};
}
public static Author? Create(AuthorViewModel? model)
{
return new Author()
{
Id = model.Id,
Name = model.Name,
};
}
public void Update(AuthorBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
}
public AuthorViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
};
}
}

View File

@ -0,0 +1,63 @@
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
using LibraryAccountingApp_lab3.DataModels;
using System.ComponentModel.DataAnnotations;
namespace LibraryAccountingApp_lab3.DatabaseImplement.Models
{
public class Book : IBookModel
{
public int Id { get; private set; }
[Required]
public string Title { get; set; } = string.Empty;
public int AuthorId { get; set; }
public virtual Author Author { get; set; } = new();
[Required]
public string Date { get; set; } = string.Empty;
[Required]
public byte[] Image { get; set; }
public static Book? Create(LibraryDatabase context, BookBindingModel? model)
{
if (model == null)
{
return null;
}
return new Book()
{
Id = model.Id,
Title = model.Title,
Date = model.Date,
AuthorId = model.AuthorId,
Author = context.Authors.First(x => x.Id == model.AuthorId),
Image = model.Image,
};
}
public void Update(BookBindingModel? model, LibraryDatabase context)
{
if (model == null)
{
return;
}
Title = model.Title;
AuthorId = model.AuthorId;
Date = model.Date;
Author = context.Authors.First(x => x.Id == model.AuthorId);
Image = model.Image;
}
public BookViewModel GetViewModel => new()
{
Id = Id,
Title = Title,
Date = Date,
AuthorId = AuthorId,
AuthorName = Author.Name,
Image = Image,
};
}
}

View File

@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations;
namespace LibraryAccountingApp_lab3.DatabaseImplement.Models
{
public class BookForExcel
{
public int? Id { get; set; }
[Required]
public string Title { get; set; }
public string AuthorName { get; set; }
[Required]
public string Date { get; set; }
}
}

View File

@ -0,0 +1,89 @@
namespace LibraryAccountingApp_lab3
{
partial class FormAuthor
{
/// <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();
NameCol = new DataGridViewTextBoxColumn();
Id = new DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { NameCol, Id });
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.Margin = new Padding(3, 2, 3, 2);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(625, 357);
dataGridView.TabIndex = 0;
dataGridView.CellValueChanged += dataGridView_CellValueChanged;
dataGridView.UserDeletingRow += dataGridView_UserDeletingRow;
dataGridView.KeyUp += dataGridView_KeyUp;
//
// NameCol
//
NameCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
NameCol.HeaderText = "Имя";
NameCol.MinimumWidth = 6;
NameCol.Name = "NameCol";
//
// Id
//
Id.HeaderText = "Id";
Id.MinimumWidth = 6;
Id.Name = "Id";
Id.Visible = false;
Id.Width = 125;
//
// FormAuthor
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
BackColor = Color.White;
ClientSize = new Size(536, 228);
Controls.Add(dataGridView);
Margin = new Padding(3, 2, 3, 2);
Name = "FormAuthor";
Text = "Авторы";
Load += FormAuthor_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private DataGridViewTextBoxColumn NameCol;
private DataGridViewTextBoxColumn Id;
}
}

View File

@ -0,0 +1,97 @@
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts;
using LibraryAccountingApp_lab3.Contracts.StorageContracts;
namespace LibraryAccountingApp_lab3
{
public partial class FormAuthor : Form
{
private readonly IAuthorLogic _logic;
private readonly IAuthorStorage _storage;
private bool loading = false;
public FormAuthor(IAuthorLogic logic, IAuthorStorage storage)
{
InitializeComponent();
_logic = logic;
_storage = storage;
}
private void FormAuthor_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
loading = true;
try
{
var list = _logic.ReadList(null);
if (list != null)
{
foreach (var interest in list)
{
int rowIndex = dataGridView.Rows.Add();
dataGridView.Rows[rowIndex].Cells[0].Value = interest.Name;
dataGridView.Rows[rowIndex].Cells[1].Value = interest.Id;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
loading = false;
}
}
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (loading || e.RowIndex < 0 || e.ColumnIndex != 0) return;
if (dataGridView.Rows[e.RowIndex].Cells[1].Value != null && !string.IsNullOrEmpty(dataGridView.Rows[e.RowIndex].Cells[1].Value.ToString()))
{
var name = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (name is null) return;
_logic.Update(new AuthorBindingModel { Id = Convert.ToInt32(dataGridView.Rows[e.RowIndex].Cells[1].Value), Name = name.ToString() });
}
else
{
var name = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (name is null) return;
_logic.Create(new AuthorBindingModel { Id = 0, Name = name.ToString() });
int newCategoryId = _logic.ReadList(null).ToList().Last().Id;
dataGridView.Rows[e.RowIndex].Cells[1].Value = newCategoryId;
}
}
private void dataGridView_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Insert:
dataGridView.Rows.Add();
break;
}
}
private void deleteRows(DataGridViewSelectedRowCollection rows)
{
for (int i = 0; i < rows.Count; i++)
{
DataGridViewRow row = rows[i];
if (!_logic.Delete(new AuthorBindingModel { Id = Convert.ToInt32(row.Cells[1].Value) })) continue;
dataGridView.Rows.Remove(row);
}
}
private void dataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
e.Cancel = true;
if (dataGridView.SelectedRows == null) return;
if (MessageBox.Show("Удалить записи?", "Подтвердите действие", MessageBoxButtons.YesNo) == DialogResult.No) return;
deleteRows(dataGridView.SelectedRows);
}
}
}

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,169 @@
namespace LibraryAccountingApp_lab3
{
partial class FormBook
{
/// <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()
{
textBoxTitle = new TextBox();
buttonBookAdd = new Button();
buttonClearImage = new Button();
textBoxImage = new TextBox();
label2 = new Label();
controlSelectedComboBoxSingleAuthor = new ControlsLibraryNet60.Selected.ControlSelectedComboBoxSingle();
dateTextBoxDate = new FedComponentLib.DateTextBox();
label1 = new Label();
buttonChooseImage = new Button();
SuspendLayout();
//
// textBoxTitle
//
textBoxTitle.Anchor = AnchorStyles.Left | AnchorStyles.Right;
textBoxTitle.Location = new Point(18, 38);
textBoxTitle.Name = "textBoxTitle";
textBoxTitle.Size = new Size(243, 23);
textBoxTitle.TabIndex = 27;
//
// buttonBookAdd
//
buttonBookAdd.Anchor = AnchorStyles.Left | AnchorStyles.Right;
buttonBookAdd.BackColor = Color.YellowGreen;
buttonBookAdd.Location = new Point(31, 389);
buttonBookAdd.Name = "buttonBookAdd";
buttonBookAdd.Size = new Size(231, 36);
buttonBookAdd.TabIndex = 28;
buttonBookAdd.Text = "Сохранить книгу";
buttonBookAdd.UseVisualStyleBackColor = false;
buttonBookAdd.Click += buttonBookAdd_Click;
//
// buttonClearImage
//
buttonClearImage.Anchor = AnchorStyles.Left | AnchorStyles.Right;
buttonClearImage.BackColor = Color.Silver;
buttonClearImage.Font = new Font("Segoe UI", 7F, FontStyle.Regular, GraphicsUnit.Point);
buttonClearImage.Location = new Point(151, 323);
buttonClearImage.Name = "buttonClearImage";
buttonClearImage.Size = new Size(127, 27);
buttonClearImage.TabIndex = 29;
buttonClearImage.Text = "Очистить";
buttonClearImage.UseVisualStyleBackColor = false;
buttonClearImage.Click += buttonClearImage_Click;
//
// textBoxImage
//
textBoxImage.Anchor = AnchorStyles.Left | AnchorStyles.Right;
textBoxImage.Location = new Point(18, 294);
textBoxImage.Name = "textBoxImage";
textBoxImage.ReadOnly = true;
textBoxImage.Size = new Size(243, 23);
textBoxImage.TabIndex = 34;
//
// label2
//
label2.Anchor = AnchorStyles.Left | AnchorStyles.Right;
label2.AutoSize = true;
label2.Location = new Point(18, 162);
label2.Name = "label2";
label2.Size = new Size(43, 15);
label2.TabIndex = 33;
label2.Text = "Автор:";
//
// controlSelectedComboBoxSingleAuthor
//
controlSelectedComboBoxSingleAuthor.Anchor = AnchorStyles.Left | AnchorStyles.Right;
controlSelectedComboBoxSingleAuthor.Location = new Point(18, 180);
controlSelectedComboBoxSingleAuthor.Margin = new Padding(5, 3, 5, 3);
controlSelectedComboBoxSingleAuthor.Name = "controlSelectedComboBoxSingleAuthor";
controlSelectedComboBoxSingleAuthor.SelectedElement = "";
controlSelectedComboBoxSingleAuthor.Size = new Size(243, 28);
controlSelectedComboBoxSingleAuthor.TabIndex = 30;
//
// dateTextBoxDate
//
dateTextBoxDate.Anchor = AnchorStyles.Left | AnchorStyles.Right;
dateTextBoxDate.DatePattern = null;
dateTextBoxDate.Location = new Point(18, 78);
dateTextBoxDate.Margin = new Padding(3, 4, 3, 4);
dateTextBoxDate.Name = "dateTextBoxDate";
dateTextBoxDate.Size = new Size(243, 57);
dateTextBoxDate.TabIndex = 32;
//
// label1
//
label1.Anchor = AnchorStyles.Left | AnchorStyles.Right;
label1.AutoSize = true;
label1.Location = new Point(18, 20);
label1.Name = "label1";
label1.Size = new Size(62, 15);
label1.TabIndex = 31;
label1.Text = "Название:";
//
// buttonChooseImage
//
buttonChooseImage.Anchor = AnchorStyles.Left | AnchorStyles.Right;
buttonChooseImage.Location = new Point(64, 264);
buttonChooseImage.Margin = new Padding(3, 2, 3, 2);
buttonChooseImage.Name = "buttonChooseImage";
buttonChooseImage.Size = new Size(176, 24);
buttonChooseImage.TabIndex = 26;
buttonChooseImage.Text = "Выбрать обложку";
buttonChooseImage.UseVisualStyleBackColor = true;
buttonChooseImage.Click += buttonChooseImage_Click;
//
// FormBook
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(290, 467);
Controls.Add(textBoxTitle);
Controls.Add(buttonBookAdd);
Controls.Add(buttonClearImage);
Controls.Add(textBoxImage);
Controls.Add(label2);
Controls.Add(controlSelectedComboBoxSingleAuthor);
Controls.Add(dateTextBoxDate);
Controls.Add(label1);
Controls.Add(buttonChooseImage);
Margin = new Padding(3, 2, 3, 2);
Name = "FormBook";
Text = "Книги";
Load += FormBook_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBoxTitle;
private Button buttonBookAdd;
private Button buttonClearImage;
private TextBox textBoxImage;
private Label label2;
private ControlsLibraryNet60.Selected.ControlSelectedComboBoxSingle controlSelectedComboBoxSingleAuthor;
private FedComponentLib.DateTextBox dateTextBoxDate;
private Label label1;
private Button buttonChooseImage;
}
}

View File

@ -0,0 +1,149 @@
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts;
using LibraryAccountingApp_lab3.Contracts.SearchModels;
using LibraryAccountingApp_lab3.Contracts.StorageContracts;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
namespace LibraryAccountingApp_lab3
{
public partial class FormBook : Form
{
private byte[]? selectedImage = new byte[16];
private readonly IBookLogic _bookLogic;
private readonly IAuthorLogic _authorLogic;
public readonly IBookStorage _bookStorage;
private List<AuthorViewModel> _authors;
private int? _id;
public int Id { set { _id = value; } }
public FormBook(IBookLogic bookLogic, IAuthorLogic authorLogic)
{
InitializeComponent();
_bookLogic = bookLogic;
_authorLogic = authorLogic;
_authors = new List<AuthorViewModel>();
FillControlSelectedComboBoxSingle();
dateTextBoxDate.DatePattern = @"^(0[1-9]|[12][0-9]|3[01])\s+(январь|февраль|март|апрель|май|июнь|июль|август|сентябрь|октябрь|ноябрь|декабрь)\s+\d{4}$";
}
private void FormBook_Load(object sender, EventArgs e)
{
_authors = _authorLogic.ReadList(null);
if (_id.HasValue)
{
try
{
var view = _bookLogic.ReadElement(new BookSearchModel { Id = _id.Value });
if (view != null)
{
textBoxTitle.Text = view.Title;
dateTextBoxDate.TextBoxValue = view.Date;
textBoxImage.Text = "Обложка выбрана";
selectedImage = view.Image;
controlSelectedComboBoxSingleAuthor.SelectedElement = view.AuthorName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void FillControlSelectedComboBoxSingle()
{
controlSelectedComboBoxSingleAuthor.Clear();
try
{
var list = _authorLogic.ReadList(null);
if (list != null)
{
foreach (var author in list)
{
controlSelectedComboBoxSingleAuthor.AddElement(author.Name);
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка загрузки данных: {ex.Message}");
}
}
private void buttonBookAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxTitle.Text))
MessageBox.Show("Введите название!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
try
{
if (string.IsNullOrEmpty(dateTextBoxDate.TextBoxValue))
MessageBox.Show("Введите дату издания!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if (string.IsNullOrEmpty(controlSelectedComboBoxSingleAuthor.SelectedElement))
MessageBox.Show("Выберите автора!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
if (string.IsNullOrEmpty(textBoxImage.Text))
MessageBox.Show("Выберите обложку!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
try
{
var model = new BookBindingModel
{
Id = _id ?? 0,
Title = textBoxTitle.Text,
Date = dateTextBoxDate.TextBoxValue,
AuthorId = _authors.First(x => x.Name == controlSelectedComboBoxSingleAuthor.SelectedElement).Id,
Image = selectedImage,
};
var operationResult = _id.HasValue ? _bookLogic.Update(model) : _bookLogic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch
{
MessageBox.Show("Ошибка при добавлении!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonChooseImage_Click(object sender, EventArgs e)
{
using OpenFileDialog openFileDialog = new OpenFileDialog
{
Multiselect = true,
Filter = "Изображения|*.jpg;*.jpeg;*.png;*.bmp"
};
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
ClearImage();
foreach (string filePath in openFileDialog.FileNames)
{
selectedImage = File.ReadAllBytes(filePath);
textBoxImage.Text = Path.GetFileName(filePath);
}
}
}
private void ClearImage()
{
selectedImage = null;
textBoxImage.Clear();
}
private void buttonClearImage_Click(object sender, EventArgs e)
{
ClearImage();
}
}
}

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,167 @@
namespace LibraryAccountingApp_lab3
{
partial class FormLibrary
{
/// <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();
pdfForImages = new COP_5.PdfForImages(components);
componentDocumentWithChartBarWord = new ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord(components);
tableComponent = new FedComponentLib.NonVisualComponents.TableComponent(components);
менюToolStripMenuItem = new ToolStripMenuItem();
авторыToolStripMenuItem = new ToolStripMenuItem();
книгиToolStripMenuItem = new ToolStripMenuItem();
отчетыToolStripMenuItem = new ToolStripMenuItem();
pDFСОбложкамиToolStripMenuItem = new ToolStripMenuItem();
excelПоВсемКнигамToolStripMenuItem = new ToolStripMenuItem();
гистограммаВWordToolStripMenuItem = new ToolStripMenuItem();
menuStrip1 = new MenuStrip();
удалитьToolStripMenuItem = new ToolStripMenuItem();
controlDataTableCellBooks = new ControlsLibraryNet60.Data.ControlDataTableCell();
редактироватьToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// менюToolStripMenuItem
//
менюToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { авторыToolStripMenuItem, книгиToolStripMenuItem });
менюToolStripMenuItem.Name = енюToolStripMenuItem";
менюToolStripMenuItem.Size = new Size(86, 20);
менюToolStripMenuItem.Text = "Добавление";
//
// авторыToolStripMenuItem
//
авторыToolStripMenuItem.Name = "авторыToolStripMenuItem";
авторыToolStripMenuItem.Size = new Size(116, 22);
авторыToolStripMenuItem.Text = "Авторы";
авторыToolStripMenuItem.Click += авторыToolStripMenuItem_Click;
//
// книгиToolStripMenuItem
//
книгиToolStripMenuItem.Name = "книгиToolStripMenuItem";
книгиToolStripMenuItem.Size = new Size(116, 22);
книгиToolStripMenuItem.Text = "Книги";
книгиToolStripMenuItem.Click += книгиToolStripMenuItem_Click;
//
// отчетыToolStripMenuItem
//
отчетыToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { pDFСОбложкамиToolStripMenuItem, excelПоВсемКнигамToolStripMenuItem, гистограммаВWordToolStripMenuItem });
отчетыToolStripMenuItem.Name = "отчетыToolStripMenuItem";
отчетыToolStripMenuItem.Size = new Size(60, 20);
отчетыToolStripMenuItem.Text = "Отчеты";
//
// pDFСОбложкамиToolStripMenuItem
//
pDFСОбложкамиToolStripMenuItem.Name = "pDFСОбложкамиToolStripMenuItem";
pDFСОбложкамиToolStripMenuItem.Size = new Size(194, 22);
pDFСОбложкамиToolStripMenuItem.Text = "PDF с обложками";
pDFСОбложкамиToolStripMenuItem.Click += pDFСОбложкамиToolStripMenuItem_Click;
//
// excelПоВсемКнигамToolStripMenuItem
//
excelПоВсемКнигамToolStripMenuItem.Name = "excelПоВсемКнигамToolStripMenuItem";
excelПоВсемКнигамToolStripMenuItem.Size = new Size(194, 22);
excelПоВсемКнигамToolStripMenuItem.Text = "Excel по всем книгам ";
excelПоВсемКнигамToolStripMenuItem.Click += excelПоВсемКнигамToolStripMenuItem_Click;
//
// гистограммаВWordToolStripMenuItem
//
гистограммаВWordToolStripMenuItem.Name = "гистограммаВWordToolStripMenuItem";
гистограммаВWordToolStripMenuItem.Size = new Size(194, 22);
гистограммаВWordToolStripMenuItem.Text = "Гистограмма в Word";
гистограммаВWordToolStripMenuItem.Click += гистограммаВWordToolStripMenuItem_Click;
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { менюToolStripMenuItem, отчетыToolStripMenuItem, удалитьToolStripMenuItem, редактироватьToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Padding = new Padding(5, 2, 0, 2);
menuStrip1.Size = new Size(609, 24);
menuStrip1.TabIndex = 26;
menuStrip1.Text = "menuStrip1";
//
// удалитьToolStripMenuItem
//
удалитьToolStripMenuItem.Name = "удалитьToolStripMenuItem";
удалитьToolStripMenuItem.Size = new Size(63, 20);
удалитьToolStripMenuItem.Text = "Удалить";
удалитьToolStripMenuItem.Click += удалитьToolStripMenuItem_Click;
//
// controlDataTableCellBooks
//
controlDataTableCellBooks.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
controlDataTableCellBooks.AutoSize = true;
controlDataTableCellBooks.Location = new Point(12, 34);
controlDataTableCellBooks.Margin = new Padding(4, 3, 4, 3);
controlDataTableCellBooks.Name = "controlDataTableCellBooks";
controlDataTableCellBooks.SelectedRowIndex = -1;
controlDataTableCellBooks.Size = new Size(578, 328);
controlDataTableCellBooks.TabIndex = 0;
//
// редактироватьToolStripMenuItem
//
редактироватьToolStripMenuItem.Name = "редактироватьToolStripMenuItem";
редактироватьToolStripMenuItem.Size = new Size(99, 20);
редактироватьToolStripMenuItem.Text = "Редактировать";
редактироватьToolStripMenuItem.Click += редактироватьToolStripMenuItem_Click;
//
// FormLibrary
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(609, 373);
Controls.Add(controlDataTableCellBooks);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormLibrary";
Text = "Библиотека";
Load += FormLibrary_Load;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private COP_5.PdfForImages pdfForImages;
private ComponentsLibraryNet60.DocumentWithChart.ComponentDocumentWithChartBarWord componentDocumentWithChartBarWord;
private FedComponentLib.NonVisualComponents.TableComponent tableComponent;
private ToolStripMenuItem менюToolStripMenuItem;
private ToolStripMenuItem авторыToolStripMenuItem;
private ToolStripMenuItem книгиToolStripMenuItem;
private ToolStripMenuItem отчетыToolStripMenuItem;
private ToolStripMenuItem pDFСОбложкамиToolStripMenuItem;
private ToolStripMenuItem excelПоВсемКнигамToolStripMenuItem;
private ToolStripMenuItem гистограммаВWordToolStripMenuItem;
private MenuStrip menuStrip1;
private ControlsLibraryNet60.Data.ControlDataTableCell controlDataTableCellBooks;
private ToolStripMenuItem удалитьToolStripMenuItem;
private ToolStripMenuItem редактироватьToolStripMenuItem;
}
}

View File

@ -0,0 +1,391 @@
using ComponentsLibraryNet60.Models;
using ControlsLibraryNet60.Core;
using ControlsLibraryNet60.Models;
using COP_5.PdfHelper;
using FedComponentLib.NonVisualComponents.HelperModels;
using LibraryAccountingApp_lab3.Contracts.BindingModels;
using LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts;
using LibraryAccountingApp_lab3.Contracts.SearchModels;
using LibraryAccountingApp_lab3.Contracts.StorageContracts;
using LibraryAccountingApp_lab3.Contracts.ViewModels;
using LibraryAccountingApp_lab3.DatabaseImplement.Models;
namespace LibraryAccountingApp_lab3
{
public partial class FormLibrary : Form
{
private byte[]? selectedImage = new byte[16];
private readonly IBookLogic _bookLogic;
private readonly IAuthorLogic _authorLogic;
public readonly IBookStorage _bookStorage;
private List<byte[]> BooksImages = new List<byte[]>();
int rowIndex = 0;
private int _id;
public int Id { set { _id = value; } }
public FormLibrary(IBookLogic bookLogic, IAuthorLogic authorLogic)
{
InitializeComponent();
_bookLogic = bookLogic;
_authorLogic = authorLogic;
InitializeTableBooks();
LoadDataInTable();
}
private void FormLibrary_Load(object sender, EventArgs e)
{
LoadDataInTable();
}
public void AddBook(int rowIndex, BookViewModel book)
{
controlDataTableCellBooks.AddCell(rowIndex, 0, book);
controlDataTableCellBooks.AddCell(rowIndex, 1, book);
controlDataTableCellBooks.AddCell(rowIndex, 2, book);
controlDataTableCellBooks.AddCell(rowIndex, 3, book);
}
public void LoadDataInTable()
{
try
{
controlDataTableCellBooks.Clear();
var list = _bookLogic.ReadList(null);
if (list != null)
{
rowIndex = 0;
foreach (var book in list)
{
AddBook(rowIndex, book);
rowIndex++;
}
controlDataTableCellBooks.Update();
}
}
catch (Exception ex)
{
MessageBox.Show($"Îøèáêà çàãðóçêè äàííûõ: {ex.Message}");
}
}
private void InitializeTableBooks()
{
List<DataTableColumnConfig> columns = new List<DataTableColumnConfig> { };
DataTableColumnConfig item1 = new DataTableColumnConfig
{
ColumnHeader = "Id",
PropertyName = "Id",
Width = 20,
Visible = false,
};
DataTableColumnConfig item2 = new DataTableColumnConfig
{
ColumnHeader = "Íàçâàíèå",
PropertyName = "Title",
Width = 250,
Visible = true,
};
DataTableColumnConfig item3 = new DataTableColumnConfig
{
ColumnHeader = "Àâòîð",
PropertyName = "AuthorName",
Width = 180,
Visible = true,
};
DataTableColumnConfig item4 = new DataTableColumnConfig
{
ColumnHeader = "Äàòà èçäàíèÿ",
PropertyName = "Date",
Width = 150,
Visible = true,
};
columns.Add(item1);
columns.Add(item2);
columns.Add(item3);
columns.Add(item4);
controlDataTableCellBooks.LoadColumns(columns);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.A))
{
êíèãèToolStripMenuItem_Click(null, null);
return true;
}
if (keyData == (Keys.Control | Keys.U))
{
ðåäàêòèðîâàòüToolStripMenuItem_Click(null, null);
return true;
}
if (keyData == (Keys.Control | Keys.D))
{
óäàëèòüToolStripMenuItem_Click(null, null);
return true;
}
if (keyData == (Keys.Control | Keys.S))
{
pDFÑÎáëîæêàìèToolStripMenuItem_Click(null, null);
return true;
}
if (keyData == (Keys.Control | Keys.T))
{
excelÏîÂñåìÊíèãàìToolStripMenuItem_Click(null, null);
return true;
}
if (keyData == (Keys.Control | Keys.C))
{
ãèñòîãðàììàÂWordToolStripMenuItem_Click(null, null);
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void àâòîðûToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormAuthor));
if (service is FormAuthor form)
{
form.ShowDialog();
}
}
private void êíèãèToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormBook));
if (service is FormBook form)
{
form.ShowDialog();
}
LoadDataInTable();
}
private void pDFÑÎáëîæêàìèToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
var list = _bookLogic.ReadList(null);
if (list != null)
{
BooksImages.Clear();
foreach (var book in list)
{
BooksImages.Add(book.Image);
}
}
using SaveFileDialog saveFileDialog = new SaveFileDialog
{
Filter = "PDF Files|*.pdf",
DefaultExt = "pdf",
AddExtension = true
};
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
var config = new ImagePdfInfo
{
FilePath = saveFileDialog.FileName,
Header = "Äîêóìåíò ñ îáëîæêàìè êíèã",
Images = BooksImages
};
pdfForImages.CreatePdf(config);
MessageBox.Show("PDF óñïåøíî ñîçäàí!", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Ñîõðàíåíèå îòìåíåíî ïîëüçîâàòåëåì.", "Îòìåíà", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Îøèáêà çàãðóçêè äàííûõ: {ex.Message}");
}
}
private void excelÏîÂñåìÊíèãàìToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
// Ñïðîñèòü ó ïîëüçîâàòåëÿ ïóòü è èìÿ ôàéëà äëÿ ñîõðàíåíèÿ Excel
using SaveFileDialog saveFileDialog = new SaveFileDialog
{
Filter = "Excel Files|*.xlsx",
DefaultExt = "xlsx",
AddExtension = true
};
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filepath = saveFileDialog.FileName;
string title = "Òàáëèöà ñ êíèãàìè áèáëèîòåêè";
List<MergeCells> mergeCells = new List<MergeCells>()
{
new MergeCells("Êíèãà", new int[] { 1, 2 }),
};
List<ColumnInfo> columns = new List<ColumnInfo>()
{
new ColumnInfo("Id", "Id", 10),
new ColumnInfo("Title", "Íàçâàíèå", 30),
new ColumnInfo("AuthorName", "Àâòîð", 30),
new ColumnInfo("Date", "Äàòà", 20),
};
var list = _bookLogic.ReadList(null);
List<BookForExcel> data = new List<BookForExcel>();
if (list != null)
{
foreach (var book in list)
{
data.Add(new BookForExcel
{
Id = book.Id,
Title = book.Title,
AuthorName = book.AuthorName,
Date = book.Date
});
}
controlDataTableCellBooks.Update();
}
tableComponent.CreateDocument(filepath, title, mergeCells, columns, data);
MessageBox.Show("Excel óñïåøíî ñîçäàí!", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Ñîõðàíåíèå îòìåíåíî ïîëüçîâàòåëåì.", "Îòìåíà", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Îøèáêà çàãðóçêè äàííûõ: {ex.Message}");
}
}
private void ãèñòîãðàììàÂWordToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
// Ñïðîñèòü ó ïîëüçîâàòåëÿ ïóòü è èìÿ ôàéëà äëÿ ñîõðàíåíèÿ Word
using SaveFileDialog saveFileDialog = new SaveFileDialog
{
Filter = "Word Files|*.docx",
DefaultExt = "docx",
AddExtension = true
};
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
List<(int AuthorId, double Value)> listData = new List<(int AuthorId, double Value)>();
(int AuthorId, double Value) item = default;
// Ïîëó÷åíèå ñïèñêà àâòîðîâ
var authors = _authorLogic.ReadList(null);
if (authors != null)
{
// Ïîëó÷åíèå ñïèñêà êíèã
var books = _bookLogic.ReadList(null);
if (books != null)
{
// Ïîäñ÷åò êîëè÷åñòâà êíèã äëÿ êàæäîãî àâòîðà
foreach (var author in authors)
{
int bookCount = books.Count(book => book.AuthorName == author.Name);
listData.Add((author.Id, bookCount));
}
}
}
Dictionary<string, List<(int AuthorId, double Value)>> data = new()
{
{ "Àâòîðû", listData }
};
var config = new ComponentDocumentWithChartConfig
{
ChartTitle = "Ñêîëüêî êíèã íàïèñàëè àâòîðû",
FilePath = saveFileDialog.FileName,
Header = "Ãèñòîãðàììà â Word",
Data = data,
LegendLocation = ComponentsLibraryNet60.Models.Location.Rigth,
};
componentDocumentWithChartBarWord.CreateDoc(config);
MessageBox.Show("Word óñïåøíî ñîçäàí!", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Ñîõðàíåíèå îòìåíåíî ïîëüçîâàòåëåì.", "Îòìåíà", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Îøèáêà çàãðóçêè äàííûõ: {ex.Message}");
}
}
private void óäàëèòüToolStripMenuItem_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Óäàëèòü çàïèñü?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
var test = controlDataTableCellBooks.GetSelectedObject<BookBindingModel>().Title;
int test2 = controlDataTableCellBooks.GetSelectedObject<BookBindingModel>().Id;
var test3 = controlDataTableCellBooks.GetSelectedObject<BookBindingModel>();
var test4 = controlDataTableCellBooks.GetSelectedObject<BookViewModel>();
var test5 = controlDataTableCellBooks.GetSelectedObject<BookSearchModel>();
if (_bookLogic.Delete(new BookBindingModel { Id = controlDataTableCellBooks.GetSelectedObject<BookViewModel>().Id }))
{
LoadDataInTable();
}
else
{
MessageBox.Show("Îøèáêà ïðè óäàëåíèè", "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//if (MessageBox.Show("Óäàëèòü çàïèñü", "Âîïðîñ", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
//{
// int id = Convert.ToInt32(controlDataTableCellBooks.GetSelectedObject<BookBindingModel>().Id);
// var test = controlDataTableCellBooks.GetSelectedObject<BookBindingModel>().Title;
// try
// {
// _bookLogic.Delete(new BookBindingModel { Id = id });
// }
// catch (Exception ex)
// {
// MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
// }
// LoadDataInTable();
//}
}
private void ðåäàêòèðîâàòüToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormBook));
if (service is FormBook form)
{
form.Id = controlDataTableCellBooks.GetSelectedObject<BookViewModel>().Id;
if (form.ShowDialog() == DialogResult.OK)
{
LoadDataInTable();
}
}
}
}
}

View File

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

View File

@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ComponentsLibraryNet60" Version="1.0.0" />
<PackageReference Include="ControlsLibraryNet60" Version="1.0.0" />
<PackageReference Include="FedComponentLib" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.18" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.14" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.14">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.18" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\COP_5\COP_5.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,87 @@
// <auto-generated />
using LibraryAccountingApp_lab3.DatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace LibraryAccountingApp_lab3.Migrations
{
[DbContext(typeof(LibraryDatabase))]
[Migration("20241111111934_Initial")]
partial class Initial
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.18")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("LibraryAccountingApp_lab3.DatabaseImplement.Models.Author", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Authors");
});
modelBuilder.Entity("LibraryAccountingApp_lab3.DatabaseImplement.Models.Book", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("AuthorId")
.HasColumnType("int");
b.Property<string>("Date")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<byte[]>("Image")
.IsRequired()
.HasColumnType("varbinary(max)");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("AuthorId");
b.ToTable("Books");
});
modelBuilder.Entity("LibraryAccountingApp_lab3.DatabaseImplement.Models.Book", b =>
{
b.HasOne("LibraryAccountingApp_lab3.DatabaseImplement.Models.Author", "Author")
.WithMany()
.HasForeignKey("AuthorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Author");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,64 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace LibraryAccountingApp_lab3.Migrations
{
/// <inheritdoc />
public partial class Initial : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Authors",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Authors", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Books",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Title = table.Column<string>(type: "nvarchar(max)", nullable: false),
AuthorId = table.Column<int>(type: "int", nullable: false),
Date = table.Column<string>(type: "nvarchar(max)", nullable: false),
Image = table.Column<byte[]>(type: "varbinary(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Books", x => x.Id);
table.ForeignKey(
name: "FK_Books_Authors_AuthorId",
column: x => x.AuthorId,
principalTable: "Authors",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Books_AuthorId",
table: "Books",
column: "AuthorId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Books");
migrationBuilder.DropTable(
name: "Authors");
}
}
}

View File

@ -0,0 +1,84 @@
// <auto-generated />
using LibraryAccountingApp_lab3.DatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace LibraryAccountingApp_lab3.Migrations
{
[DbContext(typeof(LibraryDatabase))]
partial class LibraryDatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.18")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("LibraryAccountingApp_lab3.DatabaseImplement.Models.Author", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Authors");
});
modelBuilder.Entity("LibraryAccountingApp_lab3.DatabaseImplement.Models.Book", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("AuthorId")
.HasColumnType("int");
b.Property<string>("Date")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<byte[]>("Image")
.IsRequired()
.HasColumnType("varbinary(max)");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("AuthorId");
b.ToTable("Books");
});
modelBuilder.Entity("LibraryAccountingApp_lab3.DatabaseImplement.Models.Book", b =>
{
b.HasOne("LibraryAccountingApp_lab3.DatabaseImplement.Models.Author", "Author")
.WithMany()
.HasForeignKey("AuthorId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Author");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,42 @@
using LibraryAccountingApp_lab3.BusinessLogic;
using LibraryAccountingApp_lab3.Contracts.BusinessLogicsContracts;
using LibraryAccountingApp_lab3.Contracts.StorageContracts;
using LibraryAccountingApp_lab3.DatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace LibraryAccountingApp_lab3
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormLibrary>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddTransient<IBookStorage, BookStorage>();
services.AddTransient<IAuthorStorage, AuthorStorage>();
services.AddTransient<IBookLogic, BookLogic>();
services.AddTransient<IAuthorLogic, AuthorLogic>();
services.AddTransient<FormLibrary>();
services.AddTransient<FormAuthor>();
services.AddTransient<FormBook>();
}
}
}

406
COP_5/WinFormsApp/Form1.Designer.cs generated Normal file
View File

@ -0,0 +1,406 @@
namespace WinFormsApp
{
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();
chooseCheckedListBox1 = new COP_5.ChooseCheckedListBox();
label1 = new Label();
label2 = new Label();
rangeTextBox = new COP_5.RangeTextBox();
treeView1 = new COP_5.TreeView();
label3 = new Label();
label4 = new Label();
label5 = new Label();
numericUpDownRangeMin = new NumericUpDown();
numericUpDownRangeMax = new NumericUpDown();
DepartamentComboBox = new ComboBox();
label6 = new Label();
buttonChooseImage = new Button();
buttonCreateImagePdf = new Button();
groupBox1 = new GroupBox();
groupBox2 = new GroupBox();
groupBox3 = new GroupBox();
buttonSelectEmployee = new Button();
buttonAddEmployee = new Button();
label8 = new Label();
NameTextBox = new TextBox();
label7 = new Label();
PostTextBox = new TextBox();
groupBox4 = new GroupBox();
buttonCreateDiagramPdf = new Button();
listBoxWithImages = new ListBox();
buttonTablePdf = new Button();
pdfForImages1 = new COP_5.PdfForImages(components);
((System.ComponentModel.ISupportInitialize)numericUpDownRangeMin).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownRangeMax).BeginInit();
groupBox1.SuspendLayout();
groupBox2.SuspendLayout();
groupBox3.SuspendLayout();
groupBox4.SuspendLayout();
SuspendLayout();
//
// chooseCheckedListBox1
//
chooseCheckedListBox1.Anchor = AnchorStyles.Top | AnchorStyles.Right;
chooseCheckedListBox1.Location = new Point(7, 46);
chooseCheckedListBox1.Name = "chooseCheckedListBox1";
chooseCheckedListBox1.SelectedValue = "";
chooseCheckedListBox1.Size = new Size(225, 168);
chooseCheckedListBox1.TabIndex = 0;
//
// label1
//
label1.Anchor = AnchorStyles.Top | AnchorStyles.Right;
label1.AutoSize = true;
label1.Location = new Point(50, 21);
label1.Name = "label1";
label1.Size = new Size(164, 15);
label1.TabIndex = 1;
label1.Text = "Выбор из списка с выбором";
//
// label2
//
label2.Anchor = AnchorStyles.Top | AnchorStyles.Right;
label2.AutoSize = true;
label2.Location = new Point(11, 27);
label2.Name = "label2";
label2.Size = new Size(272, 15);
label2.TabIndex = 2;
label2.Text = "Ввод значения с проверкой (длина в диапазоне)";
//
// rangeTextBox
//
rangeTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Right;
rangeTextBox.Location = new Point(4, 45);
rangeTextBox.MaxLength = 0;
rangeTextBox.MinLength = 0;
rangeTextBox.Name = "rangeTextBox";
rangeTextBox.Size = new Size(315, 41);
rangeTextBox.TabIndex = 3;
rangeTextBox.TextBoxValue = "";
//
// treeView1
//
treeView1.Location = new Point(6, 42);
treeView1.Name = "treeView1";
treeView1.SelectedNodeIndex = -1;
treeView1.Size = new Size(263, 255);
treeView1.TabIndex = 4;
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(37, 24);
label3.Name = "label3";
label3.Size = new Size(160, 15);
label3.TabIndex = 5;
label3.Text = "Вывод списка в виде дерева";
//
// label4
//
label4.Anchor = AnchorStyles.Top | AnchorStyles.Right;
label4.AutoSize = true;
label4.Location = new Point(30, 77);
label4.Name = "label4";
label4.Size = new Size(21, 15);
label4.TabIndex = 10;
label4.Text = "От";
//
// label5
//
label5.Anchor = AnchorStyles.Top | AnchorStyles.Right;
label5.AutoSize = true;
label5.Location = new Point(198, 77);
label5.Name = "label5";
label5.Size = new Size(22, 15);
label5.TabIndex = 11;
label5.Text = "До";
//
// numericUpDownRangeMin
//
numericUpDownRangeMin.Anchor = AnchorStyles.Top | AnchorStyles.Right;
numericUpDownRangeMin.Location = new Point(58, 75);
numericUpDownRangeMin.Margin = new Padding(3, 2, 3, 2);
numericUpDownRangeMin.Name = "numericUpDownRangeMin";
numericUpDownRangeMin.Size = new Size(92, 23);
numericUpDownRangeMin.TabIndex = 12;
numericUpDownRangeMin.ValueChanged += numericUpDownRangeMin_ValueChanged;
//
// numericUpDownRangeMax
//
numericUpDownRangeMax.Anchor = AnchorStyles.Top | AnchorStyles.Right;
numericUpDownRangeMax.Location = new Point(227, 75);
numericUpDownRangeMax.Margin = new Padding(3, 2, 3, 2);
numericUpDownRangeMax.Name = "numericUpDownRangeMax";
numericUpDownRangeMax.Size = new Size(92, 23);
numericUpDownRangeMax.TabIndex = 13;
numericUpDownRangeMax.ValueChanged += numericUpDownRangeMax_ValueChanged;
//
// DepartamentComboBox
//
DepartamentComboBox.FormattingEnabled = true;
DepartamentComboBox.Location = new Point(275, 72);
DepartamentComboBox.Margin = new Padding(3, 2, 3, 2);
DepartamentComboBox.Name = "DepartamentComboBox";
DepartamentComboBox.Size = new Size(133, 23);
DepartamentComboBox.TabIndex = 14;
//
// label6
//
label6.Anchor = AnchorStyles.Top | AnchorStyles.Right;
label6.AutoSize = true;
label6.Location = new Point(275, 55);
label6.Name = "label6";
label6.Size = new Size(40, 15);
label6.TabIndex = 15;
label6.Text = "Отдел";
//
// buttonChooseImage
//
buttonChooseImage.Location = new Point(6, 191);
buttonChooseImage.Margin = new Padding(3, 2, 3, 2);
buttonChooseImage.Name = "buttonChooseImage";
buttonChooseImage.Size = new Size(168, 38);
buttonChooseImage.TabIndex = 16;
buttonChooseImage.Text = "Выбрать изображение";
buttonChooseImage.UseVisualStyleBackColor = true;
buttonChooseImage.Click += buttonCreate_Click;
//
// buttonCreateImagePdf
//
buttonCreateImagePdf.Location = new Point(6, 239);
buttonCreateImagePdf.Margin = new Padding(3, 2, 3, 2);
buttonCreateImagePdf.Name = "buttonCreateImagePdf";
buttonCreateImagePdf.Size = new Size(168, 38);
buttonCreateImagePdf.TabIndex = 17;
buttonCreateImagePdf.Text = "Создать изображение в PDF";
buttonCreateImagePdf.UseVisualStyleBackColor = true;
buttonCreateImagePdf.Click += buttonCreateImagePdf_Click;
//
// groupBox1
//
groupBox1.Anchor = AnchorStyles.Top | AnchorStyles.Right;
groupBox1.Controls.Add(numericUpDownRangeMax);
groupBox1.Controls.Add(numericUpDownRangeMin);
groupBox1.Controls.Add(label5);
groupBox1.Controls.Add(label4);
groupBox1.Controls.Add(rangeTextBox);
groupBox1.Controls.Add(label2);
groupBox1.Location = new Point(523, 12);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(335, 108);
groupBox1.TabIndex = 18;
groupBox1.TabStop = false;
groupBox1.Text = "Кастомный TextBox";
//
// groupBox2
//
groupBox2.Anchor = AnchorStyles.Top | AnchorStyles.Right;
groupBox2.Controls.Add(label1);
groupBox2.Controls.Add(chooseCheckedListBox1);
groupBox2.Location = new Point(581, 137);
groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(244, 225);
groupBox2.TabIndex = 19;
groupBox2.TabStop = false;
groupBox2.Text = "Кастомный ListBox";
//
// groupBox3
//
groupBox3.Controls.Add(buttonSelectEmployee);
groupBox3.Controls.Add(buttonAddEmployee);
groupBox3.Controls.Add(label8);
groupBox3.Controls.Add(NameTextBox);
groupBox3.Controls.Add(label7);
groupBox3.Controls.Add(PostTextBox);
groupBox3.Controls.Add(label6);
groupBox3.Controls.Add(DepartamentComboBox);
groupBox3.Controls.Add(label3);
groupBox3.Controls.Add(treeView1);
groupBox3.Location = new Point(12, 12);
groupBox3.Name = "groupBox3";
groupBox3.Size = new Size(418, 313);
groupBox3.TabIndex = 20;
groupBox3.TabStop = false;
groupBox3.Text = "Кастомный TreeView";
//
// buttonSelectEmployee
//
buttonSelectEmployee.Location = new Point(277, 259);
buttonSelectEmployee.Name = "buttonSelectEmployee";
buttonSelectEmployee.Size = new Size(131, 38);
buttonSelectEmployee.TabIndex = 21;
buttonSelectEmployee.Text = "Выбрать сотрудника";
buttonSelectEmployee.UseVisualStyleBackColor = true;
buttonSelectEmployee.Click += buttonSelectEmployee_Click;
//
// buttonAddEmployee
//
buttonAddEmployee.Location = new Point(277, 215);
buttonAddEmployee.Name = "buttonAddEmployee";
buttonAddEmployee.Size = new Size(131, 38);
buttonAddEmployee.TabIndex = 20;
buttonAddEmployee.Text = "Добавить сотрудника";
buttonAddEmployee.UseVisualStyleBackColor = true;
buttonAddEmployee.Click += buttonAddEmployee_Click;
//
// label8
//
label8.Anchor = AnchorStyles.Top | AnchorStyles.Right;
label8.AutoSize = true;
label8.Location = new Point(275, 144);
label8.Name = "label8";
label8.Size = new Size(34, 15);
label8.TabIndex = 19;
label8.Text = "ФИО";
//
// NameTextBox
//
NameTextBox.Location = new Point(275, 162);
NameTextBox.Name = "NameTextBox";
NameTextBox.Size = new Size(133, 23);
NameTextBox.TabIndex = 18;
//
// label7
//
label7.Anchor = AnchorStyles.Top | AnchorStyles.Right;
label7.AutoSize = true;
label7.Location = new Point(275, 98);
label7.Name = "label7";
label7.Size = new Size(69, 15);
label7.TabIndex = 17;
label7.Text = "Должность";
//
// PostTextBox
//
PostTextBox.Location = new Point(275, 116);
PostTextBox.Name = "PostTextBox";
PostTextBox.Size = new Size(133, 23);
PostTextBox.TabIndex = 16;
//
// groupBox4
//
groupBox4.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
groupBox4.Controls.Add(buttonCreateDiagramPdf);
groupBox4.Controls.Add(listBoxWithImages);
groupBox4.Controls.Add(buttonTablePdf);
groupBox4.Controls.Add(buttonChooseImage);
groupBox4.Controls.Add(buttonCreateImagePdf);
groupBox4.Location = new Point(12, 342);
groupBox4.Name = "groupBox4";
groupBox4.Size = new Size(344, 286);
groupBox4.TabIndex = 21;
groupBox4.TabStop = false;
groupBox4.Text = "PDF";
//
// buttonCreateDiagramPdf
//
buttonCreateDiagramPdf.Location = new Point(180, 191);
buttonCreateDiagramPdf.Name = "buttonCreateDiagramPdf";
buttonCreateDiagramPdf.Size = new Size(158, 38);
buttonCreateDiagramPdf.TabIndex = 23;
buttonCreateDiagramPdf.Text = "Создать диаграмму в PDF";
buttonCreateDiagramPdf.UseVisualStyleBackColor = true;
buttonCreateDiagramPdf.Click += buttonCreateDiagramPdf_Click;
//
// listBoxWithImages
//
listBoxWithImages.FormattingEnabled = true;
listBoxWithImages.ItemHeight = 15;
listBoxWithImages.Location = new Point(6, 35);
listBoxWithImages.Name = "listBoxWithImages";
listBoxWithImages.Size = new Size(332, 124);
listBoxWithImages.TabIndex = 18;
//
// buttonTablePdf
//
buttonTablePdf.Location = new Point(180, 243);
buttonTablePdf.Name = "buttonTablePdf";
buttonTablePdf.Size = new Size(158, 34);
buttonTablePdf.TabIndex = 22;
buttonTablePdf.Text = "Создать таблицу в PDF";
buttonTablePdf.UseVisualStyleBackColor = true;
buttonTablePdf.Click += buttonTablePdf_Click;
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(864, 640);
Controls.Add(groupBox4);
Controls.Add(groupBox3);
Controls.Add(groupBox2);
Controls.Add(groupBox1);
Name = "Form1";
Text = "Тестовая формочка";
((System.ComponentModel.ISupportInitialize)numericUpDownRangeMin).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownRangeMax).EndInit();
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
groupBox2.ResumeLayout(false);
groupBox2.PerformLayout();
groupBox3.ResumeLayout(false);
groupBox3.PerformLayout();
groupBox4.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private COP_5.ChooseCheckedListBox chososeList1;
private COP_5.ChooseCheckedListBox chooseCheckedListBox1;
private Label label1;
private Label label2;
private COP_5.RangeTextBox rangeTextBox;
private COP_5.TreeView treeView1;
private Label label3;
private Label label4;
private Label label5;
private NumericUpDown numericUpDownRangeMin;
private NumericUpDown numericUpDownRangeMax;
private ComboBox DepartamentComboBox;
private Label label6;
private Button buttonChooseImage;
private Button buttonCreateImagePdf;
private GroupBox groupBox1;
private GroupBox groupBox2;
private GroupBox groupBox3;
private GroupBox groupBox4;
private ListBox listBoxWithImages;
private Button buttonTablePdf;
private Button buttonCreateDiagramPdf;
private Button buttonAddEmployee;
private Label label8;
private TextBox NameTextBox;
private Label label7;
private TextBox PostTextBox;
private Button buttonSelectEmployee;
private COP_5.PdfForImages pdfForImages1;
}
}

200
COP_5/WinFormsApp/Form1.cs Normal file
View File

@ -0,0 +1,200 @@
using COP_5;
using COP_5.Exceptions;
using COP_5.PdfHelper;
using COP_5.TestClasses;
namespace WinFormsApp
{
public partial class Form1 : Form
{
private PdfForImages pdfForImages = new PdfForImages();
private PdfForTables pdfForTables = new PdfForTables();
private PdfForDiagram PdfForDiagram = new PdfForDiagram();
private List<byte[]> selectedImages = new List<byte[]>();
public Form1()
{
InitializeComponent();
FillChooseCheckedListBox();
FillTreeView();
}
private void FillChooseCheckedListBox()
{
List<string> list = new List<string>() { "Çíà÷åíèå 1", "Çíà÷åíèå 2", "Çíà÷åíèå 3", "Çíà÷åíèå 4", "Çíà÷åíèå 5" };
for (int i = 0; i < list.Count; i++)
{
chooseCheckedListBox1.AddItemToList(list[i]);
}
}
private void FillTreeView()
{
DepartamentComboBox.Items.Add("Îòäåë ïðîäàæ");
DepartamentComboBox.Items.Add("Îòäåë àíàëèòèêè");
DepartamentComboBox.Items.Add("IT îòäåë");
var hierarchy = new List<string> { "Department", "Post", "Name" };
var newBranch = new Dictionary<string, bool> { { "Name", true } };
treeView1.SetHierarchy(hierarchy, newBranch);
var employees = new List<Employee>
{
new Employee("Îòäåë ïðîäàæ", "Ìåíåäæåð", "Âàðóì Àíæåëèêà" ),
new Employee("Îòäåë ïðîäàæ", "Òåëåìàðêåòîëîã", "Ïåòð Äóðîâ"),
new Employee("Îòäåë àíàëèòèêè", "Ôèíàíñîâûé àíàëèòèê", "Àãóòèí Ëåîíèä"),
new Employee("Îòäåë àíàëèòèêè", "Ñèñòåìíûé àíàëèòèê", "Ñòåïàíèòà Êàáëó÷åâñêàÿ"),
new Employee("Îòäåë àíàëèòèêè", "Ñèñòåìíûé àíàëèòèê", "Ðîçàëèÿ Ñìåëàÿ"),
new Employee("IT îòäåë", "Ðàçðàáîò÷èê Python", "Äæåéí Êàáà÷êîâà"),
new Employee("IT îòäåë", "Ðàçðàáîò÷èê Java", "Õðèñòèíà Öèáàðåòêîâà"),
new Employee("IT îòäåë", "Ðàçðàáîò÷èê Java", "Âèêòîð Âûíü-äà-Ïîëîæ"),
new Employee("IT îòäåë", "Ðàçðàáîò÷èê C++", "Îëåñÿ Ôûð"),
};
foreach (var employee in employees)
{
treeView1.AddObjectToTree(employee, hierarchy.Last());
}
}
private void buttonAddEmployee_Click(object sender, EventArgs e)
{
if (PostTextBox.Text == null || NameTextBox.Text == null || DepartamentComboBox.SelectedItem == null)
{
return;
}
var hierarchy = new List<string> { "Department", "Post", "Name" };
treeView1.AddObjectToTree(new Employee(DepartamentComboBox.SelectedItem.ToString(), PostTextBox.Text, NameTextBox.Text), hierarchy.Last());
treeView1.Update();
}
private void buttonSelectEmployee_Click(object sender, EventArgs e)
{
Employee employee = treeView1.GetSelectedObject<Employee>();
if (employee == null)
{
return;
}
DepartamentComboBox.SelectedItem = employee.Department;
PostTextBox.Text = employee.Post;
NameTextBox.Text = employee.Name;
}
private void numericUpDownRangeMin_ValueChanged(object sender, EventArgs e)
{
int minLengthValue = Convert.ToInt32(numericUpDownRangeMin.Value);
rangeTextBox.MinLength = minLengthValue;
}
private void numericUpDownRangeMax_ValueChanged(object sender, EventArgs e)
{
int maxLengthValue = Convert.ToInt32(numericUpDownRangeMax.Value);
rangeTextBox.MaxLength = maxLengthValue;
rangeTextBox.Update();
}
private void buttonCreate_Click(object sender, EventArgs e)
{
using OpenFileDialog openFileDialog = new OpenFileDialog
{
Multiselect = true,
Filter = "Èçîáðàæåíèÿ|*.jpg;*.jpeg;*.png;*.bmp"
};
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
selectedImages.Clear();
listBoxWithImages.Items.Clear();
foreach (string filePath in openFileDialog.FileNames)
{
selectedImages.Add(File.ReadAllBytes(filePath));
listBoxWithImages.Items.Add(Path.GetFileName(filePath));
}
}
}
private void buttonCreateImagePdf_Click(object sender, EventArgs e)
{
if (selectedImages.Count == 0)
{
MessageBox.Show("Âûáåðèòå õîòÿ áû îäíî èçîáðàæåíèå!", "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var config = new ImagePdfInfo
{
FilePath = "D:\\ULSTU\\COP\\PdfWithImage.pdf",
Header = "Äîêóìåíò ñ èçîáðàæåíèÿìè",
Images = selectedImages
};
pdfForImages.CreatePdf(config);
MessageBox.Show("PDF óñïåøíî ñîçäàí!", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void buttonTablePdf_Click(object sender, EventArgs e)
{
TablePdfInfo<Human> config = new TablePdfInfo<Human>
{
FileName = "D:\\ULSTU\\COP\\PdfWithTable.pdf",
Title = "Ïðèìåð Òàáëèöû",
RowHeights = new List<double> { 1, 1, 1 },
Headers = new Dictionary<string, List<(string Name, string Value)>>
{
{ "Ëè÷íûå äàííûå", new List<(string Name, string Value)> { ("Name", "Èìÿ"), ("Surname", "Ôàìèëèÿ") } },
{ "Âîçðàñò", new List<(string Name, string Value)> () },
},
Data = new List<Human>
{
new Human("Àíæåëèêà", "Âàðóì", 30),
new Human("Àãóòèí", "Ëåîíèä", 35),
new Human("Ðîìàí", "Ñëóæåáíûé", 10)
}
};
try
{
// Âûçîâ ìåòîäà äëÿ ñîçäàíèÿ PDF
pdfForTables.CreatePdf(config);
MessageBox.Show("PDF-äîêóìåíò óñïåøíî ñîçäàí!", "Óñïåõ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Îøèáêà ïðè ñîçäàíèè PDF: {ex.Message}", "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCreateDiagramPdf_Click(object sender, EventArgs e)
{
try
{
PdfForDiagram.CreateDoc(new DiagramPdfInfo
{
FilePath = "D:\\ULSTU\\COP\\PdfWithPieDiagram.pdf",
Header = "Ïðèìåð çàãîëîâêà",
ChartTitle = "Êðóãîâàÿ äèàãðàììà",
LegendLocation = COP_5.PdfHelper.PdfParagraphAlignmentType.Bottom,
Data = new Dictionary<string, List<(string Name, double Value)>>
{
{
"Product A", new List<(string Name, double Value)>
{
("Çíà÷åíèå 1", 120.0),
("Çíà÷åíèå 2", 250.0),
("Çíà÷åíèå 3", 50.0)
}
}
}
});
MessageBox.Show("PDF äîêóìåíò ñ äèàãðàììîé ñîçäàí!", "Óñïåõ");
}
catch (Exception ex)
{
MessageBox.Show($"Îøèáêà: {ex.Message}");
}
}
}
}

View File

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

View File

@ -0,0 +1,18 @@
namespace WinFormsApp
{
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());
//Application.Run(new FormLibrary());
}
}
}

View File

@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ComponentsLibraryNet60" Version="1.0.0" />
<PackageReference Include="ControlsLibraryNet60" Version="1.0.0" />
<PackageReference Include="FedComponentLib" Version="1.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\COP_5\COP_5.csproj" />
</ItemGroup>
</Project>