Лабораторная работа 3

This commit is contained in:
danilafilippov7299 2024-11-07 00:39:46 +04:00
parent 8d8d704a13
commit 45714e0b95
52 changed files with 2479 additions and 1267 deletions

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineShopContracts.BindingModels
{
public class OrderBindingModel
{
public int Id { get; set; }
public string CustomerFIO { get; set; }
public byte[] Photo { get; set; } // Для хранения фото заказа
public string ProductId { get; set; } // Внешний ключ на продукт
public string Email { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineShopContracts.BindingModels
{
public class ProductBindingModel
{
public int Id { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Analyzers" Version="7.0.17" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineShopContracts.ViewModels
{
public class OrderViewModel
{
[DisplayName("Идентификатор")]
public int? Id { get; set; }
[DisplayName("ФИО заказчика")]
public string CustomerFIO { get; set; }
//!!!МБ изменить на список строк
[DisplayName("Фото заказа")]
public byte[] Photo { get; set; }
[DisplayName("Продукт")]
public string ProductId { get; set; }
[DisplayName("Почта заказчика")]
public string Email { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineShopContracts.ViewModels
{
public class ProductViewModel
{
[DisplayName("Идентификатор")]
public int? Id { get; set; }
[DisplayName("Название продукта")]
public string Name { get; set; }
}
}

View File

@ -1,13 +1,13 @@
namespace WinFormsLibrary1
namespace OnlineShopForms
{
partial class PieChart
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
@ -20,7 +20,7 @@
base.Dispose(disposing);
}
#region Component Designer generated code
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
@ -28,9 +28,12 @@
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "FormMain";
}
#endregion
}
}
}

View File

@ -0,0 +1,20 @@
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 OnlineShopForms
{
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,65 @@
namespace OnlineShopForms
{
partial class FormStatuses
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
dataGridView = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// dataGridView
//
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersWidth = 51;
dataGridView.RowTemplate.Height = 29;
dataGridView.Size = new Size(250, 450);
dataGridView.TabIndex = 0;
dataGridView.CellEndEdit += dataGridView_CellEndEdit;
dataGridView.KeyDown += dataGridView_KeyDown;
//
// FormStatuses
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(250, 450);
Controls.Add(dataGridView);
Name = "FormStatuses";
Text = "FormStatuses";
Load += FormStatuses_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,119 @@
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using OnlineShopContracts.BindingModels;
using OnlineShopContracts.ViewModels;
using OnlineStoreDatabase.Storages;
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 OnlineShopForms
{
public partial class FormStatuses : Form
{
private readonly StatusStorage _storage;
List<StatusViewModel> list;
public FormStatuses()
{
InitializeComponent();
_storage = new StatusStorage();
}
private void FormStatuses_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
try
{
list = _storage.GetFullList();
if (list != null)
{
dataGridView.DataSource = list;
dataGridView.Columns["Id"].Visible = false;
dataGridView.Columns["Name"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Insert)
{
list.Add(new StatusViewModel());
dataGridView.DataSource = list;
dataGridView.CurrentCell = dataGridView.Rows[dataGridView.Rows.Count - 1].Cells[1];
}
else if (e.KeyData == Keys.Delete)
{
if (dataGridView.SelectedRows.Count == 1)
{
if (MessageBox.Show("Удалить запись?", "Вопрос", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
int id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
try
{
if (!_storage.Delete(new StatusBindingModel() { Id = id }))
{
throw new Exception("Ошибка при удалении");
}
dataGridView.Rows.RemoveAt(dataGridView.SelectedRows[0].Index);
LoadData();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
//конец редактирования названия статуса (ячейки)
private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
//то, что введено в ячейке
string statusName = (string)dataGridView.CurrentRow.Cells[1].Value;
//если в ячейке есть текст (строка непустая)
if (!string.IsNullOrEmpty(statusName))
{
//если есть id, то надо обновить
if (dataGridView.CurrentRow.Cells[0].Value != null)
{
_storage.Update(new StatusBindingModel()
{
Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue
});
}
//если нет id, значит надо создать запись
else
{
_storage.Insert(new StatusBindingModel()
{
Name = (string)dataGridView.CurrentRow.Cells[1].EditedFormattedValue
});
}
}
//если строка пустая
else
{
MessageBox.Show("Введена пустая строка", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
LoadData();
}
}
}

View File

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

View File

@ -5,11 +5,10 @@
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EPPlus" Version="7.4.1" />
<ProjectReference Include="..\OnlineStoreDatabase\OnlineShopDatabase.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,58 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using OnlineStoreDatabase;
#nullable disable
namespace OnlineStoreDatabase.Migrations
{
[DbContext(typeof(OnlineShopDatabase))]
[Migration("20241105211148_Initial2")]
partial class Initial2
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.17")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("OnlineStoreDatabase.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("CustomerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<byte[]>("Photo")
.IsRequired()
.HasColumnType("bytea");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Orders");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,38 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace OnlineStoreDatabase.Migrations
{
/// <inheritdoc />
public partial class Initial2 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Orders",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
CustomerFIO = table.Column<string>(type: "text", nullable: false),
Photo = table.Column<byte[]>(type: "bytea", nullable: false),
ProductId = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Orders", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Orders");
}
}
}

View File

@ -0,0 +1,75 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using OnlineStoreDatabase;
#nullable disable
namespace OnlineStoreDatabase.Migrations
{
[DbContext(typeof(OnlineShopDatabase))]
[Migration("20241105224042_Initial3")]
partial class Initial3
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.17")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("OnlineStoreDatabase.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("CustomerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<byte[]>("Photo")
.IsRequired()
.HasColumnType("bytea");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Orders");
});
modelBuilder.Entity("OnlineStoreDatabase.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Products");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,35 @@
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace OnlineStoreDatabase.Migrations
{
/// <inheritdoc />
public partial class Initial3 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Name = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Products");
}
}
}

View File

@ -0,0 +1,72 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using OnlineStoreDatabase;
#nullable disable
namespace OnlineStoreDatabase.Migrations
{
[DbContext(typeof(OnlineShopDatabase))]
partial class OnlineShopDatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.17")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("OnlineStoreDatabase.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("CustomerFIO")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<byte[]>("Photo")
.IsRequired()
.HasColumnType("bytea");
b.Property<string>("ProductId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Orders");
});
modelBuilder.Entity("OnlineStoreDatabase.Models.Product", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Products");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,63 @@
using OnlineShopContracts.BindingModels;
using OnlineShopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineStoreDatabase.Models
{
public class Order
{
public int Id { get; set; }
[Required]
public string CustomerFIO { get; set; }
[Required]
public byte[] Photo { get; set; }
[Required]
public string ProductId { get; set; }
public string Email { get; set; }
public OrderViewModel GetViewModel => new()
{
Id = Id,
CustomerFIO = CustomerFIO,
Photo = Photo,
ProductId = ProductId,
Email = Email,
};
public static Order? Create(OrderBindingModel model)
{
if (model == null)
{
return null;
}
return new Order()
{
Id = model.Id,
CustomerFIO = model.CustomerFIO,
Photo = model.Photo,
ProductId = model.ProductId,
Email = model.Email
};
}
public void Update(OrderBindingModel model)
{
if (model == null)
{
return;
}
CustomerFIO = model.CustomerFIO;
Photo = model.Photo;
ProductId = model.ProductId;
Email = model.Email;
}
}
}

View File

@ -0,0 +1,48 @@
using OnlineShopContracts.BindingModels;
using OnlineShopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OnlineStoreDatabase.Models
{
public class Product
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public ProductViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
};
public static Product? Create(ProductBindingModel model)
{
if (model == null)
{
return null;
}
return new Product()
{
Id = model.Id,
Name = model.Name
};
}
public void Update(ProductBindingModel model)
{
if (model == null)
{
return;
}
Name = model.Name;
}
}
}

View File

@ -0,0 +1,17 @@
using Microsoft.EntityFrameworkCore;
using OnlineStoreDatabase.Models;
namespace OnlineStoreDatabase
{
public class OnlineShopDatabase : DbContext
{
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder OptionsBuilder)
{
OptionsBuilder.UseNpgsql(@"Host=localhost;Database=postgres;Username=postgres;Password=postgres");
}
}
}

View File

@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Analyzers" Version="7.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.17" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.17">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\OnlineShopContracts\OnlineShopContracts.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,133 @@
using Microsoft.EntityFrameworkCore;
using OnlineShopContracts.BindingModels;
using OnlineShopContracts.ViewModels;
using OnlineStoreDatabase.Models;
using OnlineStoreDatabase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace OnlineStoreDatabase.Storages
{
public class OrderStorage
{
public List<OrderViewModel> GetFullList()
{
using var context = new OnlineShopDatabase();
return context.Orders.Select(x => x.GetViewModel).ToList();
}
public List<OrderViewModel> GetFilteredList(OrderBindingModel model)
{
using var context = new OnlineShopDatabase();
//либо поиск по ФИО заказчика
if (!string.IsNullOrEmpty(model.CustomerFIO))
{
return context.Orders
.Where(x => x.CustomerFIO == model.CustomerFIO)
.Select(x => x.GetViewModel)
.ToList();
}
/*//либо по статусу заказа
else if (!string.IsNullOrEmpty(model.Status))
{
return context.Orders
.Where(x => x.Status == model.Status)
.Select(x => x.GetViewModel)
.ToList();
}
//либо по стоимости
else if (model.Sum.HasValue)
{
return context.Orders
.Where(x => x.Sum == model.Sum)
.Select(x => x.GetViewModel)
.ToList();
}*/
return new();
}
//получение по id заказа
public OrderViewModel? GetElement(OrderBindingModel model)
{
//if (!model.Id.HasValue) return null;
using var context = new OnlineShopDatabase();
return context.Orders.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public bool Insert(OrderBindingModel model)
{
var newOrder = Order.Create(model);
if (newOrder == null)
{
return false;
}
using var context = new OnlineShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
context.Orders.Add(newOrder);
context.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
transaction.Rollback();
return false;
throw;
}
}
public bool Update(OrderBindingModel model)
{
using var context = new OnlineShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var order = context.Orders.FirstOrDefault(x => x.Id == model.Id);
if (order == null)
{
throw new Exception("Заказ не найден");
}
order.Update(model);
context.SaveChanges();
transaction.Commit();
return true;
}
catch
{
transaction.Rollback();
return false;
}
}
public bool Delete(OrderBindingModel model)
{
using var context = new OnlineShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var order = context.Orders.FirstOrDefault(rec => rec.Id == model.Id);
if (order == null)
{
throw new Exception("Заказ не найден");
}
context.Orders.Remove(order);
context.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception e)
{
transaction.Rollback();
return false;
}
}
}
}

View File

@ -0,0 +1,133 @@
using Microsoft.EntityFrameworkCore;
using OnlineShopContracts.BindingModels;
using OnlineShopContracts.ViewModels;
using OnlineStoreDatabase.Models;
using OnlineStoreDatabase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace OnlineStoreDatabase.Storages
{
public class ProductStorage
{
public List<ProductViewModel> GetFullList()
{
using var context = new OnlineShopDatabase();
return context.Products.Select(x => x.GetViewModel).ToList().OrderBy(x => x.Id).ToList();
}
public List<ProductViewModel> GetFilteredList(ProductBindingModel model)
{
using var context = new OnlineShopDatabase();
//либо поиск по ФИО заказчика
/*if (!string.IsNullOrEmpty(model.Name))
{
return context.Products
.Where(x => x.Name == model.Name)
.Select(x => x.GetViewModel)
.ToList();
}*/
/*//либо по статусу заказа
else if (!string.IsNullOrEmpty(model.Status))
{
return context.Products
.Where(x => x.Status == model.Status)
.Select(x => x.GetViewModel)
.ToList();
}*/
//либо по стоимости
if (model.Id != null)
{
return context.Products
.Where(x => x.Id == model.Id)
.Select(x => x.GetViewModel)
.ToList();
}
return new();
}
//получение по id заказа
public ProductViewModel? GetElement(ProductBindingModel model)
{
//if (!model.Id.HasValue) return null;
using var context = new OnlineShopDatabase();
return context.Products.FirstOrDefault(x => x.Id == model.Id)?.GetViewModel;
}
public bool Insert(ProductBindingModel model)
{
var newProduct = Product.Create(model);
if (newProduct == null)
{
return false;
}
using var context = new OnlineShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
context.Products.Add(newProduct);
context.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception ex)
{
transaction.Rollback();
return false;
throw;
}
}
public bool Update(ProductBindingModel model)
{
using var context = new OnlineShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var Product = context.Products.FirstOrDefault(x => x.Id == model.Id);
if (Product == null)
{
throw new Exception("Заказ не найден");
}
Product.Update(model);
context.SaveChanges();
transaction.Commit();
return true;
}
catch
{
transaction.Rollback();
return false;
}
}
public bool Delete(ProductBindingModel model)
{
using var context = new OnlineShopDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
var Product = context.Products.FirstOrDefault(rec => rec.Id == model.Id);
if (Product == null)
{
throw new Exception("Заказ не найден");
}
context.Products.Remove(Product);
context.SaveChanges();
transaction.Commit();
return true;
}
catch (Exception e)
{
transaction.Rollback();
return false;
}
}
}
}

View File

@ -1,11 +1,13 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.1.32210.238
VisualStudioVersion = 17.11.35312.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinFormsApp1", "WinFormsApp1\WinFormsApp1.csproj", "{511958B8-3EDB-4F7E-9172-173515683273}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinFormsApp1", "WinFormsApp1\WinFormsApp1.csproj", "{A8183C87-10C0-41E3-B444-A79BF2B14F1D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinFormsLibrary1", "WinFormsLibrary1\WinFormsLibrary1.csproj", "{951999A1-5DDE-47DD-A205-BAD106A268AB}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OnlineStoreDatabase", "OnlineStoreDatabase\OnlineStoreDatabase.csproj", "{020F2EAA-8B0E-41AC-8677-3D3B8BDFFA6B}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OnlineShopContracts", "OnlineShopContracts\OnlineShopContracts.csproj", "{79C13F67-853B-441F-9284-5F683172B252}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -13,19 +15,23 @@ Global
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{511958B8-3EDB-4F7E-9172-173515683273}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{511958B8-3EDB-4F7E-9172-173515683273}.Debug|Any CPU.Build.0 = Debug|Any CPU
{511958B8-3EDB-4F7E-9172-173515683273}.Release|Any CPU.ActiveCfg = Release|Any CPU
{511958B8-3EDB-4F7E-9172-173515683273}.Release|Any CPU.Build.0 = Release|Any CPU
{951999A1-5DDE-47DD-A205-BAD106A268AB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{951999A1-5DDE-47DD-A205-BAD106A268AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{951999A1-5DDE-47DD-A205-BAD106A268AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{951999A1-5DDE-47DD-A205-BAD106A268AB}.Release|Any CPU.Build.0 = Release|Any CPU
{A8183C87-10C0-41E3-B444-A79BF2B14F1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A8183C87-10C0-41E3-B444-A79BF2B14F1D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A8183C87-10C0-41E3-B444-A79BF2B14F1D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A8183C87-10C0-41E3-B444-A79BF2B14F1D}.Release|Any CPU.Build.0 = Release|Any CPU
{020F2EAA-8B0E-41AC-8677-3D3B8BDFFA6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{020F2EAA-8B0E-41AC-8677-3D3B8BDFFA6B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{020F2EAA-8B0E-41AC-8677-3D3B8BDFFA6B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{020F2EAA-8B0E-41AC-8677-3D3B8BDFFA6B}.Release|Any CPU.Build.0 = Release|Any CPU
{79C13F67-853B-441F-9284-5F683172B252}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{79C13F67-853B-441F-9284-5F683172B252}.Debug|Any CPU.Build.0 = Debug|Any CPU
{79C13F67-853B-441F-9284-5F683172B252}.Release|Any CPU.ActiveCfg = Release|Any CPU
{79C13F67-853B-441F-9284-5F683172B252}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B32788A5-2A20-48CA-95B2-C703D4313D50}
SolutionGuid = {D0F4C3C4-038E-467D-8374-89DB6185E5B7}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,192 @@
namespace WinFormsApp1
{
partial class Create
{
/// <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()
{
textBox1 = new TextBox();
mailTextBox1 = new Labs.MailTextBox();
label1 = new Label();
label2 = new Label();
label3 = new Label();
tableLayoutPanel1 = new TableLayoutPanel();
dropDownList2 = new Labs.DropDownList();
button1 = new Button();
pictureBox1 = new PictureBox();
label4 = new Label();
tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox1).BeginInit();
SuspendLayout();
//
// textBox1
//
textBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right;
textBox1.Location = new Point(3, 53);
textBox1.Multiline = true;
textBox1.Name = "textBox1";
textBox1.Size = new Size(334, 77);
textBox1.TabIndex = 0;
//
// mailTextBox1
//
mailTextBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right;
mailTextBox1.AutoSize = true;
mailTextBox1.Location = new Point(679, 76);
mailTextBox1.Name = "mailTextBox1";
mailTextBox1.Size = new Size(248, 30);
mailTextBox1.TabIndex = 1;
mailTextBox1.Template = "^([\\w\\.\\-]+)@([\\w\\-]+)((\\.(\\w){2,3})+)$";
//
// label1
//
label1.Anchor = AnchorStyles.None;
label1.AutoSize = true;
label1.Location = new Point(149, 15);
label1.Name = "label1";
label1.Size = new Size(42, 20);
label1.TabIndex = 3;
label1.Text = "ФИО";
//
// label2
//
label2.Anchor = AnchorStyles.None;
label2.AutoSize = true;
label2.Location = new Point(475, 15);
label2.Name = "label2";
label2.Size = new Size(66, 20);
label2.TabIndex = 4;
label2.Text = "Продукт";
//
// label3
//
label3.Anchor = AnchorStyles.None;
label3.AutoSize = true;
label3.Location = new Point(777, 15);
label3.Name = "label3";
label3.Size = new Size(51, 20);
label3.TabIndex = 5;
label3.Text = "Почта";
//
// tableLayoutPanel1
//
tableLayoutPanel1.ColumnCount = 4;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30.4413929F));
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 30.1369915F));
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 22.7549458F));
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 16.666666F));
tableLayoutPanel1.Controls.Add(label2, 1, 0);
tableLayoutPanel1.Controls.Add(dropDownList2, 1, 1);
tableLayoutPanel1.Controls.Add(textBox1, 0, 1);
tableLayoutPanel1.Controls.Add(button1, 1, 2);
tableLayoutPanel1.Controls.Add(label1, 0, 0);
tableLayoutPanel1.Controls.Add(pictureBox1, 3, 1);
tableLayoutPanel1.Controls.Add(label4, 3, 0);
tableLayoutPanel1.Controls.Add(mailTextBox1, 2, 1);
tableLayoutPanel1.Controls.Add(label3, 2, 0);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(0, 0);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 3;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 50F));
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.RowStyles.Add(new RowStyle());
tableLayoutPanel1.Size = new Size(1117, 413);
tableLayoutPanel1.TabIndex = 6;
tableLayoutPanel1.Paint += tableLayoutPanel1_Paint;
//
// dropDownList2
//
dropDownList2.Anchor = AnchorStyles.Left | AnchorStyles.Right;
dropDownList2.AutoSize = true;
dropDownList2.Location = new Point(343, 76);
dropDownList2.MinimumSize = new Size(0, 30);
dropDownList2.Name = "dropDownList2";
dropDownList2.SelectedLine = "";
dropDownList2.Size = new Size(330, 30);
dropDownList2.TabIndex = 7;
//
// button1
//
button1.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
button1.Location = new Point(343, 381);
button1.Name = "button1";
button1.Size = new Size(330, 29);
button1.TabIndex = 8;
button1.Text = "Сохранить";
button1.UseVisualStyleBackColor = true;
button1.Click += saveButton_Click;
//
// pictureBox1
//
pictureBox1.Anchor = AnchorStyles.Left | AnchorStyles.Right;
pictureBox1.Location = new Point(933, 60);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new Size(181, 62);
pictureBox1.TabIndex = 10;
pictureBox1.TabStop = false;
pictureBox1.Click += pictureBox1_Click;
//
// label4
//
label4.Anchor = AnchorStyles.None;
label4.AutoSize = true;
label4.Location = new Point(975, 15);
label4.Name = "label4";
label4.Size = new Size(97, 20);
label4.TabIndex = 9;
label4.Text = "Фото заказа";
//
// Create
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1117, 413);
Controls.Add(tableLayoutPanel1);
Name = "Create";
Text = "Create";
FormClosing += Create_FormClosing;
Load += Create_Load;
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox1).EndInit();
ResumeLayout(false);
}
#endregion
private TextBox textBox1;
private Labs.MailTextBox mailTextBox1;
private Label label1;
private Label label2;
private Label label3;
private TableLayoutPanel tableLayoutPanel1;
private Button button1;
private Label label4;
private PictureBox pictureBox1;
private Labs.DropDownList dropDownList2;
}
}

View File

@ -0,0 +1,139 @@
using DocumentFormat.OpenXml.Drawing.Charts;
using Microsoft.VisualBasic.ApplicationServices;
using OnlineStoreDatabase.Storages;
using OnlineShopContracts.BindingModels;
using OnlineShopContracts.ViewModels;
using System;
using System.Linq;
using System.Windows.Forms;
using ShabComponentsLibrary;
using Labs;
namespace WinFormsApp1
{
public partial class Create : Form
{
public Create(int row = -1)
{
InitializeComponent();
_storage = new OrderStorage();
_productStorage = new ProductStorage();
orderIndex = row;
//MessageBox.Show(row.ToString(), "Some title", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
public int orderIndex { get; set; } = -1;
private readonly OrderStorage _storage;
private readonly ProductStorage _productStorage;
OrderViewModel initial { get; set; }
public bool saved = false;
private void saveButton_Click(object sender, EventArgs e)
{
try
{
if (pictureBox1.Image == null) throw new Exception("No Image");
if (orderIndex != -1)
{
_storage.Update(new OrderBindingModel
{
Id = orderIndex,
CustomerFIO = textBox1.Text,
Photo = Order.converterToBytes(pictureBox1.Image), //"photo",
Email = mailTextBox1.TextValue,
ProductId = dropDownList2.SelectedLine,
});
}
else
{
_storage.Insert(new OrderBindingModel
{
CustomerFIO = textBox1.Text,
Photo = Order.converterToBytes(pictureBox1.Image), //"photo",
Email = mailTextBox1.TextValue,
ProductId = dropDownList2.SelectedLine,
});
}
saved = true;
this.Close();
}
catch (Exception er)
{
MessageBox.Show(er.Message, "Some title", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Create_Load(object sender, EventArgs e)
{
if (orderIndex != -1)
{
OrderViewModel order1 = _storage.GetElement(new OrderBindingModel
{
Id = orderIndex,
});
textBox1.Text = order1.CustomerFIO;
dropDownList2.Fill(_productStorage.GetFullList().Select(x => x.Name).ToList());
dropDownList2.SelectedLine = order1.ProductId;
pictureBox1.Image = Order.ConvertBytesToImage(order1.Photo);
mailTextBox1.TextValue = order1.Email;
initial = order1;
}
else
{
initial = new OrderViewModel
{
CustomerFIO = "",
Photo = new byte[0], //"photo",
Email = "",
ProductId = "",
};
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "Image|*.jpg;*.jpeg;*.png";
if (dlg.ShowDialog() == DialogResult.OK)
{
pictureBox1.Image = new Bitmap(dlg.FileName);
}
}
}
private void Create_FormClosing(object sender, FormClosingEventArgs e)
{
string email = "";
try { email = mailTextBox1.TextValue; } catch { }
if (saved == false &&
(initial.CustomerFIO != textBox1.Text ||
!initial.Photo.SequenceEqual(Order.converterToBytes(pictureBox1.Image)) ||
initial.Email != email ||
initial.ProductId != dropDownList2.SelectedLine)
)
{
DialogResult dialogResult = MessageBox.Show("У вас есть не сохранённые изменения! \n Уверены, что хотите закрыть?", "Закрыть?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.No)
{
e.Cancel = true;
}
}
}
private void tableLayoutPanel1_Paint(object sender, PaintEventArgs 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,73 @@
namespace WinFormsApp1
{
partial class Dictinary
{
/// <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()
{
dataGridView1 = new DataGridView();
((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit();
SuspendLayout();
//
// dataGridView1
//
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.Location = new Point(0, 0);
dataGridView1.MultiSelect = false;
dataGridView1.Name = "dataGridView1";
dataGridView1.RowHeadersWidth = 51;
dataGridView1.RowTemplate.Height = 29;
dataGridView1.Size = new Size(443, 652);
dataGridView1.TabIndex = 0;
dataGridView1.KeyDown += dataGridView1_KeyDown;
dataGridView1.KeyUp += dataGridView1_KeyUp;
dataGridView1.PreviewKeyDown += dataGridView1_PreviewKeyDown;
//
// Dictinary
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(443, 652);
Controls.Add(dataGridView1);
KeyPreview = true;
Name = "Dictinary";
Text = "Dictinary";
Load += Dictinary_Load;
KeyDown += Dictinary_KeyDown;
((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit();
ResumeLayout(false);
}
#endregion
private DataGridView dataGridView1;
}
}

View File

@ -0,0 +1,116 @@
using Labs;
using OnlineShopContracts.BindingModels;
using OnlineStoreDatabase.Storages;
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 WinFormsApp1
{
public partial class Dictinary : Form
{
public Dictinary()
{
InitializeComponent();
_storage = new ProductStorage();
}
private readonly ProductStorage _storage;
public bool deleting = false;
private void Dictinary_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("Id", "Id");
dataGridView1.Columns[0].Visible = false;
dataGridView1.Columns.Add("Name", "Name");
//dataGridView1.Columns[1].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
updateTable();
}
public void updateTable()
{
dataGridView1.Rows.Clear();
_storage.GetFullList().ForEach(item =>
{
dataGridView1.Rows.Add(item.Id, item.Name);
});
}
private void Dictinary_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Insert)
{
dataGridView1.Rows.Add("", "");
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Selected = true;
}
else if (e.KeyCode == Keys.Delete)
{
deleting = true;
DialogResult dialogResult = MessageBox.Show("Уверены, что хотите удалить?", "Удалить?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
_storage.Delete(new ProductBindingModel
{
Id = (int)dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex].Cells[0].Value,
});
updateTable();
}
}
}
private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter && deleting == false)
{
if ((string)dataGridView1.SelectedCells[0].Value == "")
{
MessageBox.Show("Пустая строка!", "Empty", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (dataGridView1.SelectedCells[0].RowIndex != dataGridView1.Rows.Count - 1)
{
_storage.Update(new ProductBindingModel
{
Id = (int)dataGridView1.Rows[Math.Max(0, dataGridView1.SelectedCells[0].RowIndex - 1)].Cells[0].Value,
Name = (string)dataGridView1.Rows[Math.Max(0, dataGridView1.SelectedCells[0].RowIndex - 1)].Cells[1].Value,
});
}
else
{
_storage.Insert(new ProductBindingModel
{
Name = (string)dataGridView1.SelectedCells[0].Value,
});
}
updateTable();
e.SuppressKeyPress = true;
e.Handled = true;
return;
}
else deleting = false;
}
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
}
private void dataGridView1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs 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

@ -28,61 +28,129 @@
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.userControl11 = new WinFormsLibrary1.CheckedListBoxControl();
this.dataControl1 = new WinFormsLibrary1.DataControl();
this.treeViewControl1 = new WinFormsLibrary1.TreeViewControl();
this.excel21 = new WinFormsLibrary1.ExcelTable(this.components);
this.SuspendLayout();
components = new System.ComponentModel.Container();
objectsListBox1 = new Labs.ObjectsListBox();
shabListOutputComponent1 = new ShabComponentsLibrary.ShabListOutputComponent();
contextMenuStrip1 = new ContextMenuStrip(components);
создатьЗаписьToolStripMenuItem = new ToolStripMenuItem();
открытьЗаписьToolStripMenuItem = new ToolStripMenuItem();
удалитьЗаписьToolStripMenuItem = new ToolStripMenuItem();
создатьПростойДокументToolStripMenuItem = new ToolStripMenuItem();
создатьДокументСНастраиваемойТаблицейToolStripMenuItem = new ToolStripMenuItem();
создатьДокументСДиаграммойToolStripMenuItem = new ToolStripMenuItem();
справочникToolStripMenuItem = new ToolStripMenuItem();
excelImages1 = new WinFormsLibrary1.ExcelImages(components);
wordTable1 = new Labs.WordTable(components);
shabDiagramComponent1 = new ShabComponentsLibrary.ShabDiagramComponent(components);
contextMenuStrip1.SuspendLayout();
SuspendLayout();
//
// userControl11
// objectsListBox1
//
this.userControl11.Location = new System.Drawing.Point(12, 37);
this.userControl11.Name = "userControl11";
this.userControl11.SelectedItem = "";
this.userControl11.Size = new System.Drawing.Size(276, 217);
this.userControl11.TabIndex = 0;
this.userControl11.Load += new System.EventHandler(this.userControl11_Load);
objectsListBox1.AutoSize = true;
objectsListBox1.Location = new Point(44, 35);
objectsListBox1.Name = "objectsListBox1";
objectsListBox1.SelectedIndex = -1;
objectsListBox1.Size = new Size(520, 321);
objectsListBox1.TabIndex = 1;
//
// dataControl1
// shabListOutputComponent1
//
this.dataControl1.Location = new System.Drawing.Point(306, 29);
this.dataControl1.Name = "dataControl1";
this.dataControl1.Size = new System.Drawing.Size(332, 115);
this.dataControl1.TabIndex = 1;
this.dataControl1.ValueChanged += new System.EventHandler(this.dataControl1_ValueChanged);
shabListOutputComponent1.ContextMenuStrip = contextMenuStrip1;
shabListOutputComponent1.Dock = DockStyle.Fill;
shabListOutputComponent1.Location = new Point(0, 0);
shabListOutputComponent1.Margin = new Padding(3, 4, 3, 4);
shabListOutputComponent1.Name = "shabListOutputComponent1";
shabListOutputComponent1.SelectedRow = -1;
shabListOutputComponent1.Size = new Size(1054, 491);
shabListOutputComponent1.TabIndex = 2;
shabListOutputComponent1.Enter += shabListOutputComponent1_Enter;
//
// treeViewControl1
// contextMenuStrip1
//
this.treeViewControl1.Location = new System.Drawing.Point(665, 12);
this.treeViewControl1.Name = "treeViewControl1";
this.treeViewControl1.SelectedNod = -1;
this.treeViewControl1.SelectedNode = null;
this.treeViewControl1.Size = new System.Drawing.Size(361, 360);
this.treeViewControl1.TabIndex = 2;
contextMenuStrip1.ImageScalingSize = new Size(20, 20);
contextMenuStrip1.Items.AddRange(new ToolStripItem[] { создатьЗаписьToolStripMenuItem, открытьЗаписьToolStripMenuItem, удалитьЗаписьToolStripMenuItem, создатьПростойДокументToolStripMenuItem, создатьДокументСНастраиваемойТаблицейToolStripMenuItem, создатьДокументСДиаграммойToolStripMenuItem, справочникToolStripMenuItem });
contextMenuStrip1.Name = "contextMenuStrip1";
contextMenuStrip1.Size = new Size(397, 172);
//
// создатьЗаписьToolStripMenuItem
//
создатьЗаписьToolStripMenuItem.Name = "создатьЗаписьToolStripMenuItem";
создатьЗаписьToolStripMenuItem.Size = new Size(396, 24);
создатьЗаписьToolStripMenuItem.Text = "Создать запись";
создатьЗаписьToolStripMenuItem.Click += создатьЗаписьToolStripMenuItem_Click;
//
// открытьЗаписьToolStripMenuItem
//
открытьЗаписьToolStripMenuItem.Name = "открытьЗаписьToolStripMenuItem";
открытьЗаписьToolStripMenuItem.Size = new Size(396, 24);
открытьЗаписьToolStripMenuItem.Text = "Открыть запись";
открытьЗаписьToolStripMenuItem.Click += открытьЗаписьToolStripMenuItem_Click;
//
// удалитьЗаписьToolStripMenuItem
//
удалитьЗаписьToolStripMenuItem.Name = "удалитьЗаписьToolStripMenuItem";
удалитьЗаписьToolStripMenuItem.Size = new Size(396, 24);
удалитьЗаписьToolStripMenuItem.Text = "Удалить запись";
удалитьЗаписьToolStripMenuItem.Click += удалитьЗаписьToolStripMenuItem_Click;
//
// создатьПростойДокументToolStripMenuItem
//
создатьПростойДокументToolStripMenuItem.Name = "создатьПростойДокументToolStripMenuItem";
создатьПростойДокументToolStripMenuItem.Size = new Size(396, 24);
создатьПростойДокументToolStripMenuItem.Text = "Создать простой документ";
создатьПростойДокументToolStripMenuItem.Click += создатьПростойДокументToolStripMenuItem_Click;
//
// создатьДокументСНастраиваемойТаблицейToolStripMenuItem
//
создатьДокументСНастраиваемойТаблицейToolStripMenuItem.Name = "создатьДокументСНастраиваемойТаблицейToolStripMenuItem";
создатьДокументСНастраиваемойТаблицейToolStripMenuItem.Size = new Size(396, 24);
создатьДокументСНастраиваемойТаблицейToolStripMenuItem.Text = "Создать документ с настраиваемой таблицей";
создатьДокументСНастраиваемойТаблицейToolStripMenuItem.Click += создатьДокументСНастраиваемойТаблицейToolStripMenuItem_Click;
//
// создатьДокументСДиаграммойToolStripMenuItem
//
создатьДокументСДиаграммойToolStripMenuItem.Name = "создатьДокументСДиаграммойToolStripMenuItem";
создатьДокументСДиаграммойToolStripMenuItem.Size = new Size(396, 24);
создатьДокументСДиаграммойToolStripMenuItem.Text = "Создать документ с диаграммой";
создатьДокументСДиаграммойToolStripMenuItem.Click += создатьДокументСДиаграммойToolStripMenuItem_Click;
//
// справочникToolStripMenuItem
//
справочникToolStripMenuItem.Name = "справочникToolStripMenuItem";
справочникToolStripMenuItem.Size = new Size(396, 24);
справочникToolStripMenuItem.Text = "Справочник";
справочникToolStripMenuItem.Click += справочникToolStripMenuItem_Click;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1052, 404);
this.Controls.Add(this.treeViewControl1);
this.Controls.Add(this.dataControl1);
this.Controls.Add(this.userControl11);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1054, 491);
Controls.Add(shabListOutputComponent1);
Controls.Add(objectsListBox1);
Name = "Form1";
Text = "Form1";
Enter += Form1_Enter;
contextMenuStrip1.ResumeLayout(false);
ResumeLayout(false);
PerformLayout();
}
#endregion
private WinFormsLibrary1.CheckedListBoxControl userControl11;
private WinFormsLibrary1.DataControl dataControl1;
private WinFormsLibrary1.TreeViewControl treeViewControl1;
private WinFormsLibrary1.ExcelImages excelComponent1;
private WinFormsLibrary1.ExcelTable excel22;
private WinFormsLibrary1.ExcelTable excel21;
//private WinFormsLibrary1.TreeViewControl treeViewControl2;
private Labs.ObjectsListBox objectsListBox1;
private ShabComponentsLibrary.ShabListOutputComponent shabListOutputComponent1;
private ContextMenuStrip contextMenuStrip1;
private ToolStripMenuItem создатьЗаписьToolStripMenuItem;
private ToolStripMenuItem открытьЗаписьToolStripMenuItem;
private ToolStripMenuItem удалитьЗаписьToolStripMenuItem;
private ToolStripMenuItem создатьПростойДокументToolStripMenuItem;
private ToolStripMenuItem создатьДокументСНастраиваемойТаблицейToolStripMenuItem;
private ToolStripMenuItem создатьДокументСДиаграммойToolStripMenuItem;
private ToolStripMenuItem справочникToolStripMenuItem;
private WinFormsLibrary1.ExcelImages excelImages1;
private Labs.WordTable wordTable1;
private ShabComponentsLibrary.ShabDiagramComponent shabDiagramComponent1;
}
}
}

View File

@ -1,4 +1,14 @@
using WinFormsLibrary1;
using Labs;
using Labs.HelperClasses.WordTable;
using ShabComponentsLibrary;
using WinFormsLibrary1;
using ShabComponentsLibrary;
using OnlineShopContracts.BindingModels;
using OnlineStoreDatabase.Storages;
using System.Windows.Forms;
using System.Text;
using OfficeOpenXml;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace WinFormsApp1
{
@ -8,32 +18,227 @@ namespace WinFormsApp1
{
InitializeComponent();
/*treeViewControl1.AddTree(new List<TestNode>
_storage = new OrderStorage();
/*objectsListBox1.SetTemplateInfo("ФИО: <CustomerFIO>; <ProductId>, <Email>", '<', '>');
objectsListBox1.Fill(new List<Order>
{
new Order(1, "FIO1", converterDemo(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 0, "EMAIL1"),
new Order(1, "FIO2", converterDemo(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL2"),
new Order(1, "FIO3", converterDemo(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL3"),
new Order(1, "FIO4", converterDemo(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL4"),
});
treeViewControl2.SetHierarchy(new string[] { "Otdel", "Dol", "FirstName", });
treeViewControl2.SetAlwaysNewBranchFields(new string[] { "FirstName" });
treeViewControl2.AddTree(new List<TestNode>
{
new TestNode("Name1", "otdel1", "dolj"),
new TestNode("Name1", "otdel1", "dolj"),
new TestNode("Name2", "otdel3", "dolj4"),
new TestNode("Name3", "otdel3", "dolj2"),
});
*/
// Configure the columns for the list output component
shabListOutputComponent1.ConfigureColumns(new List<ColumnInfo>
{
//new ColumnInfo { Header = "Name", Width = 150, IsVisible = true, Name = "Name" },
new ColumnInfo("Id", 400, false, "Id"),
new ColumnInfo("FIO", 400, true, "CustomerFIO"),
new ColumnInfo("Produc", 400, true, "ProductId"),
new ColumnInfo("Photo", 400, false, "Photo"),
new ColumnInfo("Email", 400, true, "Email"),
});
/*
// Insert values into the grid
shabListOutputComponent1.InsertValues(new List<Order>
{
new Order(1, "FIO1", Order.converterToBytes(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 0, "EMAIL1"),
new Order(1, "FIO2", Order.converterToBytes(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL2"),
new Order(1, "FIO3", Order.converterToBytes(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL3"),
new Order(1, "FIO4", Order.converterToBytes(Image.FromFile("E:/System/Memory/Interface/Safety/university/KOP/33/MainAfter.jpg")), 1, "EMAIL4"),
});*/
}
private void userControl11_Load(object sender, EventArgs e)
shabListOutputComponent1.InsertValues(_storage.GetFullList());
}
private readonly OrderStorage _storage;
private void создатьЗаписьToolStripMenuItem_Click(object sender, EventArgs e)
{
Create g = new Create();
g.ShowDialog();
shabListOutputComponent1.InsertValues(_storage.GetFullList());
}
private void Form1_Load(object sender, EventArgs e)
private void открытьЗаписьToolStripMenuItem_Click(object sender, EventArgs e)
{
var myObject = shabListOutputComponent1.GetSelectedObject<OrderBindingModel>();
Create g = new Create(myObject.Id);
g.ShowDialog();
shabListOutputComponent1.InsertValues(_storage.GetFullList());
}
private void dataControl1_ValueChanged(object sender, EventArgs e)
private void удалитьЗаписьToolStripMenuItem_Click(object sender, EventArgs e)
{
if (shabListOutputComponent1.SelectedRow != -1)
{
DialogResult dialogResult = MessageBox.Show("Удалить запись под номером " + (shabListOutputComponent1.SelectedRow + 1).ToString() + "?", "Удалить?", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
_storage.Delete(new OrderBindingModel
{
Id = shabListOutputComponent1.SelectedRow + 1
});
}
}
}
private void справочникToolStripMenuItem_Click(object sender, EventArgs e)
{
Dictinary g = new Dictinary();
g.ShowDialog();
shabListOutputComponent1.InsertValues(_storage.GetFullList());
}
private void создатьПростойДокументToolStripMenuItem_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog.Filter = "Image Files (*.xlsx)|*.xlsx";
saveFileDialog.Title = "Сохранить документ";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
List<OrderBindingModel> objects = new List<OrderBindingModel> { };
try
{
for (int i = 0; i < 100000; i++)
{
shabListOutputComponent1.SelectedRow = i;
objects.Add(shabListOutputComponent1.GetSelectedObject<OrderBindingModel>());
}
}
catch { }
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
excelImages1.CreateDocument(saveFileDialog.FileName, "My Document", objects.Select(x => Order.ConvertBytesToImage(x.Photo)).ToList());
}
}
}
private void Form1_Enter(object sender, EventArgs e)
{
shabListOutputComponent1.InsertValues(_storage.GetFullList());
}
private void treeViewControl2_Load(object sender, EventArgs e)
{
// Insert values into the grid
}
private void shabListOutputComponent1_Enter(object sender, EventArgs e)
{
}
private void создатьДокументСНастраиваемойТаблицейToolStripMenuItem_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog.Filter = "Image Files (*.docx)|*.docx";
saveFileDialog.Title = "Сохранить документ";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
List<OrderBindingModel> objects = new List<OrderBindingModel> { };
try
{
for (int i = 0; i < 100000; i++)
{
shabListOutputComponent1.SelectedRow = i;
objects.Add(shabListOutputComponent1.GetSelectedObject<OrderBindingModel>());
}
}
catch { }
wordTable1.CreateWordTable(new Labs.HelperClasses.WordTable.WordTableConfig<OrderBindingModel>(
saveFileDialog.FileName,
"ExcelMine",
new List<Labs.HelperClasses.WordTable.ColumnProperties> {
new ColumnProperties("Id", 100, "Идентификатор", "Идентификатор"),
new ColumnProperties("CustomerFIO", 100, "Личные данные", "ФИО заказчика"),
new ColumnProperties("Email", 100, "Личные данные", "Эл. почта"),
new ColumnProperties("ProductId", 100, "Выбранный товар", "Выбранный товар"),
},
new List<Labs.HelperClasses.WordTable.CellMergeInfo>
{
new CellMergeInfo(1, 2)
},
objects
));
}
}
}
private void создатьДокументСДиаграммойToolStripMenuItem_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog.Filter = "Image Files (*.pdf)|*.pdf";
saveFileDialog.Title = "Сохранить документ";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
List<OrderBindingModel> objects = new List<OrderBindingModel> { };
try
{
for (int i = 0; i < 100000; i++)
{
shabListOutputComponent1.SelectedRow = i;
objects.Add(shabListOutputComponent1.GetSelectedObject<OrderBindingModel>());
}
}
catch { }
Dictionary<string, int[]> l = new Dictionary<string, int[]> {};
objects.ForEach(item =>
{
if (!l.ContainsKey(item.ProductId))
l[item.ProductId] = new int[] { 1 };
else
l[item.ProductId][0] += 1;
});
shabDiagramComponent1.CreateDocument(
saveFileDialog.FileName,
"Гистограмма интернет магазина",
"Количество заказов товаров",
ShabComponentsLibrary.Enums.LegendPosition.Top,
l
);
}
}
}
}
}
}

View File

@ -1,4 +1,64 @@
<root>
<?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">
@ -57,7 +117,16 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="excel21.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<metadata name="contextMenuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="excelImages1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>202, 17</value>
</metadata>
<metadata name="wordTable1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>348, 17</value>
</metadata>
<metadata name="shabDiagramComponent1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>481, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormsApp1
{
public class Order
{
public int Id { get; set; }
public string CustomerFIO { get; set; }
public byte[] Photo { get; set; } // Для хранения фото заказа
public int ProductId { get; set; } // Внешний ключ на продукт
public string Email { get; set; }
public Order(int id, string customerFIO, byte[] photo, int productId, string email)
{
Id = id;
CustomerFIO = customerFIO;
Photo = photo;
ProductId = productId;
Email = email;
}
public static byte[] converterToBytes(Image x)
{
ImageConverter _imageConverter = new ImageConverter();
byte[] xByte = (byte[])_imageConverter.ConvertTo(new Bitmap(x), typeof(byte[]));
return xByte;
}
public static Image ConvertBytesToImage(byte[] imageBytes)
{
using (var ms = new MemoryStream(imageBytes))
{
return Image.FromStream(ms);
}
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}

View File

@ -6,14 +6,23 @@
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateRuntimeConfigurationFiles>True</GenerateRuntimeConfigurationFiles>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EPPlus" Version="7.4.1" />
<PackageReference Include="Labs" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.17">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="ShabComponentsLibrary" Version="1.0.0" />
<PackageReference Include="WinFormsLibrary1" Version="1.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WinFormsLibrary1\WinFormsLibrary1.csproj" />
<ProjectReference Include="..\OnlineStoreDatabase\OnlineStoreDatabase.csproj" />
</ItemGroup>
</Project>

View File

@ -1,60 +0,0 @@
namespace WinFormsLibrary1
{
partial class CheckedListBoxControl
{
/// <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 Component 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.checkedListBox1 = new System.Windows.Forms.CheckedListBox();
this.SuspendLayout();
//
// checkedListBox1
//
this.checkedListBox1.FormattingEnabled = true;
this.checkedListBox1.Location = new System.Drawing.Point(13, 16);
this.checkedListBox1.Name = "checkedListBox1";
this.checkedListBox1.Size = new System.Drawing.Size(180, 144);
this.checkedListBox1.TabIndex = 1;
this.checkedListBox1.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.checkedListBox1_ItemCheck);
this.checkedListBox1.SelectedIndexChanged += new System.EventHandler(this.checkedListBox1_SelectedIndexChanged);
//
// CheckedListBoxControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.checkedListBox1);
this.Name = "CheckedListBoxControl";
this.Size = new System.Drawing.Size(209, 180);
this.Load += new System.EventHandler(this.UserControl1_Load);
this.ResumeLayout(false);
}
#endregion
private CheckedListBox checkedListBox1;
}
}

View File

@ -1,82 +0,0 @@
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 WinFormsLibrary1
{
public partial class CheckedListBoxControl : UserControl
{
public CheckedListBoxControl()
{
InitializeComponent();
}
//Метод, у которого в передаваемых параметрах идет список строк
public void AddToComboBox(List<string> list)
{
foreach (var Item in list)
{
checkedListBox1.Items.Add(Item);
}
}
//Очистка списка
public void ClearList()
{
checkedListBox1.Items.Clear();
}
//Установка и получение выбранного значения
public string SelectedItem
{
get { return (string?)checkedListBox1.SelectedItem ?? string.Empty; }
set { checkedListBox1.SelectedItem = value; }
}
private event EventHandler? _itemSelected;
//Событие, вызываемое при смене значения
public event EventHandler? ItemSelected
{
add { _itemSelected += value; }
remove { _itemSelected -= value; }
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedId = checkedListBox1.SelectedIndex;
//checkedListBox1.SetItemChecked(selectedId, true);
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (i != selectedId) checkedListBox1.SetItemChecked(i, false);
}
_itemSelected?.Invoke(this, e);
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
}
private void UserControl1_Load(object sender, EventArgs e)
{
}
}
}

View File

@ -1,60 +0,0 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,57 +0,0 @@
namespace WinFormsLibrary1
{
partial class DataControl
{
/// <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 Component 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.dateTimePicker1 = new System.Windows.Forms.DateTimePicker();
this.SuspendLayout();
//
// dateTimePicker1
//
this.dateTimePicker1.Location = new System.Drawing.Point(14, 50);
this.dateTimePicker1.Name = "dateTimePicker1";
this.dateTimePicker1.Size = new System.Drawing.Size(300, 31);
this.dateTimePicker1.TabIndex = 2;
this.dateTimePicker1.ValueChanged += new System.EventHandler(this.MainTextBox_TextChanged);
//
// DataControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.dateTimePicker1);
this.Name = "DataControl";
this.Size = new System.Drawing.Size(329, 131);
this.ResumeLayout(false);
}
#endregion
private DateTimePicker dateTimePicker1;
}
}

View File

@ -1,66 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinFormsLibrary1.Exceptions;
namespace WinFormsLibrary1
{
public partial class DataControl : UserControl
{
public DataControl()
{
InitializeComponent();
}
//Установка диапазона
public void SetDateRange(DateTime time1, DateTime time2)
{
first = time1;
end = time2;
}
private DateTime? first = null;
private DateTime? end = null;
/// Установка и получение введенного значения
public DateTime DateValue
{
get
{
if (first == null) throw new EmptyValueException();
if (dateTimePicker1.Value < first || dateTimePicker1.Value > end)
throw new NotInDateRange();
return dateTimePicker1.Value;
}
set
{
if (first != null && value >= first && value <= end)
dateTimePicker1.Value = (DateTime)value;
}
}
private event EventHandler? _valueChanged;
/// Событие, вызываемое при смене значения
public event EventHandler? ValueChanged
{
add { _valueChanged += value; }
remove { _valueChanged -= value; }
}
private void MainTextBox_TextChanged(object sender, EventArgs e)
{
_valueChanged?.Invoke(this, e);
}
}
}

View File

@ -1,60 +0,0 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -1,36 +0,0 @@
namespace WinFormsLibrary1
{
partial class ExcelImages
{
/// <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 Component 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();
}
#endregion
}
}

View File

@ -1,80 +0,0 @@
using System.ComponentModel;
using OfficeOpenXml;
namespace WinFormsLibrary1
{
public partial class ExcelImages : Component
{
public ExcelImages()
{
InitializeComponent();
}
public ExcelImages(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateDocument(
string filePath,
string documentTitle,
List<Image> images)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentException("Путь к файлу не может быть пустым.", nameof(filePath));
}
if (string.IsNullOrWhiteSpace(documentTitle))
{
throw new ArgumentException("Название документа не может быть пустым.", nameof(documentTitle));
}
if (images == null || images.Count == 0)
{
throw new ArgumentException("Массив изображений не может быть пустым.", nameof(images));
}
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add(documentTitle);
worksheet.Cells[1, 1].Value = documentTitle;
worksheet.Cells[1, 1].Style.Font.Bold = true;
worksheet.Cells[1, 1].Style.Font.Size = 16;
double row = 2;
foreach (var image in images)
{
var excelImage = worksheet.Drawings.AddPicture($"Image{(int)(row - 1)}", new MemoryStream(ImageToByteArray(image)));
excelImage.SetPosition((int)(row - 1), 0, 0, 0);
excelImage.SetSize(image.Width, image.Height);
row += (int)(image.Height/ PointsToPixels(worksheet.Row(1).Height));
}
FileInfo file = new FileInfo(filePath);
package.SaveAs(file);
}
}
private byte[] ImageToByteArray(Image image)
{
using (var ms = new MemoryStream())
{
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
}
// Метод для перевода пунктов в пиксели
static double PointsToPixels(double points)
{
return points * (96.0 / 72.0); // Стандартный DPI для экранов 96 пикселей на дюйм, а 1 пункт = 1/72 дюйма
}
}
}

View File

@ -1,36 +0,0 @@
namespace WinFormsLibrary1
{
partial class ExcelTable
{
/// <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 Component 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();
}
#endregion
}
}

View File

@ -1,212 +0,0 @@
using System.ComponentModel;
using OfficeOpenXml;
using OfficeOpenXml.Style;
namespace WinFormsLibrary1
{
public partial class ExcelTable : Component
{
public ExcelTable()
{
InitializeComponent();
}
public ExcelTable(IContainer container)
{
container.Add(this);
InitializeComponent();
}
// Публичный метод для создания Excel документа
public void GenerateExcel<T>(string filePath, string documentTitle,
List<MergeInfo> mergeInfo,
List<(string, string, string propertyName)> headerTitles, List<T> data)
{
if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(documentTitle) ||
mergeInfo == null || headerTitles == null || data == null)
{
throw new ArgumentException("Не все входные данные заполнены.");
}
// Проверка на заполненность шапки
ValidateHeaders(headerTitles);
// Проверки на корректность объединения ячеек и заполнения
ValidateMergedCells(mergeInfo, headerTitles.Count);
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Sheet1");
worksheet.Cells[1, 1].Value = documentTitle;
worksheet.Cells[1, 1, 1, headerTitles.Count].Merge = true;
worksheet.Cells[1, 1].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
//Мержим заголовки по столбцам
for (int i = 1; i < headerTitles.Count; i++)
{
if (headerTitles[i].Item2 == headerTitles[i + 1].Item2)
{
int j;
for (j = i; j < headerTitles.Count; j++)
{
if (headerTitles[j].Item2 != headerTitles[j + 1].Item2) break;
}
mergeInfo.Add(new MergeInfo(2, i + 1, 2, j + 1));
i = j + 1;
}
}
// Заполняем шапку таблицы
for (int i = 0; i < headerTitles.Count; i++)
{
worksheet.Cells[2, i + 1].Value = headerTitles[i].Item2;
worksheet.Cells[3, i + 1].Value = headerTitles[i].Item1;
//Мержим заголовки по строкам
if (headerTitles[i].Item1 == headerTitles[i].Item2) mergeInfo.Add(new MergeInfo(2, i + 1, 3, i + 1));
}
// Применение объединений ячеек
foreach (var merge in mergeInfo)
{
worksheet.Cells[merge.StartRow, merge.StartColumn, merge.EndRow, merge.EndColumn].Merge = true;
}
// Установка высоты строк
for (int i = 0; i < data.Count; i++)
{
}
// Заполнение данных таблицы
for (int rowIndex = 0; rowIndex < data.Count; rowIndex++)
{
var rowData = data[rowIndex];
for (int colIndex = 0; colIndex < headerTitles.Count; colIndex++)
{
// Используем сопоставление полей/свойств объекта
string propertyName = headerTitles[colIndex].propertyName;
var property = rowData.GetType().GetProperty(propertyName);
if (property == null)
throw new ArgumentException($"Свойство {property} не найдено в классе {propertyName}.");
worksheet.Cells[rowIndex + 4, colIndex + 1].Value = property.GetValue(rowData);
}
string propertyName2 = "height";
var propertyHeight = rowData.GetType().GetProperty(propertyName2);
if (propertyHeight == null)
throw new ArgumentException($"Свойство {propertyHeight} не найдено в классе {propertyName2}.");
worksheet.Row(rowIndex + 4).Height = (double)propertyHeight.GetValue(rowData);
}
// Сохранение файла
var file = new FileInfo(filePath);
package.SaveAs(file);
}
}
public class Person
{
public int ID { get; set; } // Идентификатор
public string status { get; set; }
public string name { get; set; }
public string fio { get; set; }
public int Age { get; set; }
public string vos { get; set; }
public string kids { get; set; }
public string dol { get; set; }
public string pod { get; set; }
public int prem { get; set; }
public int height { get; set; }
public Person(int height, int id, string status, string name, string fio, int Age, string vos, string kids, string dol, string pod, int prem)
{
this.height = height;
this.ID = id;
this.status = status;
this.name = name;
this.fio = fio;
this.Age = Age;
this.vos = vos;
this.kids = kids;
this.dol = dol;
this.pod = pod;
this.prem = prem;
}
}
// Метод для проверки на заполненность шапки
private void ValidateHeaders(List<(string, string, string)> headerInfo)
{
foreach (var header in headerInfo)
{
if (string.IsNullOrWhiteSpace(header.Item1) || string.IsNullOrWhiteSpace(header.Item2))
{
throw new ArgumentException("Все ячейки шапки должны быть заполнены.");
}
}
}
// Метод для проверки наложения объединенных ячеек
private void ValidateMergedCells(List<MergeInfo> mergeInfo, int headerColumnsCount)
{
foreach (var merge in mergeInfo)
{
if (merge.StartColumn > headerColumnsCount || merge.EndColumn > headerColumnsCount)
{
throw new ArgumentException("Объединенные ячейки выходят за пределы шапки.");
}
// Дополнительные проверки можно добавить здесь
}
// Проверка на наложение объединенных ячеек
for (int i = 0; i < mergeInfo.Count; i++)
{
var currentMerge = mergeInfo[i];
for (int j = i + 1; j < mergeInfo.Count; j++)
{
var otherMerge = mergeInfo[j];
// Проверка пересечения по строкам и столбцам
bool isOverlapping =
currentMerge.StartRow <= otherMerge.EndRow && currentMerge.EndRow >= otherMerge.StartRow &&
currentMerge.StartColumn <= otherMerge.EndColumn && currentMerge.EndColumn >= otherMerge.StartColumn;
if (isOverlapping)
{
throw new ArgumentException($"Объединенные ячейки пересекаются: [{currentMerge.StartRow},{currentMerge.StartColumn}] - [{currentMerge.EndRow},{currentMerge.EndColumn}] и [{otherMerge.StartRow},{otherMerge.StartColumn}] - [{otherMerge.EndRow},{otherMerge.EndColumn}].");
}
}
}
}
}
}
// Класс для информации об объединении ячеек
public class MergeInfo
{
public int StartRow { get; set; }
public int StartColumn { get; set; }
public int EndRow { get; set; }
public int EndColumn { get; set; }
public MergeInfo(int startRow, int startColumn, int endRow, int endColumn)
{
StartRow = startRow;
StartColumn = startColumn;
EndRow = endRow;
EndColumn = endColumn;
}
}

View File

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormsLibrary1.Exceptions
{
public class EmptyValueException : ApplicationException
{
public EmptyValueException()
: base("Значение Пустое")
{ }
}
}

View File

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormsLibrary1.Exceptions
{
public class NotInDateRange : ApplicationException
{
public NotInDateRange()
: base("Дата находится не в диапазоне.")
{ }
}
}

View File

@ -1,111 +0,0 @@
using System.ComponentModel;
using OfficeOpenXml;
using OfficeOpenXml.Drawing.Chart;
namespace WinFormsLibrary1
{
public partial class PieChart : Component
{
public PieChart()
{
InitializeComponent();
}
public PieChart(IContainer container)
{
container.Add(this);
InitializeComponent();
}
// Публичный метод для создания Excel-документа с круговой диаграммой
public void CreateExcelWithPieChart(string filePath, string documentTitle,
string chartTitle, LegendPosition legendPosition, List<PieChartData> chartData)
{
if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(documentTitle) || string.IsNullOrEmpty(chartTitle) || chartData == null || chartData.Count == 0)
{
throw new ArgumentException("Все входные данные должны быть заполнены.");
}
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("ChartSheet");
// Устанавливаем заголовок документа
worksheet.Cells[1, 1].Value = documentTitle;
worksheet.Cells[1, 1, 1, 2].Merge = true;
worksheet.Cells[1, 1].Style.Font.Size = 16;
worksheet.Cells[1, 1].Style.Font.Bold = true;
// Записываем данные для диаграммы в ячейки
int row = 3;
worksheet.Cells[row, 1].Value = "Series";
worksheet.Cells[row, 2].Value = "Value";
foreach (var data in chartData)
{
row++;
worksheet.Cells[row, 1].Value = data.SeriesName;
worksheet.Cells[row, 2].Value = data.Value;
}
// Создаем круговую диаграмму
var pieChart = worksheet.Drawings.AddChart(chartTitle, eChartType.Pie) as ExcelPieChart;
// Устанавливаем диапазоны данных для диаграммы
pieChart.Series.Add(worksheet.Cells[4, 2, row, 2], worksheet.Cells[4, 1, row, 1]);
// Заголовок диаграммы
pieChart.Title.Text = chartTitle;
// Установка положения легенды
switch (legendPosition)
{
case LegendPosition.Top:
pieChart.Legend.Position = eLegendPosition.Top;
break;
case LegendPosition.Bottom:
pieChart.Legend.Position = eLegendPosition.Bottom;
break;
case LegendPosition.Left:
pieChart.Legend.Position = eLegendPosition.Left;
break;
case LegendPosition.Right:
pieChart.Legend.Position = eLegendPosition.Right;
break;
case LegendPosition.None:
pieChart.Legend.Remove();
break;
}
// Сохранение файла
var file = new FileInfo(filePath);
package.SaveAs(file);
}
}
}
public class PieChartData
{
public string SeriesName { get; set; } // Название серии
public double Value { get; set; } // Значение
public PieChartData(string seriesName, double value)
{
SeriesName = seriesName ?? throw new ArgumentNullException(nameof(seriesName));
Value = value;
}
}
// Перечисление для позиции легенды
public enum LegendPosition
{
Top,
Bottom,
Left,
Right,
None
}
}

View File

@ -1,29 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormsLibrary1
{
public class TestNode
{
public string FirstName { get; set; } = string.Empty;
public string Otdel { get; set; } = string.Empty;
public string Dol { get; set; } = string.Empty;
public TestNode()
{ }
public TestNode(string FirstName, string Otdel, string Dol)
{
this.FirstName = FirstName;
this.Otdel = Otdel;
this.Dol = Dol;
}
}
}

View File

@ -1,57 +0,0 @@
namespace WinFormsLibrary1
{
partial class TreeViewControl
{
/// <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 Component 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.treeView1 = new System.Windows.Forms.TreeView();
this.SuspendLayout();
//
// treeView1
//
this.treeView1.Location = new System.Drawing.Point(29, 30);
this.treeView1.Name = "treeView1";
this.treeView1.Size = new System.Drawing.Size(444, 283);
this.treeView1.TabIndex = 0;
this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
//
// TreeViewControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.treeView1);
this.Name = "TreeViewControl";
this.Size = new System.Drawing.Size(512, 350);
this.ResumeLayout(false);
}
#endregion
private TreeView treeView1;
}
}

View File

@ -1,153 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsLibrary1
{
public partial class TreeViewControl : UserControl
{
public TreeViewControl()
{
InitializeComponent();
}
private List<string> hierarchy = new List<string>();
private HashSet<string> alwaysNewBranches = new HashSet<string>();
// Метод для задания иерархии полей
public void SetHierarchy(params string[] fields)
{
hierarchy.Clear();
hierarchy.AddRange(fields);
}
//всегда новая ветка
public void SetAlwaysNewBranchFields(params string[] fields)
{
alwaysNewBranches.Clear();
alwaysNewBranches.UnionWith(fields);
}
public void AddTree<T>(List<T> items)
{
treeView1.Nodes.Clear();
foreach (var item in items)
{
TreeNodeCollection currentNodes = treeView1.Nodes;
foreach (var fieldName in hierarchy)
{
var property = typeof(T).GetProperties().First(x => x.Name == fieldName);
if (property == null)
throw new ArgumentException($"Field {fieldName} not found in type {typeof(T).Name}");
var fieldValue = property.GetValue(item)?.ToString() ?? "Unknown";
TreeNode existingNode = null;
if (!alwaysNewBranches.Contains(fieldName))
{
foreach (TreeNode node in currentNodes)
{
if (node.Text == fieldValue)
{
existingNode = node;
break;
}
}
}
if (existingNode == null)
{
existingNode = new TreeNode(fieldValue);
currentNodes.Add(existingNode);
}
currentNodes = existingNode.Nodes;
}
}
}
public T GetObject<T>() where T : new()
{
if (hierarchy == null)
{
throw new InvalidOperationException("Иерархия не задана");
}
if (SelectedNode == null)
{
throw new InvalidOperationException("Узел не выбран");
}
if (SelectedNode.Nodes.Count != 0)
{
throw new InvalidOperationException("Узел не конечный");
}
var obj = new T();
for (int i = hierarchy.Count - 1; i >= 0; i--)
{
var value = SelectedNode.Text;
var propInfo = typeof(T).GetProperty(hierarchy[i]);
if (propInfo == null)
{
throw new InvalidOperationException($"Свойство {hierarchy[i]} не найдено в классе {typeof(T).Name}");
}
propInfo.SetValue(obj, Convert.ChangeType(value, propInfo.PropertyType));
SelectedNode = SelectedNode.Parent;
if (SelectedNode == null)
{
break;
}
}
return obj;
}
// Свойство для получения/установки индекса выбранной ветки (конечного элемента одной из ветки) (set, get)
public int SelectedNod
{
get {
if (SelectedNode != null && SelectedNode.Nodes.Count == 0)
return SelectedNode.Index;
else return -1;
}
set {
if (value > 0 && value < treeView1.Nodes.Count && treeView1.Nodes[value]?.Nodes?.Count == 0)
SelectedNode = treeView1.Nodes[value];
}
}
// Свойство для получения/установки выбранной ветки
public TreeNode SelectedNode
{
get { return treeView1.SelectedNode; }
set { treeView1.SelectedNode = value; }
}
//Публичный метод для получения выбранной записи (дляконечного элемента дерева).
public string SelectedName()
{
if (SelectedNode != null && SelectedNode.Nodes.Count == 0)
return SelectedNode.Text;
else return "Unknown";
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
//GetSelectedObject<object>();
}
}
}

View File

@ -1,60 +0,0 @@
<root>
<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>