Compare commits

...

41 Commits
main ... lab3

Author SHA1 Message Date
1ba0759d3c провсто добавила новый проект для 4 лабы случайно в третью 2024-11-30 20:39:18 +04:00
6c77b73f44 о еще пофиксила критическое и сдала 2024-11-20 16:55:12 +04:00
3ea68ad50d все сделала, только сдать осталось 2024-11-20 16:45:43 +04:00
394ecca149 работает форма добавления и редактирования полностью, пофиксила компонент выбора из списка 2024-11-20 13:39:30 +04:00
9c3a569942 работает справочник, все отлично
нужно связать теперь главную и справочник, поработать с горячими главишами и документами
2024-11-20 13:13:24 +04:00
64c1a27950 ну и вызов справочника добавила, все, спать 2024-11-20 01:36:20 +04:00
716c8682de без клавиш все работает вроде по созданию/редактированию/удалению основной сущности 2024-11-20 01:29:06 +04:00
9e1d524c2e работает проверка на изменение перед закрытием 2024-11-20 00:37:05 +04:00
061773baca работает вывод полей для редактирования 2024-11-20 00:06:32 +04:00
e507aa62a2 выводится тривью на главной форме 2024-11-19 22:29:34 +04:00
e5dd7184ed вроде все классы готовы, теперь нужно доработать формы и приступить к документам... 2024-11-19 02:15:38 +04:00
f1422b3632 нужно еще сторедж классы сделать и формы начать пилить по-адекватному 2024-11-19 01:40:09 +04:00
12844f798e поправила одно поле в моделях и сделала модели для базы данных 2024-11-19 01:20:24 +04:00
be9a809eae слой бизнес логики закончен 2024-11-19 00:49:49 +04:00
b111ab8039 так, я закончила слой контрактов. далее ждет жЕпа 2024-11-18 01:55:14 +04:00
c3b0de078d начала слой контрактов, добавила модели (интерфейсы моделей) 2024-11-18 01:41:24 +04:00
0dd9d6702c начинаю делать форму для справочника 2024-11-18 01:20:57 +04:00
9e102f153d форму создания/редактирования налепила вроде 2024-11-18 00:00:54 +04:00
f396b005b8 ну... я форму главную накидала немного 2024-11-17 15:30:59 +04:00
d29d0674ca вторая лаба сдана, а коммит в третьей 2024-11-06 17:14:14 +04:00
53121f5150 новый проект добавила, попыталась подключить пакет Кирилла, не вышло не фортануло. но и не сильно то надо, спасть вообще пора... 2024-11-05 23:02:31 +04:00
da0b0b3c97 чет подправила, у меня там очень много закомментированного кода было... 2024-11-05 18:50:01 +04:00
dd9e86a211 все работает НАКОНЕЦ ТО Я ЕГО РОТ НАОБОРОТ да и поздно уже... на паре ему не работалось...( 2024-10-23 22:51:01 +04:00
78cadc292f что-то работает во втором компоненте, но это все ТАКОЕ Г.... 2024-10-23 17:55:00 +04:00
db33928447 работает третий компонент, а второй не работает 2024-10-22 12:40:57 +04:00
e2e42acf98 так.. ну я начала что-то делать и устала. 6 часов делала второй компонент, гпт всякую фигню советует, опять переделывать... нужно настроить объединение ячеек в таблице и вообще вывод информации 2024-10-20 17:52:02 +04:00
c357d9e21b продолжаю делать 2 лабу... 2024-10-07 14:38:45 +04:00
4ef34fb579 изменения делаю во второй лабе, но я доделала и у меня приняли 1 лабу, 3 компонент 2024-10-07 14:15:47 +04:00
8a74c38488 начала делать второй компонент 2024-10-06 23:30:51 +04:00
877dcc8eed убрала излишние комментарии :/ для первого компонента 2024-10-06 22:26:24 +04:00
719ba80758 готов первый компонент 2024-10-06 22:24:58 +04:00
d79cf20111 рабочий третий компонент без символов начала и конца и спроверкой на нуллбл 2024-09-28 13:59:17 +04:00
d270df92c0 какие-то танцы с бубном по третьему компоненту и считыванию подстроки 2024-09-23 14:04:59 +04:00
da7b64ec6f чет проверила в лабе, подправила (в третьем компоненте...)
вроде работает
2024-09-23 01:06:36 +04:00
bbc5701cbc работает третий компонент :_) 2024-09-21 17:36:24 +04:00
0bd7fd69e3 второй компонент работает 2024-09-14 22:23:11 +04:00
89ceade732 в процессе разработки второго компонента 2024-09-06 22:21:18 +04:00
be6e8d0466 начинаю делать компонент ввода 2024-09-06 11:44:11 +04:00
33f373fde7 добавила тестовое приложение и протестировала компонент выбора из списка 2024-09-06 11:43:48 +04:00
8084f4f79a добавила компонент выбора из списка 2024-09-06 11:43:25 +04:00
34989eaa4a создание проекта 2024-09-06 10:02:55 +04:00
69 changed files with 4756 additions and 0 deletions

View File

@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Components" Version="1.0.1" />
<PackageReference Include="FixedWinFormsLibrary1" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="9.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ShopBusinessLogic\ShopBusinessLogic.csproj" />
<ProjectReference Include="..\ShopDataBaseImplements\ShopDataBaseImplements.csproj" />
<ProjectReference Include="..\UserComponentsOption19\UserComponentsOption19.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,184 @@
namespace AppShopInternetOption19
{
partial class FormEdit_Add
{
/// <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()
{
textComponentOrderSum = new WinFormsLibrary1.TextComponent();
textBoxFIO = new TextBox();
labelFIO = new Label();
labelGoodDescription = new Label();
textBoxGoodDescription = new TextBox();
labelOrderSum = new Label();
labelOrderStatus = new Label();
selectComponentOrderStatus = new UserComponentsOption19.SelectComponent();
buttonClose = new Button();
buttonSave = new Button();
SuspendLayout();
//
// textComponentOrderSum
//
textComponentOrderSum.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
textComponentOrderSum.Location = new Point(213, -35);
textComponentOrderSum.Margin = new Padding(3, 4, 3, 4);
textComponentOrderSum.Name = "textComponentOrderSum";
textComponentOrderSum.Size = new Size(351, 199);
textComponentOrderSum.TabIndex = 0;
textComponentOrderSum.TextValue = 0;
//
// textBoxFIO
//
textBoxFIO.Location = new Point(60, 9);
textBoxFIO.Name = "textBoxFIO";
textBoxFIO.Size = new Size(346, 27);
textBoxFIO.TabIndex = 1;
textBoxFIO.TextChanged += valueChanged;
//
// labelFIO
//
labelFIO.AutoSize = true;
labelFIO.Location = new Point(12, 9);
labelFIO.Name = "labelFIO";
labelFIO.Size = new Size(42, 20);
labelFIO.TabIndex = 4;
labelFIO.Text = "ФИО";
//
// labelGoodDescription
//
labelGoodDescription.Anchor = AnchorStyles.Top | AnchorStyles.Right;
labelGoodDescription.AutoSize = true;
labelGoodDescription.Location = new Point(430, 16);
labelGoodDescription.Name = "labelGoodDescription";
labelGoodDescription.Size = new Size(131, 20);
labelGoodDescription.TabIndex = 7;
labelGoodDescription.Text = "Описание товара";
//
// textBoxGoodDescription
//
textBoxGoodDescription.Anchor = AnchorStyles.Top | AnchorStyles.Right;
textBoxGoodDescription.Location = new Point(582, 9);
textBoxGoodDescription.Name = "textBoxGoodDescription";
textBoxGoodDescription.Size = new Size(378, 27);
textBoxGoodDescription.TabIndex = 8;
textBoxGoodDescription.TextChanged += valueChanged;
//
// labelOrderSum
//
labelOrderSum.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
labelOrderSum.AutoSize = true;
labelOrderSum.Location = new Point(248, 59);
labelOrderSum.Name = "labelOrderSum";
labelOrderSum.Size = new Size(104, 20);
labelOrderSum.TabIndex = 9;
labelOrderSum.Text = "Сумма заказа";
//
// labelOrderStatus
//
labelOrderStatus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
labelOrderStatus.AutoSize = true;
labelOrderStatus.Location = new Point(12, 59);
labelOrderStatus.Name = "labelOrderStatus";
labelOrderStatus.Size = new Size(101, 20);
labelOrderStatus.TabIndex = 10;
labelOrderStatus.Text = "Статус заказа";
//
// selectComponentOrderStatus
//
selectComponentOrderStatus.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
selectComponentOrderStatus.Location = new Point(12, 91);
selectComponentOrderStatus.Name = "selectComponentOrderStatus";
selectComponentOrderStatus.SelectedValue = "";
selectComponentOrderStatus.Size = new Size(189, 36);
selectComponentOrderStatus.TabIndex = 11;
selectComponentOrderStatus.SelectComponentChanged += valueChanged;
//
// buttonClose
//
buttonClose.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonClose.BackColor = Color.IndianRed;
buttonClose.ForeColor = SystemColors.ButtonHighlight;
buttonClose.Location = new Point(582, 80);
buttonClose.Name = "buttonClose";
buttonClose.Size = new Size(138, 47);
buttonClose.TabIndex = 12;
buttonClose.Text = "Закрыть";
buttonClose.UseVisualStyleBackColor = false;
buttonClose.Click += buttonClose_Click;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonSave.BackColor = Color.LightGreen;
buttonSave.ForeColor = Color.DarkGreen;
buttonSave.Location = new Point(822, 80);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(138, 47);
buttonSave.TabIndex = 13;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = false;
buttonSave.Click += buttonSave_Click;
//
// FormEdit_Add
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1032, 166);
Controls.Add(buttonSave);
Controls.Add(buttonClose);
Controls.Add(selectComponentOrderStatus);
Controls.Add(labelOrderStatus);
Controls.Add(labelOrderSum);
Controls.Add(textBoxGoodDescription);
Controls.Add(labelGoodDescription);
Controls.Add(labelFIO);
Controls.Add(textBoxFIO);
Controls.Add(textComponentOrderSum);
Name = "FormEdit_Add";
Text = "Редактировать/добавить сущность";
Load += FormEdit_Add_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private WinFormsLibrary1.TextComponent textComponentOrderSum;
private TextBox textBoxFIO;
private TextBox textBoxLastName;
private TextBox textBoxPatronymic;
private Label labelFIO;
private Label labelLastName;
private Label labelPatronymic;
private Label labelGoodDescription;
private TextBox textBoxGoodDescription;
private Label labelOrderSum;
private Label labelOrderStatus;
private UserComponentsOption19.SelectComponent selectComponentOrderStatus;
private Button buttonClose;
private Button buttonSave;
}
}

View File

@ -0,0 +1,124 @@
using ShopContracts.BindingModels;
using ShopContracts.BusinessLogicContracts;
using ShopContracts.SearchModels;
namespace AppShopInternetOption19
{
public partial class FormEdit_Add : Form
{
private readonly IOrderLogic _orderLogic;
private readonly IOrderStatusLogic _orderStatusLogic;
private int? _id;
public int Id { set { _id = value; } }
private bool isChanged = false;
public FormEdit_Add(IOrderLogic orderLogic, IOrderStatusLogic orderStatusLogic)
{
_orderLogic = orderLogic;
_orderStatusLogic = orderStatusLogic;
InitializeComponent();
selectComponentOrderStatus.FillList(_orderStatusLogic.ReadList(null), "Name");
textBoxFIO.TextChanged += valueChanged;
textBoxGoodDescription.TextChanged += valueChanged;
textComponentOrderSum.TextChanged += valueChanged;
selectComponentOrderStatus.SelectComponentChanged += valueChanged;
}
private void FormEdit_Add_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
if (_id != null)
{
var element = _orderLogic.ReadElement(new OrderSearchModel { Id = _id.Value });
if (element != null)
{
textBoxFIO.Text = element.FIO;
textBoxGoodDescription.Text = element.OrderDescription;
selectComponentOrderStatus.SelectedValue = element.OrderStatus;
if (int.TryParse(element.OrderSumm?.ToString(), out int result))
{
textComponentOrderSum.TextValue = result;
}
else
{
textComponentOrderSum.TextValue = null;
}
}
}
isChanged = false;
}
catch (Exception)
{
throw;
}
}
private void valueChanged(object sender, EventArgs e)
{
isChanged = true;
}
private void buttonClose_Click(object sender, EventArgs e)
{
if (isChanged == true)
{
var result = MessageBox.Show(
"Есть несохраненные изменения. Вы уверены, что хотите закрыть?",
"Подтверждение",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question
);
if (result == DialogResult.Yes)
{
Close();
}
else if (result == DialogResult.No)
{
MessageBox.Show("Окей, тогда делайте дальше)", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
Close();
}
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
var element = new OrderBindingModel
{
Id = _id ?? 0,
FIO = textBoxFIO.Text,
OrderDescription = textBoxGoodDescription.Text,
OrderStatus = selectComponentOrderStatus.SelectedValue.ToString(),
OrderSumm = textComponentOrderSum.TextValue.ToString() ?? "Оплачено скидками",
};
var operatingResult = _id.HasValue ? _orderLogic.Update(element) : _orderLogic.Create(element);
if (!operatingResult)
{
throw new Exception("Ошибка при создании сущности");
}
MessageBox.Show("Создание сущности прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

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,95 @@
using ShopDataBaseImplements.Models;
namespace AppShopInternetOption19.Forms
{
partial class FormGuide
{
/// <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()
{
dataGridViewGuide = new DataGridView();
OrderStatus = new DataGridViewTextBoxColumn();
ID = new DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)dataGridViewGuide).BeginInit();
SuspendLayout();
//
// dataGridViewGuide
//
dataGridViewGuide.AllowUserToAddRows = false;
dataGridViewGuide.AllowUserToDeleteRows = false;
dataGridViewGuide.AllowUserToResizeColumns = false;
dataGridViewGuide.AllowUserToResizeRows = false;
dataGridViewGuide.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
dataGridViewGuide.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewGuide.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewGuide.Columns.AddRange(new DataGridViewColumn[] { OrderStatus, ID });
dataGridViewGuide.EditMode = DataGridViewEditMode.EditOnF2;
dataGridViewGuide.Location = new Point(12, 11);
dataGridViewGuide.MultiSelect = false;
dataGridViewGuide.Name = "dataGridViewGuide";
dataGridViewGuide.RowHeadersVisible = false;
dataGridViewGuide.RowHeadersWidth = 51;
dataGridViewGuide.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewGuide.Size = new Size(282, 411);
dataGridViewGuide.TabIndex = 0;
dataGridViewGuide.CellEndEdit += dataGridViewGuide_CellEndEdit;
dataGridViewGuide.CellValidating += dataGridViewGuide_CellValidating;
dataGridViewGuide.KeyDown += dataGridViewGuide_KeyDown;
//
// ID
//
ID.HeaderText = "Id";
ID.MinimumWidth = 6;
ID.Name = "Id";
ID.Visible = false;
//
// OrderStatus
//
OrderStatus.HeaderText = "Статус заказа";
OrderStatus.MinimumWidth = 6;
OrderStatus.Name = "OrderStatus";
//
// FormGuide
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(306, 435);
Controls.Add(dataGridViewGuide);
Name = "FormGuide";
Text = "Справочник";
((System.ComponentModel.ISupportInitialize)dataGridViewGuide).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridViewGuide;
private DataGridViewTextBoxColumn OrderStatus;
private DataGridViewTextBoxColumn ID;
}
}

View File

@ -0,0 +1,140 @@
using ShopBusinessLogic;
using ShopContracts.BindingModels;
using ShopContracts.BusinessLogicContracts;
using ShopContracts.SearchModels;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AppShopInternetOption19.Forms
{
public partial class FormGuide : Form
{
private readonly IOrderStatusLogic _orderStatusLogic;
public FormGuide(IOrderStatusLogic orderStatusLogic)
{
_orderStatusLogic = orderStatusLogic;
InitializeComponent();
LoadData();
}
private void LoadData()
{
try
{
var orderStatuses = _orderStatusLogic.ReadList(null);
if (orderStatuses != null)
{
dataGridViewGuide.Rows.Clear();
foreach (var status in orderStatuses)
{
dataGridViewGuide.Rows.Add(status.Name, status.Id);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridViewGuide_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.KeyCode == Keys.Insert)
{
dataGridViewGuide.Rows.Add();
dataGridViewGuide.CurrentCell = dataGridViewGuide.Rows[dataGridViewGuide.Rows.Count - 1].Cells["OrderStatus"]; // Ставим фокус на новую строку
e.Handled = true;
}
if (e.KeyCode == Keys.Delete)
{
if (dataGridViewGuide.SelectedRows.Count == 1)
{
DataGridViewRow currentRow = dataGridViewGuide.SelectedRows[0];
if (currentRow.Cells["Id"].Value != null || Convert.ToInt32(currentRow.Cells["Id"].Value) != 0)
{
var result = MessageBox.Show(
"Уверены???? удалю ведь щас",
"Подтверждение",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question
);
if (result == DialogResult.Yes)
{
_orderStatusLogic.Delete(new OrderStatusBindingModel { Id = Convert.ToInt32(currentRow.Cells["Id"].Value) });
MessageBox.Show("Ну все, успешно удалено");
LoadData();
}
else
{
MessageBox.Show("Ну не удаляй значит :/", "хммм", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
else
{
MessageBox.Show("ну тут нечего удалять", "алё", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void dataGridViewGuide_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
string? userInput = e.FormattedValue.ToString();
if (string.IsNullOrWhiteSpace(userInput))
{
MessageBox.Show("Ну ты не торопись давай, пустую запись сохранять низя Э", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
e.Cancel = true;
}
}
private void dataGridViewGuide_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
DataGridViewRow currentRow = dataGridViewGuide.Rows[e.RowIndex];
if (currentRow.Cells["Id"].Value == null || Convert.ToInt32(currentRow.Cells["Id"].Value) == 0)
{
_orderStatusLogic.Create(new OrderStatusBindingModel
{
Name = currentRow.Cells["OrderStatus"].Value.ToString()!,
});
}
else
{
_orderStatusLogic.Update(new OrderStatusBindingModel
{
Id = Convert.ToInt32(currentRow.Cells["Id"].Value),
Name = currentRow.Cells["OrderStatus"].Value.ToString(),
});
}
MessageBox.Show("Ура, успешно сохранена новая запись");
}
catch (Exception ex)
{
MessageBox.Show("Э ты ЧО на" + ex.Message);
}
}
}
}

View File

@ -0,0 +1,126 @@
<?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="OrderStatus.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
<metadata name="ID.UserAddedColumn" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>

View File

@ -0,0 +1,151 @@
namespace AppShopInternetOption19
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
userControlTreeView = new Components.UserControlTreeView();
menuStrip1 = new MenuStrip();
добавитьToolStripMenuItem = new ToolStripMenuItem();
редактироватьToolStripMenuItem = new ToolStripMenuItem();
удалитьToolStripMenuItem = new ToolStripMenuItem();
созданиеПростогоДокументаToolStripMenuItem = new ToolStripMenuItem();
сОзданиеДоктаСТаблицейToolStripMenuItem = new ToolStripMenuItem();
созданиеДоктаСДиаграммойToolStripMenuItem = new ToolStripMenuItem();
справочникToolStripMenuItem = new ToolStripMenuItem();
createWord = new UserComponentsOption19.BigTextWordNoVisibleComponent(components);
createExcelPieDiagram = new Components.ComponentExcelWithPieDiagram(components);
createPdfTable = new WinFormsLibrary1.PDFTable(components);
menuStrip1.SuspendLayout();
SuspendLayout();
//
// userControlTreeView
//
userControlTreeView.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
userControlTreeView.BackColor = SystemColors.ActiveCaption;
userControlTreeView.Location = new Point(1, 35);
userControlTreeView.Margin = new Padding(3, 4, 3, 4);
userControlTreeView.Name = "userControlTreeView";
userControlTreeView.SelectedIndex = -1;
userControlTreeView.Size = new Size(1278, 428);
userControlTreeView.TabIndex = 0;
userControlTreeView.Load += FormMain_Load;
//
// menuStrip1
//
menuStrip1.ImageScalingSize = new Size(20, 20);
menuStrip1.Items.AddRange(new ToolStripItem[] { добавитьToolStripMenuItem, редактироватьToolStripMenuItem, удалитьToolStripMenuItem, созданиеПростогоДокументаToolStripMenuItem, сОзданиеДоктаСТаблицейToolStripMenuItem, созданиеДоктаСДиаграммойToolStripMenuItem, справочникToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1291, 28);
menuStrip1.TabIndex = 1;
menuStrip1.Text = "menuStrip1";
//
// добавитьToolStripMenuItem
//
добавитьToolStripMenuItem.Name = обавитьToolStripMenuItem";
добавитьToolStripMenuItem.Size = new Size(90, 24);
добавитьToolStripMenuItem.Text = "Добавить";
добавитьToolStripMenuItem.Click += добавитьToolStripMenuItem_Click;
//
// редактироватьToolStripMenuItem
//
редактироватьToolStripMenuItem.Name = "редактироватьToolStripMenuItem";
редактироватьToolStripMenuItem.Size = new Size(125, 24);
редактироватьToolStripMenuItem.Text = "Редактировать";
редактироватьToolStripMenuItem.Click += редактироватьToolStripMenuItem_Click;
//
// удалитьToolStripMenuItem
//
удалитьToolStripMenuItem.Name = "удалитьToolStripMenuItem";
удалитьToolStripMenuItem.Size = new Size(79, 24);
удалитьToolStripMenuItem.Text = "Удалить";
удалитьToolStripMenuItem.Click += удалитьToolStripMenuItem_Click;
//
// созданиеПростогоДокументаToolStripMenuItem
//
созданиеПростогоДокументаToolStripMenuItem.Name = "созданиеПростогоДокументаToolStripMenuItem";
созданиеПростогоДокументаToolStripMenuItem.Size = new Size(235, 24);
созданиеПростогоДокументаToolStripMenuItem.Text = "Создание простого документа";
созданиеПростогоДокументаToolStripMenuItem.Click += созданиеПростогоДокументаToolStripMenuItem_Click;
//
// сОзданиеДоктаСТаблицейToolStripMenuItem
//
сОзданиеДоктаСТаблицейToolStripMenuItem.Name = "сОзданиеДоктаСТаблицейToolStripMenuItem";
сОзданиеДоктаСТаблицейToolStripMenuItem.Size = new Size(219, 24);
сОзданиеДоктаСТаблицейToolStripMenuItem.Text = "Создание док-та с таблицей";
сОзданиеДоктаСТаблицейToolStripMenuItem.Click += сОзданиеДоктаСТаблицейToolStripMenuItem_Click;
//
// созданиеДоктаСДиаграммойToolStripMenuItem
//
созданиеДоктаСДиаграммойToolStripMenuItem.Name = "созданиеДоктаСДиаграммойToolStripMenuItem";
созданиеДоктаСДиаграммойToolStripMenuItem.Size = new Size(241, 24);
созданиеДоктаСДиаграммойToolStripMenuItem.Text = "Создание док-та с диаграммой";
созданиеДоктаСДиаграммойToolStripMenuItem.Click += созданиеДоктаСДиаграммойToolStripMenuItem_Click;
//
// справочникToolStripMenuItem
//
справочникToolStripMenuItem.Name = "справочникToolStripMenuItem";
справочникToolStripMenuItem.Size = new Size(108, 24);
справочникToolStripMenuItem.Text = "Справочник";
справочникToolStripMenuItem.Click += справочникToolStripMenuItem_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1291, 465);
Controls.Add(userControlTreeView);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormMain";
Text = "Главная форма";
Load += FormMain_Load;
KeyDown += FormMain_KeyDown;
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Components.UserControlTreeView userControlTreeView;
private MenuStrip menuStrip1;
private ToolStripMenuItem добавитьToolStripMenuItem;
private ToolStripMenuItem редактироватьToolStripMenuItem;
private ToolStripMenuItem удалитьToolStripMenuItem;
private ToolStripMenuItem созданиеПростогоДокументаToolStripMenuItem;
private ToolStripMenuItem сОзданиеДоктаСТаблицейToolStripMenuItem;
private ToolStripMenuItem созданиеДоктаСДиаграммойToolStripMenuItem;
private ToolStripMenuItem справочникToolStripMenuItem;
private UserComponentsOption19.BigTextWordNoVisibleComponent createWord;
private Components.ComponentExcelWithPieDiagram createExcelPieDiagram;
private WinFormsLibrary1.PDFTable createPdfTable;
}
}

View File

@ -0,0 +1,394 @@
using AppShopInternetOption19.Forms;
using Components;
using ShopContracts.BindingModels;
using ShopContracts.BusinessLogicContracts;
using ShopContracts.SearchModels;
using ShopDataBaseImplements.Models;
using System.Windows.Forms;
using UserComponentsOption19;
using WinFormsLibrary1;
using WinFormsLibrary1.HelperClasses;
namespace AppShopInternetOption19
{
public partial class FormMain : Form
{
private readonly IOrderLogic _orderLogic;
private readonly IOrderStatusLogic _orderStatusLogic;
public FormMain(IOrderLogic orderLogic, IOrderStatusLogic orderStatusLogic)
{
InitializeComponent();
_orderLogic = orderLogic;
_orderStatusLogic = orderStatusLogic;
this.KeyPreview = true;
LoadData();
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void äîáàâèòüToolStripMenuItem_Click(object sender, EventArgs e)
{
Add();
}
private void LoadData()
{
try
{
var orders = _orderLogic.ReadList(null);
if (orders == null)
{
return;
}
foreach (var order in orders)
{
if (order.OrderSumm == null || order.OrderSumm == string.Empty)
{
order.OrderSumm = "îïëà÷åíî ñêèäêàìè";
}
}
List<(string PropertyName, bool AlwaysCreateBranch)> hierarchy =
[
("OrderStatus", false),
("OrderSumm", false),
("Id", false),
("FIO", false),
];
userControlTreeView.SetHierarchy(hierarchy);
userControlTreeView.SetTreeObjects(orders);
}
catch (Exception ex)
{
MessageBox.Show($"{ex.Message}");
}
}
private void ðåäàêòèðîâàòüToolStripMenuItem_Click(object sender, EventArgs e)
{
Update();
}
private void óäàëèòüToolStripMenuItem_Click(object sender, EventArgs e)
{
Delete();
}
private void ñïðàâî÷íèêToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormGuide));
if (!(service is FormGuide form))
{
return;
}
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
private void Add()
{
var service = Program.ServiceProvider?.GetService(typeof(FormEdit_Add));
if (!(service is FormEdit_Add form))
{
return;
}
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
private void Update()
{
var service = Program.ServiceProvider?.GetService(typeof(FormEdit_Add));
if (!(service is FormEdit_Add form))
{
return;
}
var selectedOrder = userControlTreeView.GetObjectSelectedNode<OrderBindingModel>();
form.Id = Convert.ToInt32(selectedOrder.Id);
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
private void Delete()
{
try
{
var selectedOrder = userControlTreeView.GetObjectSelectedNode<OrderBindingModel>();
if (selectedOrder != null)
{
var result = MessageBox.Show(
"Óâåðåíû???? óäàëþ âåäü ùàñ",
"Ïîäòâåðæäåíèå",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question
);
if (result == DialogResult.Yes)
{
_orderLogic.Delete(new OrderBindingModel { Id = selectedOrder.Id });
MessageBox.Show("Íó âñå, óñïåøíî óäàëåíî");
LoadData();
}
else if (result == DialogResult.No)
{
MessageBox.Show("Îêåé, òîãäà äåëàéòå äàëüøå)", "Èíôîðìàöèÿ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
LoadData();
}
LoadData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void CreateWord()
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Word Documents (*.docx)|*.docx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
string title = "çàêàçû, êîòîðûå îïëà÷åíû ïîëíîñòüþ çà ñ÷åò ñêèäîê :D";
string[] data;
try
{
var orders = _orderLogic.ReadList(null);
if (orders != null)
{
// Ôèëüòðóåì çàêàçû, ãäå ñóììà çàêàçà ðàâíà null èëè ïóñòîé ñòðîêå
var freeOrders = orders
.Where(x => string.IsNullOrEmpty(x.OrderSumm))
.Select(x => $"ID: {x.Id}, ÔÈÎ: {x.FIO}, Ñòàòóñ çàêàçà: {x.OrderStatus}, Îïèñàíèå çàêàçà: {x.OrderDescription}")
.ToList();
if (freeOrders.Count == 0)
{
MessageBox.Show("Íåò çàêàçîâ, îïëà÷åííûõ ñêèäêàìè.");
return;
}
// Ïðåîáðàçóåì ñïèñîê â ìàññèâ ñòðîê äëÿ ïåðåäà÷è â ìåòîä
data = freeOrders.ToArray();
// Ñîçäàåì äîêóìåíò Word
createWord.CreateAndSaveDocument(filePath, title, data);
MessageBox.Show("Óñïåøíî :D ïðîâåðÿé íàëè÷èå ôàéëà...");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
private void CreateExcel()
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Excel Files (*.xlsx)|*.xlsx";
saveFileDialog.Title = "Ñîõðàíèòü äèàãðàììó â Excel";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
try
{
var orders = _orderLogic.ReadList(null);
if (orders == null || !orders.Any())
{
MessageBox.Show("Íåò äàííûõ äëÿ ñîçäàíèÿ äèàãðàììû.");
return;
}
var groupedData = orders
.Where(o => o.OrderSumm != null && o.OrderSumm != "" && o.OrderSumm != string.Empty)
.GroupBy(o => o.OrderStatus)
.Select(g => new ComponentExcelWithPieDiagram.ChartData
{
SeriesName = g.Key,
SeriesValue = g.Count()
})
.ToList();
if (!groupedData.Any())
{
MessageBox.Show("Íåò îïëà÷åííûõ çàêàçîâ.");
return;
}
string title = "Îïëà÷åííûå çàêàçû ïî ñòàòóñàì";
string diagramTitle = "Ðàñïðåäåëåíèå îïëà÷åííûõ çàêàçîâ";
createExcelPieDiagram.CreateExcelWithPieChart(
filePath,
title,
diagramTitle,
ComponentExcelWithPieDiagram.LegendPosition.Left,
groupedData
);
MessageBox.Show("Ôàéë óñïåøíî ñîçäàí.", "Èíôîðìàöèÿ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Îøèáêà ïðè ñîçäàíèè ôàéëà: {ex.Message}", "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void CreatePdf()
{
using (SaveFileDialog fileDialog = new SaveFileDialog())
{
fileDialog.Filter = "PDF Files (*.pdf)|*.pdf";
fileDialog.Title = "Ñîõðàíèòü äèàãðàììó â PDF";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = fileDialog.FileName;
string fileTitle = "Èíôîðìàöèÿ î çàêàçàõ";
try
{
var orders = _orderLogic.ReadList(null);
if (orders == null || !orders.Any())
{
MessageBox.Show("Íåò äàííûõ");
return;
}
List<string[,]> tables = new List<string[,]>();
string[,] tableData = new string[orders.Count + 1, 5];
// Øàïêà òàáëèöû
tableData[0, 0] = "Èäåíòèôèêàòîð";
tableData[0, 1] = "ÔÈÎ";
tableData[0, 2] = "Ñòàòóñ çàêàçà";
tableData[0, 3] = "Ñóììà çàêàçîâ";
tableData[0, 4] = "Îïèñàíèå";
for (int i = 0; i < orders.Count; i++)
{
var order = orders[i];
tableData[i + 1, 0] = order.Id.ToString();
tableData[i + 1, 1] = order.FIO;
tableData[i + 1, 2] = order.OrderStatus;
tableData[i + 1, 3] = string.IsNullOrWhiteSpace(order.OrderSumm)
? "Îïëà÷åí ñêèäêàìè"
: order.OrderSumm;
tableData[i + 1, 4] = order.OrderDescription;
}
tables.Add(tableData);
PdfDocumentData pdfData = new PdfDocumentData(filePath, fileTitle, tables);
createPdfTable.GeneratePdf(pdfData);
MessageBox.Show("Ôàéë óñïåøíî ñîçäàí.", "Èíôîðìàöèÿ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Îøèáêà ïðè ñîçäàíèè ôàéëà: {ex.Message}", "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
//private class PdfDocumentData
//{
// public string FileName { get; set; }
// public string DocumentTitle { get; set; }
// public List<string[,]> Tables { get; set; }
// public PdfDocumentData(string fileName, string documentTitle, List<string[,]> tables)
// {
// FileName = fileName ?? throw new ArgumentNullException("fileName");
// DocumentTitle = documentTitle ?? throw new ArgumentNullException("documentTitle");
// Tables = tables ?? throw new ArgumentNullException("tables");
// }
//}
private void FormMain_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control)
{
switch (e.KeyCode)
{
case Keys.A:
Add();
e.SuppressKeyPress = true;
break;
case Keys.U:
Update();
e.SuppressKeyPress = true;
break;
case Keys.D:
Delete();
e.SuppressKeyPress = true;
break;
case Keys.S:
CreateWord();
e.SuppressKeyPress = true;
break;
case Keys.C:
CreateExcel();
e.SuppressKeyPress = true;
break;
case Keys.T:
CreatePdf();
e.SuppressKeyPress = true;
break;
}
}
}
private void ñîçäàíèåÏðîñòîãîÄîêóìåíòàToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateWord();
}
private void ñÎçäàíèåÄîêòàÑÒàáëèöåéToolStripMenuItem_Click(object sender, EventArgs e)
{
CreatePdf();
}
private void ñîçäàíèåÄîêòàÑÄèàãðàììîéToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateExcel();
}
}
}

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="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="createWord.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>153, 17</value>
</metadata>
<metadata name="createExcelPieDiagram.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>444, 17</value>
</metadata>
<metadata name="createPdfTable.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>727, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,52 @@
using AppShopInternetOption19.Forms;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ShopBusinessLogic;
using ShopContracts.BusinessLogicContracts;
using ShopContracts.StorageContracts;
using ShopDataBaseImplements.Implements;
namespace AppShopInternetOption19
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
/// <summary>
/// </summary>
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<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
//option.AddNLog("nlog.config");
});
services.AddTransient<IOrderStorage, OrderStorage>();
services.AddTransient<IOrderStatusStorage, OrderStatusStorage>();
services.AddTransient<IOrderLogic, OrderLogic>();
services.AddTransient<IOrderStatusLogic, OrderStatusLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormEdit_Add>();
services.AddTransient<FormGuide>();
}
}
}

View File

@ -0,0 +1,39 @@
namespace FormPlugins
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "Form1";
}
#endregion
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,95 @@
using ShopContracts.BindingModels;
using ShopContracts.BusinessLogicContracts;
using ShopContracts.SearchModels;
using ShopContracts.StorageContracts;
using ShopContracts.ViewModels;
using System;
namespace ShopBusinessLogic
{
public class OrderLogic : IOrderLogic
{
IOrderStorage _orderStorage;
public OrderLogic(IOrderStorage orderStorage)
{
_orderStorage = orderStorage;
}
public bool Create(OrderBindingModel model)
{
CheckModel(model, false);
if (_orderStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Delete(OrderBindingModel model)
{
CheckModel(model, false);
if (_orderStorage.Delete(model) == null)
{
return false;
}
return true;
}
public OrderViewModel? ReadElement(OrderSearchModel model)
{
if (model == null)
{
return null;
}
var element = _orderStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public List<OrderViewModel>? ReadList(OrderSearchModel? model)
{
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
return null;
}
return list;
}
public bool Update(OrderBindingModel model)
{
CheckModel(model, false);
if (_orderStorage.Update(model) == null) { return false; }
return true;
}
private void CheckModel(OrderBindingModel model, bool param = true)
{
if (model == null)
{
throw new ArgumentNullException($"Объект \"{model}\" нулл");
}
if (!param)
{
return;
}
if (model.FIO == null || string.IsNullOrEmpty(model.FIO))
{
throw new ArgumentNullException("Что-то с именем клиента - его нет почему-то");
}
if (model.OrderStatus == null || string.IsNullOrEmpty(model.OrderStatus))
{
throw new ArgumentNullException("что-то со статусом заказа - его нет почему-то");
}
if(model.OrderSumm == null)
{
model.OrderSumm = "оплачено скидками";
}
}
}
}

View File

@ -0,0 +1,85 @@
using ShopContracts.BindingModels;
using ShopContracts.BusinessLogicContracts;
using ShopContracts.SearchModels;
using ShopContracts.StorageContracts;
using ShopContracts.ViewModels;
namespace ShopBusinessLogic
{
public class OrderStatusLogic : IOrderStatusLogic
{
IOrderStatusStorage _orderStorage;
public OrderStatusLogic(IOrderStatusStorage orderStorage)
{
_orderStorage = orderStorage;
}
public bool Create(OrderStatusBindingModel model)
{
CheckModel(model, false);
if (_orderStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Delete(OrderStatusBindingModel model)
{
CheckModel(model, false);
if (_orderStorage.Delete(model) == null)
{
return false;
}
return true;
}
public OrderStatusViewModel? ReadElement(OrderStatusSearchModel model)
{
if (model == null)
{
return null;
}
var element = _orderStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public List<OrderStatusViewModel>? ReadList(OrderStatusSearchModel? model)
{
var list = model == null ? _orderStorage.GetFullList() : _orderStorage.GetFilteredList(model);
if (list == null)
{
return null;
}
return list;
}
public bool Update(OrderStatusBindingModel model)
{
CheckModel(model, false);
if (_orderStorage.Update(model) == null) { return false; }
return true;
}
private void CheckModel(OrderStatusBindingModel model, bool param = true)
{
if (model == null)
{
throw new ArgumentNullException($"Объект \"{model}\" нулл");
}
if (!param)
{
return;
}
if (model.Name == null || string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Что-то с именем клиента - его нет почему-то");
}
}
}
}

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ShopContracts\ShopContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,13 @@
using ShopDataModels.Models;
namespace ShopContracts.BindingModels
{
public class OrderBindingModel : IOrderModel
{
public int Id { get; set; }
public string FIO { get; set; } = string.Empty;
public string OrderDescription { get; set; } = string.Empty;
public string OrderStatus { get; set; } = string.Empty;
public string? OrderSumm { get; set; } = null;
}
}

View File

@ -0,0 +1,10 @@
using ShopDataModels.Models;
namespace ShopContracts.BindingModels
{
public class OrderStatusBindingModel : IOrderStatusModel
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,15 @@
using ShopContracts.BindingModels;
using ShopContracts.SearchModels;
using ShopContracts.ViewModels;
namespace ShopContracts.BusinessLogicContracts
{
public interface IOrderLogic
{
List<OrderViewModel>? ReadList(OrderSearchModel? model);
OrderViewModel? ReadElement(OrderSearchModel model);
bool Create(OrderBindingModel model);
bool Update(OrderBindingModel model);
bool Delete(OrderBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using ShopContracts.BindingModels;
using ShopContracts.SearchModels;
using ShopContracts.ViewModels;
namespace ShopContracts.BusinessLogicContracts
{
public interface IOrderStatusLogic
{
List<OrderStatusViewModel>? ReadList(OrderStatusSearchModel? model);
OrderStatusViewModel? ReadElement(OrderStatusSearchModel model);
bool Create(OrderStatusBindingModel model);
bool Update(OrderStatusBindingModel model);
bool Delete(OrderStatusBindingModel model);
}
}

View File

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

View File

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

View File

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ShopDataModels\ShopDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,17 @@
using ShopContracts.BindingModels;
using ShopContracts.SearchModels;
using ShopContracts.ViewModels;
using System;
namespace ShopContracts.StorageContracts
{
public interface IOrderStatusStorage
{
List<OrderStatusViewModel> GetFullList();
List<OrderStatusViewModel> GetFilteredList(OrderStatusSearchModel model);
OrderStatusViewModel? GetElement(OrderStatusSearchModel model);
OrderStatusViewModel? Insert(OrderStatusBindingModel model);
OrderStatusViewModel? Update(OrderStatusBindingModel model);
OrderStatusViewModel? Delete(OrderStatusBindingModel model);
}
}

View File

@ -0,0 +1,17 @@
using ShopContracts.BindingModels;
using ShopContracts.SearchModels;
using ShopContracts.ViewModels;
using System;
namespace ShopContracts.StorageContracts
{
public interface IOrderStorage
{
List<OrderViewModel> GetFullList();
List<OrderViewModel> GetFilteredList(OrderSearchModel model);
OrderViewModel? GetElement(OrderSearchModel model);
OrderViewModel? Insert(OrderBindingModel model);
OrderViewModel? Update(OrderBindingModel model);
OrderViewModel? Delete(OrderBindingModel model);
}
}

View File

@ -0,0 +1,10 @@
using ShopDataModels.Models;
namespace ShopContracts.ViewModels
{
public class OrderStatusViewModel : IOrderStatusModel
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,13 @@
using ShopDataModels.Models;
namespace ShopContracts.ViewModels
{
public class OrderViewModel : IOrderModel
{
public int Id { get; set; }
public string FIO { get; set; } = string.Empty;
public string OrderDescription { get; set; } = string.Empty;
public string OrderStatus { get; set; } = string.Empty;
public string? OrderSumm { get; set; } = null;
}
}

View File

@ -0,0 +1,19 @@
using Microsoft.EntityFrameworkCore;
using ShopDataBaseImplements.Models;
namespace ShopDataBaseImplements
{
public class DataBase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=ShopInternetDB;Integrated Security=True;MultipleActiveResultSets=True;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Order> Orders { set; get; }
public virtual DbSet<OrderStatus> OrderStatuses { set; get; }
}
}

View File

@ -0,0 +1,90 @@
using ShopContracts.BindingModels;
using ShopContracts.SearchModels;
using ShopContracts.StorageContracts;
using ShopContracts.ViewModels;
using ShopDataBaseImplements.Models;
namespace ShopDataBaseImplements.Implements
{
public class OrderStatusStorage : IOrderStatusStorage
{
public OrderStatusViewModel? Delete(OrderStatusBindingModel model)
{
using var context = new DataBase();
var element = context.OrderStatuses.FirstOrDefault(x => x.Id == model.Id);
if (element == null)
{
return null;
}
context.OrderStatuses.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
public OrderStatusViewModel? GetElement(OrderStatusSearchModel model)
{
using var context = new DataBase();
if(model.Id == null)
{
return null;
}
return context.OrderStatuses.FirstOrDefault(x => x.Id != model.Id)?.GetViewModel;
}
public List<OrderStatusViewModel> GetFilteredList(OrderStatusSearchModel model)
{
var list = GetFullList();
if(list == null)
{
return null;
}
if (model.Id.HasValue)
{
list = list.Where(x => x.Id == model.Id).ToList();
}
return list;
}
public List<OrderStatusViewModel> GetFullList()
{
using var context = new DataBase();
return context.OrderStatuses.Select(x => x.GetViewModel).ToList();
}
public OrderStatusViewModel? Insert(OrderStatusBindingModel model)
{
using var context = new DataBase();
var element = OrderStatus.Create(model);
if(element == null)
{
return null;
}
context.OrderStatuses.Add(element);
context.SaveChanges();
return element.GetViewModel;
}
public OrderStatusViewModel? Update(OrderStatusBindingModel model)
{
using var context = new DataBase();
using var transaction = context.Database.BeginTransaction();
try
{
var element = context.OrderStatuses.FirstOrDefault(x => x.Id == model.Id);
if (element == null)
{
return null;
}
element.Update(model);
context.SaveChanges();
transaction.Commit();
return element.GetViewModel;
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
}

View File

@ -0,0 +1,86 @@
using ShopContracts.BindingModels;
using ShopContracts.SearchModels;
using ShopContracts.StorageContracts;
using ShopContracts.ViewModels;
using ShopDataBaseImplements.Models;
namespace ShopDataBaseImplements.Implements
{
public class OrderStorage : IOrderStorage
{
public OrderViewModel? Delete(OrderBindingModel model)
{
using var context = new DataBase();
var element = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if(element == null)
{
return null;
}
context.Orders.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
public OrderViewModel? GetElement(OrderSearchModel model)
{
using var context = new DataBase();
if(!model.Id.HasValue)
{
return null;
}
return context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public List<OrderViewModel> GetFilteredList(OrderSearchModel model)
{
var list = GetFullList();
if (model.Id.HasValue)
{
list = list.Where(x => x.Id == model.Id).ToList();
}
return list;
}
public List<OrderViewModel> GetFullList()
{
using var context = new DataBase();
return context.Orders.Select(x => x.GetViewModel).ToList();
}
public OrderViewModel? Insert(OrderBindingModel model)
{
using var context = new DataBase();
var element = Order.Create(model);
if(element == null)
{
return null;
}
context.Orders.Add(element);
context.SaveChanges();
return element.GetViewModel;
}
public OrderViewModel? Update(OrderBindingModel model)
{
using var context = new DataBase();
using var transaction = context.Database.BeginTransaction();
try
{
var element = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if(element == null)
{
return null;
}
element.Update(model);
context.SaveChanges();
transaction.Commit();
return element.GetViewModel;
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
}

View File

@ -0,0 +1,74 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using ShopDataBaseImplements;
#nullable disable
namespace ShopDataBaseImplements.Migrations
{
[DbContext(typeof(DataBase))]
[Migration("20241119173303_MigrationInit")]
partial class MigrationInit
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ShopDataBaseImplements.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("OrderDescription")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("OrderStatus")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("OrderSumm")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Orders");
});
modelBuilder.Entity("ShopDataBaseImplements.Models.OrderStatus", 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("OrderStatuses");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,53 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ShopDataBaseImplements.Migrations
{
/// <inheritdoc />
public partial class MigrationInit : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
FIO = table.Column<string>(type: "nvarchar(max)", nullable: false),
OrderDescription = table.Column<string>(type: "nvarchar(max)", nullable: false),
OrderStatus = table.Column<string>(type: "nvarchar(max)", nullable: false),
OrderSumm = table.Column<string>(type: "nvarchar(max)", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
});
migrationBuilder.CreateTable(
name: "OrderStatuses",
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_OrderStatuses", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Orders");
migrationBuilder.DropTable(
name: "OrderStatuses");
}
}
}

View File

@ -0,0 +1,71 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using ShopDataBaseImplements;
#nullable disable
namespace ShopDataBaseImplements.Migrations
{
[DbContext(typeof(DataBase))]
partial class DataBaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ShopDataBaseImplements.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("FIO")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("OrderDescription")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("OrderStatus")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("OrderSumm")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Orders");
});
modelBuilder.Entity("ShopDataBaseImplements.Models.OrderStatus", 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("OrderStatuses");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,52 @@
using ShopContracts.BindingModels;
using ShopContracts.ViewModels;
using ShopDataModels.Models;
using System.ComponentModel.DataAnnotations;
namespace ShopDataBaseImplements.Models
{
public class Order : IOrderModel
{
public int Id { get; set; }
[Required]
public string FIO { get; set; } = string.Empty;
[Required]
public string OrderDescription { get; set; } = string.Empty;
[Required]
public string OrderStatus { get; set; } = string.Empty;
public string? OrderSumm { get; set; } = null;
public static Order? Create(OrderBindingModel model)
{
return new Order
{
Id = model.Id,
FIO = model.FIO,
OrderDescription = model.OrderDescription,
OrderStatus = model.OrderStatus,
OrderSumm = model.OrderSumm ?? null,
};
}
public void Update(OrderBindingModel model)
{
FIO = model.FIO;
OrderDescription = model.OrderDescription;
OrderStatus = model.OrderStatus;
OrderSumm = model.OrderSumm ?? null;
}
public OrderViewModel GetViewModel => new()
{
Id = Id,
FIO = FIO,
OrderDescription = OrderDescription,
OrderStatus = OrderStatus,
OrderSumm = OrderSumm ?? null,
};
}
}

View File

@ -0,0 +1,31 @@
using ShopContracts.BindingModels;
using ShopContracts.ViewModels;
using ShopDataModels.Models;
using System.ComponentModel.DataAnnotations;
namespace ShopDataBaseImplements.Models
{
public class OrderStatus : IOrderStatusModel
{
public int Id { get; set; }
[Required]
public string Name { get; set; } = string.Empty;
public static OrderStatus? Create(OrderStatusBindingModel model)
{
return new OrderStatus { Id = model.Id, Name = model.Name };
}
public void Update(OrderStatusBindingModel model)
{
Name = model.Name;
}
public OrderStatusViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
};
}
}

View File

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

View File

@ -0,0 +1,11 @@
namespace ShopDataModels.Models
{
public interface IOrderModel
{
public int Id { get; set; }
public string FIO { get; set; }
public string OrderDescription { get; set; }
public string OrderStatus { get; set; }
public string? OrderSumm { get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace ShopDataModels.Models
{
public interface IOrderStatusModel
{
int Id { get; set; }
string Name { get; set; }
}
}

View File

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

View File

@ -0,0 +1,92 @@
namespace TestAppForCheckComponentsWorking
{
partial class FormTestNoVisibleComponents
{
/// <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();
buttonSaveBigTextToWord = new Button();
bigTextWordNoVisibleComponent = new UserComponentsOption19.BigTextWordNoVisibleComponent(components);
tableWordNoVisibleComponent = new UserComponentsOption19.TableWordNoVisibleComponent(components);
buttonSaveTableToWord = new Button();
diagramWordNoVisibleComponent1 = new UserComponentsOption19.DiagramWordNoVisibleComponent(components);
buttonSaveDiagram = new Button();
SuspendLayout();
//
// buttonSaveBigTextToWord
//
buttonSaveBigTextToWord.Location = new Point(12, 21);
buttonSaveBigTextToWord.Name = "buttonSaveBigTextToWord";
buttonSaveBigTextToWord.Size = new Size(270, 29);
buttonSaveBigTextToWord.TabIndex = 0;
buttonSaveBigTextToWord.Text = "Сохранить большой текст в ворд :)";
buttonSaveBigTextToWord.UseVisualStyleBackColor = true;
buttonSaveBigTextToWord.Click += buttonSaveBigTextToWord_Click;
//
// buttonSaveTableToWord
//
buttonSaveTableToWord.Location = new Point(12, 81);
buttonSaveTableToWord.Name = "buttonSaveTableToWord";
buttonSaveTableToWord.Size = new Size(270, 29);
buttonSaveTableToWord.TabIndex = 1;
buttonSaveTableToWord.Text = "Сохранить таблицу в ворд :>";
buttonSaveTableToWord.UseVisualStyleBackColor = true;
buttonSaveTableToWord.Click += buttonSaveTableToWord_Click;
//
// buttonSaveDiagram
//
buttonSaveDiagram.Location = new Point(12, 142);
buttonSaveDiagram.Name = "buttonSaveDiagram";
buttonSaveDiagram.Size = new Size(270, 29);
buttonSaveDiagram.TabIndex = 2;
buttonSaveDiagram.Text = "Сохранить диаграмму в ворд :>";
buttonSaveDiagram.UseVisualStyleBackColor = true;
buttonSaveDiagram.Click += buttonSaveDiagram_Click;
//
// FormTestNoVisibleComponents
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(433, 383);
Controls.Add(buttonSaveDiagram);
Controls.Add(buttonSaveTableToWord);
Controls.Add(buttonSaveBigTextToWord);
Name = "FormTestNoVisibleComponents";
Text = "FormTestNoVisibleComponents";
ResumeLayout(false);
}
#endregion
private Button buttonSaveBigTextToWord;
private UserComponentsOption19.BigTextWordNoVisibleComponent bigTextWordNoVisibleComponent;
private UserComponentsOption19.TableWordNoVisibleComponent tableWordNoVisibleComponent;
private Button buttonSaveTableToWord;
private UserComponentsOption19.DiagramWordNoVisibleComponent diagramWordNoVisibleComponent1;
private Button buttonSaveDiagram;
}
}

View File

@ -0,0 +1,168 @@
using UserComponentsOption19;
namespace TestAppForCheckComponentsWorking
{
public partial class FormTestNoVisibleComponents : Form
{
public FormTestNoVisibleComponents()
{
InitializeComponent();
}
private void buttonSaveBigTextToWord_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Word Documents (*.docx)|*.docx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
string title = "ХОБА давай знакомиться! :D";
string[] data = { "Привет, я Саня", "НЕт... это я Саня..", "чЮваки... будьте спокойнее _~_" };
bigTextWordNoVisibleComponent.CreateAndSaveDocument(filePath, title, data);
MessageBox.Show("Успешно :D проверяй скорее наличие файла...");
}
}
}
private void buttonSaveTableToWord_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Word Documents (*.docx)|*.docx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
var dataList = new List<Employee>{
new Employee { Id = 1, Status = "нет", FirstName = "Иван", LastName = "Иванов", Age = 34, Children = "нет", Car = "есть", Position = "Инж.", Departament = "Деп.", Bonus = 2000.1 },
new Employee { Id = 2, Status = "есть", FirstName = "Петр", LastName = "Петров", Age = 44, Children = "есть", Car = "есть", Position = "Инж.", Departament = "Деп.", Bonus = 2000.1 },
new Employee { Id = 3, Status = "да", FirstName = "Сергей", LastName = "Сергеев", Age = 55, Children = "да", Car = "есть", Position = "Рук.", Departament = "Деп.", Bonus = 5000.5 },
new Employee { Id = 4, Status = "есть", FirstName = "Ольга", LastName = "Иванова", Age = 34, Children = "есть", Car = "нет", Position = "Бух.", Departament = "Бухг.", Bonus = 2000.1 },
new Employee { Id = 5, Status = "да", FirstName = "Татьяна", LastName = "Петрова", Age = 44, Children = "да", Car = "нет", Position = "Ст. бух.", Departament = "Бухг.", Bonus = 7000.6 }
};
List<(float columnWidth, string headerRowCell1, string headerRowCell2, string property)> columnWidths = new List<(float, string, string, string)>
{
(1.0f, "Идент.", "Идент.", "Id"),
(2.0f, "Статус.", "Статус", "Status" ),
(2.0f, "Личные данные.", "Имя.", "FirstName"),
(3.0f, "Личные данные.", "Фамилия.", "LastName" ),
(2.0f, "Личные данные.", "Возраст.", "Age"),
(2.0f, "Дети.", "Дети.", "Children" ),
(2.0f, "Машина.", "Машина.", "Car" ),
(3.0f, "Работа.", "Должность.", "Position" ),
(3.0f, "Работа.", "Подразделение.", "Departament"),
(3.0f, "Премия.", "Премия.", "Bonus" ),
};
var columnPropertyMapping = new Dictionary<int, string>
{
{ 0, "Id" },
{ 1, "Status" },
{ 2, "FirstName" },
{ 3, "LastName" },
{ 4, "Age" },
{ 5, "Children" },
{ 6, "Car" },
{ 7, "Position"},
{ 8, "Departament" },
{ 9, "Bonus" }
};
string[] headerRow1 = { "Идент.", "Статус", "Личные данные", "Личные данные", "Личные данные", "Дети", "Машина", "Работа", "Работа", "Премия" };
string[] headerRow2 = { "Идент.", "Статус", "Имя", "Фамилия", "Возраст", "Дети", "Машина", "Должность", "Подразделение", "Премия" };
var headerTitles = new List<string[]>
{
new[] { "Идент.", "Статус", "Личные данные", "Личные данные", "Личные данные", "Дети", "Машина", "Работа", "Работа", "Премия" },
new[] { "Идент.", "Статус", "Имя", "Фамилия", "Возраст", "Дети", "Машина", "Должность", "Подразделение", "Премия" }
};
//var columnWidths = new List<float> { 3.0f, 3.0f, 2.0f, 2.0f, 2.0f, 2.0f, 3.0f, 3.0f, 2.0f, 2.0f };
var columnMerges = new List<(int StartColumn, int EndColumn)>
{
(2, 4), // Объединяем "Личные данные" на три столбца
(7, 8) // Объединяем "Работа" на два столбца
};
tableWordNoVisibleComponent.CreateTableInWordDocument(filePath, "Оп... какие-то рабы", columnMerges, columnWidths,
dataList);
//tableWordNoVisibleComponent.CreateWordTestTable(filePath);
MessageBox.Show("Успешно :D проверяй скорее наличие файла...");
}
}
}
public class Employee
{
public int Id { get; set; }
public string Status { get; set; } = string.Empty;
public string FirstName { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
public int Age { get; set; }
public string Children { get; set; } = string.Empty;
public string Car { get; set; } = string.Empty;
public string Departament { get; set; } = string.Empty;
public string Position { get; set; } = string.Empty;
public double Bonus { get; set; }
}
private void buttonSaveDiagram_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "Word Documents (*.docx)|*.docx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
string title = "ХОБА давай знакомиться! :D";
var chartData = new List<DiagramWordNoVisibleComponent.ChartSeries>
{
new DiagramWordNoVisibleComponent.ChartSeries
{
Name = "Ем пельмени день 1",
Data = new List<double> { 10, 5, 30, 4, 2 }
},
new DiagramWordNoVisibleComponent.ChartSeries
{
Name = "Ем пельмени день 2",
Data = new List<double> { 15, 5, 25, 10, 1 }
},
new DiagramWordNoVisibleComponent.ChartSeries
{
Name = "Ем пельмени день 3",
Data = new List<double> { 20, 30, 40, 50, 60 }
}
};
diagramWordNoVisibleComponent1.CreateDocumentWithChart(filePath, title, "Diagram", DiagramWordNoVisibleComponent.LegendPosition.Bottom,
chartData);
MessageBox.Show("Успешно :D проверяй скорее наличие файла...");
}
}
}
}
}

View File

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

View File

@ -0,0 +1,93 @@
namespace TestAppForCheckComponentsWorking
{
partial class FormTest
{
/// <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()
{
selectComponent = new UserComponentsOption19.SelectComponent();
writeComponent = new UserComponentsOption19.WriteComponent();
listComponent = new UserComponentsOption19.ListComponent();
button = new Button();
SuspendLayout();
//
// selectComponent
//
selectComponent.Location = new Point(12, 12);
selectComponent.Name = "selectComponent";
selectComponent.SelectedValue = "";
selectComponent.Size = new Size(189, 36);
selectComponent.TabIndex = 0;
//
// writeComponent
//
writeComponent.Location = new Point(12, 65);
writeComponent.Name = "writeComponent";
writeComponent.Size = new Size(324, 44);
writeComponent.TabIndex = 1;
writeComponent.Template = null;
//
// listComponent
//
listComponent.Location = new Point(16, 120);
listComponent.Name = "listComponent";
listComponent.SelectedIndex = -1;
listComponent.Size = new Size(406, 315);
listComponent.TabIndex = 2;
listComponent.ChangeSelectedItem += ChangeSelectedItem;
//
// button
//
button.Location = new Point(414, 65);
button.Name = "button";
button.Size = new Size(94, 29);
button.TabIndex = 3;
button.Text = "button1";
button.UseVisualStyleBackColor = true;
button.Click += button_Click;
//
// FormTest
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(635, 533);
Controls.Add(button);
Controls.Add(listComponent);
Controls.Add(writeComponent);
Controls.Add(selectComponent);
Name = "FormTest";
Text = "нукась протестируем...";
ResumeLayout(false);
}
#endregion
private UserComponentsOption19.SelectComponent selectComponent;
private UserComponentsOption19.WriteComponent writeComponent;
private UserComponentsOption19.ListComponent listComponent;
private Button button;
}
}

View File

@ -0,0 +1,111 @@
using System.Text.RegularExpressions;
using UserComponentsOption19;
namespace TestAppForCheckComponentsWorking
{
public partial class FormTest : Form
{
public List<string> testList = new List<string>();
Random rand = new Random();
public FormTest()
{
InitializeComponent();
FillList(19);
SetTemplate();
FillListBox();
}
private void SelectComponent_SelectComponentChanged(object? sender, EventArgs e)
{
MessageBox.Show("íó âûçâàë òû ìåíÿ, è ÷òî äàëüøå?");
}
private void FillList(int num)
{
for (int i = 0; i <= num; i++)
{
testList.Add("ß ñúåì " + i.ToString() + " àðáóçîâ!");
}
selectComponent.FillList(testList);
}
Regex regex = new Regex(@"^[^@\s]+@[^@\s]+\.(com|net|org|gov|ru)$");
public void SetTemplate()
{
writeComponent.Template = regex;
writeComponent.SetTextTooltip("email@email.ru");
try
{
//writeComponent.WriteTextInTextBox.ToString();
//writeComponent.WriteTextInTextBox = writeComponent.WriteTextInTextBox.ToString();
writeComponent.WriteTextInTextBox = "email@email.com";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button_Click(object sender, EventArgs e)
{
try
{
writeComponent.WriteTextInTextBox.ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public class Cat()
{
public int? Age { get; set; }
public string? Name { get; set; }
}
public void FillListBox()
{
try
{
listComponent.FillTemplateString("Êîò: (Name), âîçðàñò: (Age)", "(", ")");
for (int i = 0; i <= 10; i++)
{
Cat cat = new Cat();
cat.Name = "kitti" + i.ToString();
cat.Age = i;
listComponent.AddObjectToListBox(cat);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ChangeSelectedItem(object sender, EventArgs e)
{
var newCat = listComponent.GetObjectFromSelectedRow<Cat>();
if (newCat != null)
{
MessageBox.Show(newCat.Name);
MessageBox.Show(newCat.Age.ToString());
}
string placeHolder = "(Name)";
//listComponent.GetNameOfProperty("Êîò ñ èìåíåì (Name)", placeHolder);
}
}
}

View File

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

View File

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

View File

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

View File

@ -0,0 +1,61 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.9.34714.143
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UserComponentsOption19", "UserComponentsOption19\UserComponentsOption19.csproj", "{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestAppForCheckComponentsWorking", "TestAppForCheckComponentsWorking\TestAppForCheckComponentsWorking.csproj", "{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AppShopInternetOption19", "AppShopInternetOption19\AppShopInternetOption19.csproj", "{C750EB42-23CA-434F-80AE-CBAF146C403B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShopBusinessLogic", "ShopBusinessLogic\ShopBusinessLogic.csproj", "{F4916AFC-E68D-487E-9FEB-D343502DD046}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShopContracts", "ShopContracts\ShopContracts.csproj", "{2A049430-7407-4B2C-8C77-5D360023C5D7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShopDataBaseImplements", "ShopDataBaseImplements\ShopDataBaseImplements.csproj", "{F154F51B-C281-48CC-8BD5-DE94EBA81727}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ShopDataModels", "ShopDataModels\ShopDataModels.csproj", "{92FD9A75-09F0-48B2-AA7B-D14CF96A9030}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1BB1E87C-D5E4-41A6-9303-0F3E00F00507}.Release|Any CPU.Build.0 = Release|Any CPU
{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B5178B4-8A7C-4896-BC0C-6B0F6476B0B8}.Release|Any CPU.Build.0 = Release|Any CPU
{C750EB42-23CA-434F-80AE-CBAF146C403B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C750EB42-23CA-434F-80AE-CBAF146C403B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C750EB42-23CA-434F-80AE-CBAF146C403B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C750EB42-23CA-434F-80AE-CBAF146C403B}.Release|Any CPU.Build.0 = Release|Any CPU
{F4916AFC-E68D-487E-9FEB-D343502DD046}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F4916AFC-E68D-487E-9FEB-D343502DD046}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F4916AFC-E68D-487E-9FEB-D343502DD046}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F4916AFC-E68D-487E-9FEB-D343502DD046}.Release|Any CPU.Build.0 = Release|Any CPU
{2A049430-7407-4B2C-8C77-5D360023C5D7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2A049430-7407-4B2C-8C77-5D360023C5D7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2A049430-7407-4B2C-8C77-5D360023C5D7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2A049430-7407-4B2C-8C77-5D360023C5D7}.Release|Any CPU.Build.0 = Release|Any CPU
{F154F51B-C281-48CC-8BD5-DE94EBA81727}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F154F51B-C281-48CC-8BD5-DE94EBA81727}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F154F51B-C281-48CC-8BD5-DE94EBA81727}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F154F51B-C281-48CC-8BD5-DE94EBA81727}.Release|Any CPU.Build.0 = Release|Any CPU
{92FD9A75-09F0-48B2-AA7B-D14CF96A9030}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{92FD9A75-09F0-48B2-AA7B-D14CF96A9030}.Debug|Any CPU.Build.0 = Debug|Any CPU
{92FD9A75-09F0-48B2-AA7B-D14CF96A9030}.Release|Any CPU.ActiveCfg = Release|Any CPU
{92FD9A75-09F0-48B2-AA7B-D14CF96A9030}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {5466B454-D3BC-46EA-8960-7193721A5CF0}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,36 @@
namespace UserComponentsOption19
{
partial class BigTextWordNoVisibleComponent
{
/// <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,61 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.ComponentModel;
// КОМПОНЕНТ С БОЛЬШИМ... ТЕКСТОМ
namespace UserComponentsOption19
{
public partial class BigTextWordNoVisibleComponent : Component
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
public BigTextWordNoVisibleComponent()
{
InitializeComponent();
}
public BigTextWordNoVisibleComponent(IContainer container) : this()
{
container.Add(this);
}
public void CreateAndSaveDocument(string filePath, string title, string[] data)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException(nameof(filePath), "Укажите путь к файлу :_3");
}
if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException(nameof(title), "Заголовок документа не заполнен...");
}
if (data == null || data.Length == 0)
{
throw new ArgumentNullException(nameof(data), "Массив строк где, Алеша? >:/");
}
using (_wordDocument = WordprocessingDocument.Create(filePath, WordprocessingDocumentType.Document))
{
var mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
var titleParagraph = new Paragraph(new Run(new Text(title)));
titleParagraph.ParagraphProperties = new ParagraphProperties(
new Justification() { Val = JustificationValues.Center },
new Bold());
_docBody.AppendChild(titleParagraph);
_docBody.AppendChild(new Paragraph());
foreach (var paragraphText in data)
{
var paragraph = new Paragraph(new Run(new Text(paragraphText)));
_docBody.AppendChild(paragraph);
}
mainPart.Document.Save();
}
}
}
}

View File

@ -0,0 +1,36 @@
namespace UserComponentsOption19
{
partial class DiagramWordNoVisibleComponent
{
/// <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,127 @@
using System.ComponentModel;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
namespace UserComponentsOption19
{
public partial class DiagramWordNoVisibleComponent : Component
{
public DiagramWordNoVisibleComponent()
{
InitializeComponent();
}
public DiagramWordNoVisibleComponent(IContainer container) : this()
{
container.Add(this);
}
// Перечисление для позиции легенды
public enum LegendPosition
{
Top,
Bottom,
Left,
Right
}
// Класс для представления серии данных
public class ChartSeries
{
public string? Name { get; set; }
public List<double>? Data { get; set; }
}
// Основной метод для создания документа с диаграммой
public void CreateDocumentWithChart(
string fileName,
string documentTitle,
string chartTitle,
LegendPosition legendPosition,
List<ChartSeries> chartData
)
{
// Проверка входных данных
if (
string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(documentTitle) ||
chartData == null || chartData.Count == 0)
{
throw new ArgumentException("Некорректные входные данные: проверьте имя файла, заголовок документа и наличие данных для диаграммы.");
}
// Создаем Word документ
var wordApp = new Word.Application();
var document = wordApp.Documents.Add();
wordApp.Visible = false; // Скрыть приложение Word
// Добавляем заголовок документа
var titleRange = document.Range();
titleRange.Text = documentTitle;
titleRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
titleRange.Font.Size = 14; // Размер шрифта для заголовка
titleRange.InsertParagraphAfter();
// Создаём Excel для диаграммы
var excelApp = new Excel.Application();
var workbook = excelApp.Workbooks.Add();
var worksheet = (Excel.Worksheet)workbook.Worksheets[1];
// Заполняем данные для диаграммы
int seriesCount = chartData.Count;
int dataCount = chartData[0].Data.Count;
// Заголовки серий
for (int i = 0; i < seriesCount; i++)
{
worksheet.Cells[1, i + 1] = chartData[i].Name; // Заполнение заголовков
for (int j = 0; j < dataCount; j++)
{
worksheet.Cells[j + 2, i + 1] = chartData[i].Data[j]; // Заполнение данных
}
}
// Создание диаграммы
var chartObject = (Excel.ChartObject)worksheet.ChartObjects().Add(100, 100, 300, 200);
var chart = chartObject.Chart;
chart.SetSourceData(worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[dataCount + 1, seriesCount]]);
chart.ChartType = Excel.XlChartType.xlLine; // Линейная диаграмма
chart.HasTitle = true;
chart.ChartTitle.Text = chartTitle;
// Установка позиции легенды
switch (legendPosition)
{
case LegendPosition.Top:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionTop;
break;
case LegendPosition.Bottom:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionBottom;
break;
case LegendPosition.Left:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionLeft;
break;
case LegendPosition.Right:
chart.Legend.Position = Excel.XlLegendPosition.xlLegendPositionRight;
break;
}
// Копирование диаграммы в буфер обмена
chartObject.Copy();
// Вставка диаграммы в документ Word
var range = document.Content;
range.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
range.Paste();
// Сохраняем документ
document.SaveAs2(fileName);
document.Close();
wordApp.Quit();
// Закрываем Excel
workbook.Close(false);
excelApp.Quit();
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UserComponentsOption19
{
internal class InvalidInputException : Exception
{
public InvalidInputException(string message) : base (message) { }
}
}

View File

@ -0,0 +1,58 @@
namespace UserComponentsOption19
{
partial class ListComponent
{
/// <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()
{
listBox = new ListBox();
SuspendLayout();
//
// listBox
//
listBox.BackColor = Color.Honeydew;
listBox.FormattingEnabled = true;
listBox.Location = new Point(3, 3);
listBox.Name = "listBox";
listBox.Size = new Size(319, 244);
listBox.TabIndex = 0;
listBox.SelectedIndexChanged += listBox_SelectedIndexChanged;
//
// ListComponent
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(listBox);
Name = "ListComponent";
Size = new Size(325, 252);
ResumeLayout(false);
}
#endregion
private ListBox listBox;
}
}

View File

@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UserComponentsOption19
{
public partial class ListComponent : UserControl
{
private string? _templateString;
private string? _startPropertyChar;
private string? _endPropertyChar;
public event EventHandler? ChangeSelectedItem;
public ListComponent()
{
InitializeComponent();
}
/// <summary>
/// публичный метод заполнения макетной строки
/// </summary>
/// <param name="templateString"></param>
/// <param name="startPropertyChar"></param>
/// <param name="endPropertyChar"></param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="InvalidOperationException"></exception>
public void FillTemplateString(string templateString, string startPropertyChar, string endPropertyChar)
{
if (string.IsNullOrEmpty(templateString))
{
throw new ArgumentNullException("Введите макетную строку (не забудьте символы начала и конца свойства объекта :3)");
}
if (!templateString.Contains(startPropertyChar) || !templateString.Contains(endPropertyChar))
{
throw new InvalidOperationException("Вы не дописали символы начала и конца свойства объекта :_(");
}
_templateString = templateString;
_startPropertyChar = startPropertyChar;
_endPropertyChar = endPropertyChar;
}
/// <summary>
/// публичное свойство для получения/установки индекса строки
/// </summary>
public int SelectedIndex
{
get
{
if (listBox.SelectedIndex == -1) return -1;
return listBox.SelectedIndex;
}
set
{
if (listBox.SelectedIndex != -1)
{
listBox.SelectedIndex = value;
}
}
}
public T? GetObjectFromSelectedRow<T>() where T : class, new()
{
if (listBox.SelectedIndex == -1 || listBox.SelectedItem == null)
return null;
string? selectedString = listBox.SelectedItem.ToString();
T obj = new T();
Type objectType = typeof(T);
string selString = selectedString;
string tempString = _templateString;
List<string> arraySubstrings = new List<string>();
List<string> arrayPropertyNames = new List<string>();
List<string> Properties = new List<string>();
// заполняем массив сабстрингов
int index = 0;
int indexChar = 0;
for (int i = 0; i < tempString.Length; i++)
{
if (tempString[i] == _startPropertyChar[0])
{
indexChar = i;
arraySubstrings.Add(tempString.Substring(index, indexChar - index));
}
if (tempString[i] == _endPropertyChar[0])
{
index = i + 1;
}
}
// заполняем массив значений свойств
int d = 0;
for (int i = 0; i < arraySubstrings.Count; i++)
{
int startIndex = selString.IndexOf(arraySubstrings[i]) + arraySubstrings[i].Length - 1;
if (!(i + 1 >= arraySubstrings.Count))
{
int endIndex = selString.IndexOf(arraySubstrings[i + 1]);
string value = selString.Substring(startIndex, endIndex - startIndex);
Properties.Add(value);
d++;
}
}
if (d < arraySubstrings.Count)
{
int indexLastNameProperty = selString.IndexOf(arraySubstrings[arraySubstrings.Count - 1])
+ arraySubstrings[arraySubstrings.Count - 1].Length;
Properties.Add(selString.Substring(indexLastNameProperty, selString.Length - indexLastNameProperty));
}
// заполняем массив имен свойств
for (int i = 0; i < tempString.Length; i++)
{
if (tempString[i] == _startPropertyChar[0])
{
index = i + 1;
}
if (tempString[i] == _endPropertyChar[0])
{
indexChar = i;
arrayPropertyNames.Add(tempString.Substring(index, indexChar - index));
}
}
foreach (var property in objectType.GetProperties())
{
int propertyIndex = arrayPropertyNames.IndexOf(property.Name);
if (propertyIndex >= 0 && propertyIndex < Properties.Count)
{
Type propertyType = property.PropertyType;
Type? underlyingType = Nullable.GetUnderlyingType(propertyType);
if (underlyingType != null)
{
object? converted = string.IsNullOrWhiteSpace(Properties[propertyIndex]) ? null : Convert.ChangeType(Properties[propertyIndex], underlyingType);
property.SetValue(obj, converted);
}
else
{
property.SetValue(obj, Convert.ChangeType(Properties[propertyIndex], property.PropertyType));
}
}
}
return obj;
}
public void AddObjectToListBox<T>(T? obj)
{
Type objectType = obj.GetType();
string result = _templateString;
foreach (var propertyInfo in objectType.GetProperties())
{
string placeholder = $"{_startPropertyChar}{propertyInfo.Name}{_endPropertyChar}";
var value = propertyInfo.GetValue(obj)?.ToString() ?? string.Empty;
result = result.Replace(placeholder, value);
}
listBox.Items.Add(result);
}
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
ChangeSelectedItem?.Invoke(this, e);
}
}
}

View File

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

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UserComponentsOption19
{
internal class NoTemplateException : Exception
{
public NoTemplateException(string message) : base (message) { }
}
}

View File

@ -0,0 +1,58 @@
namespace UserComponentsOption19
{
partial class SelectComponent
{
/// <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()
{
comboBox = new ComboBox();
SuspendLayout();
//
// comboBox
//
comboBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
comboBox.FormattingEnabled = true;
comboBox.Location = new Point(0, 0);
comboBox.Name = "comboBox";
comboBox.Size = new Size(151, 28);
comboBox.TabIndex = 0;
comboBox.SelectedIndexChanged += comboBox_SelectedIndexChanged;
//
// SelectComponent
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(comboBox);
Name = "SelectComponent";
Size = new Size(151, 29);
ResumeLayout(false);
}
#endregion
private ComboBox comboBox;
}
}

View File

@ -0,0 +1,55 @@
namespace UserComponentsOption19
{
public partial class SelectComponent : UserControl
{
public event EventHandler? SelectComponentChanged;
Random rand = new Random();
public SelectComponent()
{
InitializeComponent();
//comboBox.SelectedIndexChanged += comboBox_SelectedIndexChanged;
}
public void FillList<Y>(List<Y> list, string property) where Y : class
{
ClearList();
foreach (var item in list)
{
var propName = item.GetType().GetProperty(property);
if(propName != null)
{
var value = propName.GetValue(item)?.ToString();
comboBox.Items.Add(value);
}
}
//comboBox.SelectedIndex = rand.Next(list.Count);
}
public void ClearList()
{
comboBox.Items.Clear();
}
public string SelectedValue
{
get
{
return comboBox.SelectedItem?.ToString() ?? string.Empty;
}
set
{
comboBox.SelectedItem = value;
}
}
private void comboBox_SelectedIndexChanged(object sender, EventArgs e)
{
SelectComponentChanged?.Invoke(this, e);
}
}
}

View File

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

View File

@ -0,0 +1,36 @@
namespace UserComponentsOption19
{
partial class TableWordNoVisibleComponent
{
/// <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,139 @@
using System.ComponentModel;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
/// КОМПОНЕНТ С ТАБЛИЦЕЙ ГДЕ ШАПКА - ЭТО ПЕРВЫЕ ДВЕ СТРОКИ
namespace UserComponentsOption19
{
public partial class TableWordNoVisibleComponent : Component
{
public TableWordNoVisibleComponent()
{
InitializeComponent();
}
public TableWordNoVisibleComponent(IContainer container) : this()
{
container.Add(this);
}
public void CreateTableInWordDocument<T>(
string filePath,
string title,
List<(int start, int end)> mergeColumns,
List<(float columnWidth, string headerRowCell1, string headerRowCell2, string property)> columnWidths,
List<T> data) where T : class
{
// Проверка входных данных
ValidateInput(filePath, title, mergeColumns, columnWidths, data);
var wordApp = new Word.Application();
var document = wordApp.Documents.Add();
// Установка заголовка
document.Content.Text = title;
// Добавление таблицы
//var tableRange = document.Bookmarks["\\endofdoc"].Range;
var tableRange = document.Content;
Table table = document.Tables.Add(tableRange, data.Count + 2, columnWidths.Count);
table.Borders.Enable = 1;
// Заполнение данных
FillData(table, data, columnWidths);
// Заполнение заголовка
FillHeader(table, columnWidths, mergeColumns);
// Сохранение документа
document.SaveAs2(filePath);
document.Close();
wordApp.Quit();
}
private void ValidateInput<T>(
string filePath,
string title,
List<(int start, int end)> mergeColumns,
List<(float columnWidth, string headerRowCell1, string headerRowCell2, string property)> columnWidths,
List<T> data)
{
if (string.IsNullOrEmpty(filePath)) throw new ArgumentNullException("нужно ввести путь до файла");
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException("нужно ввести заголовок документа");
if (mergeColumns == null) throw new ArgumentNullException("где информация по объединению колонок?");
if (columnWidths == null) throw new ArgumentNullException("где информация по ширине колонок и заголовкам?");
if (data == null) throw new ArgumentNullException("все ввел, а данные забыл ввести? ну ты и умник");
}
private void FillHeader(
Table table,
List<(float columnWidth, string headerRowCell1, string headerRowCell2, string property)> columnWidths,
List<(int start, int end)> mergeColumns
)
{
for (int i = 0; i < columnWidths.Count; i++)
{
table.Cell(2, i + 1).Range.Text = columnWidths[i].headerRowCell2;
table.Columns[i + 1].Width = columnWidths[i].columnWidth * 20;
}
var sortDeskMergeColumns = mergeColumns.OrderByDescending(x => x.start);
List<int> notMergedColumns = new List<int>();
for (int i = 0; i < table.Columns.Count; i++)
{
notMergedColumns.Add(i);
}
for (int i = 0; i < table.Columns.Count; i++)
{
foreach (var item in mergeColumns)
{
if (i >= item.start && i <= item.end) notMergedColumns.Remove(i)
;
}
}
foreach (var item in notMergedColumns)
{
table.Cell(1, item + 1).Merge(table.Cell(2, item + 1));
table.Cell(1, item + 1).Range.Text = columnWidths[item].headerRowCell1;
}
foreach (var item in sortDeskMergeColumns)
{
table.Cell(1, item.start + 1).Merge(table.Cell(1, item.end + 1));
table.Cell(1, item.start + 1).Range.Text = columnWidths[item.start].headerRowCell1;
}
}
private void FillData<T>(Table table, List<T> data,
List<(float columnWidth, string headerRowCell1, string headerRowCell2, string property)> columnWidths
) where T : class
{
int rowIndex = 3;
foreach (var item in data)
{
for (int i = 0; i < columnWidths.Count; i++)
{
string propName = columnWidths[i].property;
var property = typeof(T).GetProperty(propName);
if (property != null)
{
var valueProp = property.GetValue(item)?.ToString() ?? string.Empty;
table.Cell(rowIndex, i + 1).Range.Text = valueProp;
}
else
{
table.Cell(rowIndex, i + 1).Range.Text = string.Empty;
}
}
rowIndex++;
}
}
}
}

View File

@ -0,0 +1,46 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
<COMReference Include="Microsoft.Office.Core">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>8</VersionMinor>
<VersionMajor>2</VersionMajor>
<Guid>2df8d04c-5bfa-101b-bde5-00aa0044de52</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
<COMReference Include="Microsoft.Office.Interop.Word">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>7</VersionMinor>
<VersionMajor>8</VersionMajor>
<Guid>00020905-0000-0000-c000-000000000046</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
<COMReference Include="Microsoft.Office.Interop.Excel">
<WrapperTool>tlbimp</WrapperTool>
<VersionMinor>9</VersionMinor>
<VersionMajor>1</VersionMajor>
<Guid>00020813-0000-0000-c000-000000000046</Guid>
<Lcid>0</Lcid>
<Isolated>false</Isolated>
<EmbedInteropTypes>true</EmbedInteropTypes>
</COMReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.0" />
<PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,57 @@
namespace UserComponentsOption19
{
partial class WriteComponent
{
/// <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.Location = new Point(3, 3);
textBox.Name = "textBox";
textBox.Size = new Size(310, 27);
textBox.TabIndex = 0;
textBox.TextChanged += textBox_TextChanged;
//
// WriteComponent
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(textBox);
Name = "WriteComponent";
Size = new Size(320, 35);
ResumeLayout(false);
PerformLayout();
}
#endregion
private TextBox textBox;
}
}

View File

@ -0,0 +1,74 @@
using System.Text.RegularExpressions;
namespace UserComponentsOption19
{
public partial class WriteComponent : UserControl
{
private Regex? regex;
private ToolTip toolTipTemplate = new ToolTip();
public event EventHandler? ChangeText;
public WriteComponent()
{
InitializeComponent();
}
public Regex? Template
{
get => regex;
set
{
regex = value;
}
}
public void SetTextTooltip(string toolTip)
{
toolTipTemplate.SetToolTip(textBox, toolTip);
}
private void textBox_TextChanged(object sender, EventArgs e)
{
ChangeText?.Invoke(this, e);
}
public string WriteTextInTextBox
{
get
{
if (Template == null)
{
throw new NoTemplateException("Не установлен шаблон");
}
if (!Template.IsMatch(textBox.Text))
{
throw new InvalidInputException("Введенное значение не соответствует шаблону");
}
return textBox.Text;
}
set
{
if (Template != null)
{
if (Template.IsMatch(value))
{
textBox.Text = value;
}
else
{
throw new InvalidInputException("Введенное значение не соответствует шаблону");
}
}
else
{
textBox.Text = string.Empty;
}
}
}
}
}

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>