Compare commits

...

4 Commits

82 changed files with 7133 additions and 75 deletions

View File

@ -8,4 +8,37 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.2" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
<PackageReference Include="Serilog" Version="4.2.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,103 @@
//------------------------------------------------------------------------------
// <auto-generated>
// Этот код создан программой.
// Исполняемая версия:4.0.30319.42000
//
// Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
// повторной генерации кода.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ProjectOptika.Properties {
using System;
/// <summary>
/// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д.
/// </summary>
// Этот класс создан автоматически классом StronglyTypedResourceBuilder
// с помощью такого средства, как ResGen или Visual Studio.
// Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen
// с параметром /str или перестройте свой проект VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProjectOptika.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Перезаписывает свойство CurrentUICulture текущего потока для всех
/// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Add {
get {
object obj = ResourceManager.GetObject("Add", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap optika {
get {
object obj = ResourceManager.GetObject("optika", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Remove {
get {
object obj = ResourceManager.GetObject("Remove", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Поиск локализованного ресурса типа System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Update {
get {
object obj = ResourceManager.GetObject("Update", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}

View File

@ -0,0 +1,136 @@
<?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>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="Add" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Add.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Remove" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Remove.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="optika" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\optika.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="Update" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\Update.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="optika" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\optika1.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
</root>

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

View File

@ -0,0 +1,46 @@
using ProjectOptika.Scripts.Entities.Enums;
using System.ComponentModel;
namespace ProjectOptika.Scripts.Entities
{
public class Accessories
{
public int ID { get; private set; }
[DisplayName("Название")]
public string Name { get; private set; }
[DisplayName("Название бренда")]
public string Brand { get; private set; }
[DisplayName("Стоимость")]
public int Cost { get; private set; }
[DisplayName("Количество на складе")]
public int StockAvailability { get; private set; }
[DisplayName("Количество в магазине")]
public int AvailabilityStore { get; private set; }
[DisplayName("Дата поставки")]
public DateTime DeliveryDate { get; private set; }
[DisplayName("Категория")]
public CategoryType CategoryName { get; private set; }
public static Accessories CreateEntity(int id, string name, string brand, int cost, int stockAvailability, int availabilityStore, DateTime deliveryDate, CategoryType categoryName)
{
return new Accessories
{
ID = id,
Name = name,
Brand = brand,
Cost = cost,
StockAvailability = stockAvailability,
AvailabilityStore = availabilityStore,
DeliveryDate = deliveryDate,
CategoryName = categoryName
};
}
}
}

View File

@ -0,0 +1,24 @@
namespace ProjectOptika.Scripts.Entities
{
public class AccessoriesOrder
{
public int ID { get; private set; }
public int AccesoryId { get; private set; }
public int Count { get; private set; }
public string AccessoryName { get; private set; } = string.Empty;
public static AccessoriesOrder CreateElement(int id, int accesoryId, int count, string? accessoryName = null)
{
return new AccessoriesOrder
{
ID = id,
AccesoryId = accesoryId,
Count = count,
AccessoryName = accessoryName
};
}
}
}

View File

@ -0,0 +1,40 @@
using ProjectOptika.Scripts.Entities.Enums;
using System.ComponentModel;
namespace ProjectOptika.Scripts.Entities
{
public class Client
{
public int ID { get; private set; }
[DisplayName("Тип клиента")]
public ClientType ClientType { get; private set; }
[DisplayName("Имя")]
public string FirstName { get; private set; }
[DisplayName("Отчество")]
public string SecondName { get; private set; }
[DisplayName("Фамилия")]
public string Surname { get; private set; }
[DisplayName("Номер телефона")]
public string PhoneNumber { get; private set; }
public string FullName => $"{FirstName} {SecondName} {Surname}";
public static Client CreateEntity(int id, ClientType clientType, string firstName, string secondName, string surname, string phoneNumber)
{
return new Client
{
ID = id,
ClientType = clientType,
FirstName = firstName,
SecondName = secondName,
Surname = surname,
PhoneNumber = phoneNumber
};
}
}
}

View File

@ -0,0 +1,35 @@
using ProjectOptika.Scripts.Entities.Enums;
using System.ComponentModel;
namespace ProjectOptika.Scripts.Entities
{
public class Employee
{
public int ID { get; private set; }
[DisplayName("Тип сотрудника")]
public PositionEmployee PositionEmployee { get; private set; }
[DisplayName("Имя")]
public string FirstName { get; private set; }
[DisplayName("Отчество")]
public string SecondName { get; private set; }
[DisplayName("Фамилия")]
public string Surname { get; private set; }
public string FullName => $"{FirstName} {SecondName} {Surname}";
public static Employee CreateEntity(int id, PositionEmployee positionEmployee, string firstName, string secondName, string surname) {
return new Employee
{
ID = id,
PositionEmployee = positionEmployee,
FirstName = firstName,
SecondName = secondName,
Surname = surname
};
}
}
}

View File

@ -0,0 +1,13 @@
namespace ProjectOptika.Scripts.Entities.Enums
{
public enum CategoryType
{
None = 0,
Lenses = 1,
Glasses = 2,
Accessories = 3
}
}

View File

@ -0,0 +1,9 @@
namespace ProjectOptika.Scripts.Entities.Enums
{
public enum ClientType
{
Regular,
VIP,
Corporate
}
}

View File

@ -0,0 +1,13 @@
namespace ProjectOptika.Scripts.Entities.Enums
{
[System.Flags]
public enum PositionEmployee
{
None = 0,
SeniorSalesman = 1,
Salesman = 2,
SellerCashier = 4,
Administrator = 8,
Accountant = 16
}
}

View File

@ -0,0 +1,55 @@
using System.ComponentModel;
namespace ProjectOptika.Scripts.Entities
{
public class Order
{
public int ID { get; private set; }
[Browsable(false)]
public int EmployeeID { get; private set; }
[Browsable(false)]
public int ClientID { get; private set; }
[DisplayName("Дата заказа")]
public DateTime OrderDate { get; private set; }
[DisplayName("Общая стоимость")]
public double TotalCost { get; private set; }
[DisplayName("Клиент")]
public string ClientFullName { get; private set; }
[DisplayName("Работник")]
public string EmployeeFullName { get; private set; }
[DisplayName("Заказ")]
public string AccessoryOrder => AccesoriesOrders != null ?
string.Join(", ", AccesoriesOrders.Select(x => x != null ? $"{x.AccessoryName} {x.Count}" : string.Empty)) :
string.Empty;
[Browsable(false)]
public IEnumerable<AccessoriesOrder> AccesoriesOrders { get; private set; } = [];
public void SetAccessriesOrderReplenishment(IEnumerable<AccessoriesOrder> accesoriesOrders)
{
if (accesoriesOrders != null && accesoriesOrders.Any())
{
AccesoriesOrders = accesoriesOrders;
}
}
public static Order CreateOperation(int id, int employeeID, int clientID, double totalCost, IEnumerable<AccessoriesOrder> accesoriesOrders)
{
return new Order {
ID = id,
EmployeeID = employeeID,
ClientID = clientID,
OrderDate = DateTime.Now,
TotalCost = totalCost,
AccesoriesOrders = accesoriesOrders
};
}
}
}

View File

@ -0,0 +1,44 @@
using System.ComponentModel;
namespace ProjectOptika.Scripts.Entities
{
public class Specifications
{
public int ID { get; private set; }
[Browsable(false)]
public int AccessoriesID { get; private set; }
[DisplayName("Наименование аксессуара")]
public string AccessoriesName { get; private set; }
[DisplayName("Материал")]
public string Material { get; private set; }
[DisplayName("Астигматизм")]
public string Astigmatism { get; private set; }
[DisplayName("Диоптрийность")]
public string Dioptericity { get; private set; }
[DisplayName("Страна изготовителя")]
public string OriginCountry { get; private set; }
[DisplayName("Время производства")]
public double TimeProduction { get; private set; }
public static Specifications CreateEntity(int id, int accessoriesID, string material, string astigmatism, string dioptericity, string originCountry, double timeProduction)
{
return new Specifications
{
ID = id,
AccessoriesID = accessoriesID,
Material = material,
Astigmatism = astigmatism,
Dioptericity = dioptericity,
OriginCountry = originCountry,
TimeProduction = timeProduction
};
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,127 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormAccessories
{
/// <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()
{
buttonRemove = new Button();
buttonUpdate = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
panel = new Panel();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
panel.SuspendLayout();
SuspendLayout();
//
// buttonRemove
//
buttonRemove.BackgroundImage = Properties.Resources.Remove;
buttonRemove.BackgroundImageLayout = ImageLayout.Stretch;
buttonRemove.Location = new Point(3, 166);
buttonRemove.Name = "buttonRemove";
buttonRemove.Size = new Size(96, 71);
buttonRemove.TabIndex = 2;
buttonRemove.UseVisualStyleBackColor = true;
buttonRemove.Click += ButtonRemove_Click;
//
// buttonUpdate
//
buttonUpdate.BackgroundImage = Properties.Resources.Update;
buttonUpdate.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpdate.Location = new Point(3, 89);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(96, 71);
buttonUpdate.TabIndex = 1;
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpdate_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(3, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(96, 71);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(670, 390);
dataGridView.TabIndex = 5;
//
// panel
//
panel.Controls.Add(buttonRemove);
panel.Controls.Add(buttonUpdate);
panel.Controls.Add(buttonAdd);
panel.Dock = DockStyle.Right;
panel.Location = new Point(670, 0);
panel.Name = "panel";
panel.Size = new Size(104, 390);
panel.TabIndex = 4;
//
// FormAccessories
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(774, 390);
Controls.Add(dataGridView);
Controls.Add(panel);
Name = "FormAccessories";
StartPosition = FormStartPosition.CenterParent;
Text = "Аксессуары";
Load += Form_Load;
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
panel.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private Button buttonRemove;
private Button buttonUpdate;
private Button buttonAdd;
private DataGridView dataGridView;
private Panel panel;
}
}

View File

@ -0,0 +1,101 @@
using ProjectOptika.Scripts.Repositories;
using Unity;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormAccessories : Form
{
private readonly IUnityContainer _container;
private readonly IAccessoriesRepository _accessoriesRepositories;
public FormAccessories(IUnityContainer container, IAccessoriesRepository accessoriesRepositories)
{
InitializeComponent();
_container = container ??
throw new ArgumentException(nameof(container));
_accessoriesRepositories = accessoriesRepositories ??
throw new ArgumentException(nameof(accessoriesRepositories));
}
private void Form_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormAccessory>().ShowDialog();
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpdate_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRows(out var findID)) return;
try
{
var form = _container.Resolve<FormAccessory>();
form.ID = findID;
form.ShowDialog();
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonRemove_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRows(out var findID)) return;
if (MessageBox.Show("Удалить запись?", "Удалить", MessageBoxButtons.YesNo) != DialogResult.Yes) return;
try
{
_accessoriesRepositories.DeleteAccessories(findID);
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridView.DataSource = _accessoriesRepositories.GetAccessories();
dataGridView.Columns["ID"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRows(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ID"].Value);
return true;
}
}
}

View File

@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
Version 2.0 Version 2.0
The primary goals of this format is to allow a simple XML format The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes various data types are done through the TypeConverter classes
associated with the data types. associated with the data types.
Example: Example:
... ado.net/XML headers & schema ... ... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader> <resheader name="version">2.0</resheader>
@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment> <comment>This is a comment</comment>
</data> </data>
There are any number of "resheader" rows that contain simple There are any number of "resheader" rows that contain simple
name/value pairs. name/value pairs.
Each data row contains a name, and value. The row also contains a Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture. text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the Classes that don't support this are serialized and stored with the
mimetype set. mimetype set.
The mimetype is used for serialized objects, and tells the The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly: extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below. read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64 mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64 mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64 mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter : using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
--> -->

View File

@ -0,0 +1,236 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormAccessory
{
/// <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()
{
labelName = new Label();
labelBrand = new Label();
labelCost = new Label();
labelStockAvailability = new Label();
labelAvailabilityStore = new Label();
labelDeliveryDate = new Label();
buttonCancel = new Button();
buttonSave = new Button();
textBoxName = new TextBox();
textBoxBrand = new TextBox();
dateTimePickerDeliveryDate = new DateTimePicker();
numericUpDownAvailabilityStore = new NumericUpDown();
numericUpDownStockAvailability = new NumericUpDown();
numericUpDownCost = new NumericUpDown();
labelCategory = new Label();
comboBoxCategoryName = new ComboBox();
((System.ComponentModel.ISupportInitialize)numericUpDownAvailabilityStore).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownStockAvailability).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownCost).BeginInit();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(27, 26);
labelName.Name = "labelName";
labelName.Size = new Size(77, 20);
labelName.TabIndex = 0;
labelName.Text = "Название";
//
// labelBrand
//
labelBrand.AutoSize = true;
labelBrand.Location = new Point(27, 83);
labelBrand.Name = "labelBrand";
labelBrand.Size = new Size(52, 20);
labelBrand.TabIndex = 1;
labelBrand.Text = "Бренд";
//
// labelCost
//
labelCost.AutoSize = true;
labelCost.Location = new Point(21, 137);
labelCost.Name = "labelCost";
labelCost.Size = new Size(83, 20);
labelCost.TabIndex = 2;
labelCost.Text = "Стоимость";
//
// labelStockAvailability
//
labelStockAvailability.AutoSize = true;
labelStockAvailability.Location = new Point(289, 26);
labelStockAvailability.Name = "labelStockAvailability";
labelStockAvailability.Size = new Size(152, 20);
labelStockAvailability.TabIndex = 3;
labelStockAvailability.Text = "Наличие в магазине";
//
// labelAvailabilityStore
//
labelAvailabilityStore.AutoSize = true;
labelAvailabilityStore.Location = new Point(289, 83);
labelAvailabilityStore.Name = "labelAvailabilityStore";
labelAvailabilityStore.Size = new Size(141, 20);
labelAvailabilityStore.TabIndex = 4;
labelAvailabilityStore.Text = "Наличие на складе";
//
// labelDeliveryDate
//
labelDeliveryDate.AutoSize = true;
labelDeliveryDate.Location = new Point(289, 137);
labelDeliveryDate.Name = "labelDeliveryDate";
labelDeliveryDate.Size = new Size(107, 20);
labelDeliveryDate.TabIndex = 5;
labelDeliveryDate.Text = "Дата доставки";
//
// buttonCancel
//
buttonCancel.Location = new Point(145, 261);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(20, 261);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 6;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// textBoxName
//
textBoxName.Location = new Point(110, 23);
textBoxName.Name = "textBoxName";
textBoxName.Size = new Size(156, 27);
textBoxName.TabIndex = 8;
//
// textBoxBrand
//
textBoxBrand.Location = new Point(110, 80);
textBoxBrand.Name = "textBoxBrand";
textBoxBrand.Size = new Size(156, 27);
textBoxBrand.TabIndex = 9;
//
// dateTimePickerDeliveryDate
//
dateTimePickerDeliveryDate.Location = new Point(447, 130);
dateTimePickerDeliveryDate.Name = "dateTimePickerDeliveryDate";
dateTimePickerDeliveryDate.Size = new Size(171, 27);
dateTimePickerDeliveryDate.TabIndex = 10;
//
// numericUpDownAvailabilityStore
//
numericUpDownAvailabilityStore.Location = new Point(447, 80);
numericUpDownAvailabilityStore.Name = "numericUpDownAvailabilityStore";
numericUpDownAvailabilityStore.Size = new Size(171, 27);
numericUpDownAvailabilityStore.TabIndex = 11;
//
// numericUpDownStockAvailability
//
numericUpDownStockAvailability.Location = new Point(447, 19);
numericUpDownStockAvailability.Name = "numericUpDownStockAvailability";
numericUpDownStockAvailability.Size = new Size(171, 27);
numericUpDownStockAvailability.TabIndex = 12;
//
// numericUpDownCost
//
numericUpDownCost.Location = new Point(110, 135);
numericUpDownCost.Name = "numericUpDownCost";
numericUpDownCost.Size = new Size(156, 27);
numericUpDownCost.TabIndex = 13;
//
// labelCategory
//
labelCategory.AutoSize = true;
labelCategory.Location = new Point(27, 191);
labelCategory.Name = "labelCategory";
labelCategory.Size = new Size(35, 20);
labelCategory.TabIndex = 14;
labelCategory.Text = "Тип";
//
// comboBoxCategoryName
//
comboBoxCategoryName.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxCategoryName.FormattingEnabled = true;
comboBoxCategoryName.Location = new Point(110, 191);
comboBoxCategoryName.Name = "comboBoxCategoryName";
comboBoxCategoryName.Size = new Size(151, 28);
comboBoxCategoryName.TabIndex = 15;
//
// FormAccessory
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(670, 302);
Controls.Add(comboBoxCategoryName);
Controls.Add(labelCategory);
Controls.Add(numericUpDownCost);
Controls.Add(numericUpDownStockAvailability);
Controls.Add(numericUpDownAvailabilityStore);
Controls.Add(dateTimePickerDeliveryDate);
Controls.Add(textBoxBrand);
Controls.Add(textBoxName);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelDeliveryDate);
Controls.Add(labelAvailabilityStore);
Controls.Add(labelStockAvailability);
Controls.Add(labelCost);
Controls.Add(labelBrand);
Controls.Add(labelName);
Name = "FormAccessory";
StartPosition = FormStartPosition.CenterParent;
Text = "Аксессуар";
((System.ComponentModel.ISupportInitialize)numericUpDownAvailabilityStore).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownStockAvailability).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownCost).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelName;
private Label labelBrand;
private Label labelCost;
private Label labelStockAvailability;
private Label labelAvailabilityStore;
private Label labelDeliveryDate;
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxName;
private TextBox textBoxBrand;
private DateTimePicker dateTimePickerDeliveryDate;
private NumericUpDown numericUpDownAvailabilityStore;
private NumericUpDown numericUpDownStockAvailability;
private NumericUpDown numericUpDownCost;
private Label labelCategory;
private ComboBox comboBoxCategoryName;
}
}

View File

@ -0,0 +1,86 @@
using ProjectOptika.Scripts.Entities;
using ProjectOptika.Scripts.Entities.Enums;
using ProjectOptika.Scripts.Repositories;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormAccessory : Form
{
private readonly IAccessoriesRepository _accessoriesRepositories;
private int? _accessoriesID;
public int ID
{
set
{
try
{
var accessory = _accessoriesRepositories.GetAccessoriesByID(value);
if (accessory == null) throw new InvalidDataException(nameof(accessory));
_accessoriesID = accessory.ID;
textBoxBrand.Text = accessory.Brand;
textBoxName.Text = accessory.Name;
numericUpDownCost.Value = accessory.Cost;
numericUpDownAvailabilityStore.Value = accessory.AvailabilityStore;
numericUpDownStockAvailability.Value = accessory.StockAvailability;
dateTimePickerDeliveryDate.Value = accessory.DeliveryDate;
comboBoxCategoryName.SelectedIndex = (int)accessory.CategoryName;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormAccessory(IAccessoriesRepository accessoriesRepositories)
{
InitializeComponent();
_accessoriesRepositories = accessoriesRepositories
?? throw new ArgumentNullException(nameof(accessoriesRepositories));
comboBoxCategoryName.DataSource = Enum.GetValues(typeof(CategoryType));
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (comboBoxCategoryName.SelectedIndex < 1 || string.IsNullOrEmpty(textBoxName.Text) || string.IsNullOrEmpty(textBoxBrand.Text))
{
throw new Exception("Имеются незаполненные данные");
}
if (_accessoriesID.HasValue)
{
_accessoriesRepositories.UpdateAccessories(CreateAccessories(_accessoriesID.Value));
}
else
{
_accessoriesRepositories.CreateAccessories(CreateAccessories(0));
}
Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
Close();
}
private Accessories CreateAccessories(int id)
{
return Accessories.CreateEntity(id, textBoxName.Text, textBoxBrand.Text, (int)numericUpDownCost.Value, (int)numericUpDownStockAvailability.Value, (int)numericUpDownAvailabilityStore.Value, dateTimePickerDeliveryDate.Value, (CategoryType)comboBoxCategoryName.SelectedIndex);
}
}
}

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,186 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormClient
{
/// <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()
{
buttonCancel = new Button();
buttonSave = new Button();
textBoxSurname = new TextBox();
labelSurname = new Label();
textBoxSecondName = new TextBox();
labelSecondName = new Label();
textBoxFirstName = new TextBox();
labelFirstName = new Label();
labelPhoneNumber = new Label();
textBoxPhoneNumber = new TextBox();
labelClientType = new Label();
comboBoxClientType = new ComboBox();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Location = new Point(426, 114);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 23;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(314, 114);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 22;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// textBoxSurname
//
textBoxSurname.Location = new Point(108, 111);
textBoxSurname.Name = "textBoxSurname";
textBoxSurname.Size = new Size(125, 27);
textBoxSurname.TabIndex = 21;
//
// labelSurname
//
labelSurname.AutoSize = true;
labelSurname.Location = new Point(11, 114);
labelSurname.Name = "labelSurname";
labelSurname.Size = new Size(74, 20);
labelSurname.TabIndex = 20;
labelSurname.Text = "Фимилия";
//
// textBoxSecondName
//
textBoxSecondName.Location = new Point(108, 60);
textBoxSecondName.Name = "textBoxSecondName";
textBoxSecondName.Size = new Size(125, 27);
textBoxSecondName.TabIndex = 19;
//
// labelSecondName
//
labelSecondName.AutoSize = true;
labelSecondName.Location = new Point(11, 63);
labelSecondName.Name = "labelSecondName";
labelSecondName.Size = new Size(72, 20);
labelSecondName.TabIndex = 18;
labelSecondName.Text = "Отчество";
//
// textBoxFirstName
//
textBoxFirstName.Location = new Point(108, 12);
textBoxFirstName.Name = "textBoxFirstName";
textBoxFirstName.Size = new Size(125, 27);
textBoxFirstName.TabIndex = 17;
//
// labelFirstName
//
labelFirstName.AutoSize = true;
labelFirstName.Location = new Point(11, 15);
labelFirstName.Name = "labelFirstName";
labelFirstName.Size = new Size(39, 20);
labelFirstName.TabIndex = 16;
labelFirstName.Text = "Имя";
//
// labelPhoneNumber
//
labelPhoneNumber.AutoSize = true;
labelPhoneNumber.Location = new Point(249, 15);
labelPhoneNumber.Name = "labelPhoneNumber";
labelPhoneNumber.Size = new Size(127, 20);
labelPhoneNumber.TabIndex = 24;
labelPhoneNumber.Text = "Номер телефона";
//
// textBoxPhoneNumber
//
textBoxPhoneNumber.Location = new Point(399, 12);
textBoxPhoneNumber.Name = "textBoxPhoneNumber";
textBoxPhoneNumber.Size = new Size(183, 27);
textBoxPhoneNumber.TabIndex = 25;
//
// labelClientType
//
labelClientType.AutoSize = true;
labelClientType.Location = new Point(249, 70);
labelClientType.Name = "labelClientType";
labelClientType.Size = new Size(94, 20);
labelClientType.TabIndex = 26;
labelClientType.Text = "Тип клиента";
//
// comboBoxClientType
//
comboBoxClientType.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxClientType.FormattingEnabled = true;
comboBoxClientType.Location = new Point(399, 67);
comboBoxClientType.Name = "comboBoxClientType";
comboBoxClientType.Size = new Size(183, 28);
comboBoxClientType.TabIndex = 27;
//
// FormClient
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(594, 152);
Controls.Add(comboBoxClientType);
Controls.Add(labelClientType);
Controls.Add(textBoxPhoneNumber);
Controls.Add(labelPhoneNumber);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxSurname);
Controls.Add(labelSurname);
Controls.Add(textBoxSecondName);
Controls.Add(labelSecondName);
Controls.Add(textBoxFirstName);
Controls.Add(labelFirstName);
Name = "FormClient";
StartPosition = FormStartPosition.CenterParent;
Text = "Клиент";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private TextBox textBoxSurname;
private Label labelSurname;
private TextBox textBoxSecondName;
private Label labelSecondName;
private TextBox textBoxFirstName;
private Label labelFirstName;
private Label labelPhoneNumber;
private TextBox textBoxPhoneNumber;
private Label labelClientType;
private ComboBox comboBoxClientType;
}
}

View File

@ -0,0 +1,84 @@
using ProjectOptika.Scripts.Entities;
using ProjectOptika.Scripts.Entities.Enums;
using ProjectOptika.Scripts.Repositories;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormClient : Form
{
private readonly IClientRepositiory _clientRepositories;
private int? _clientID;
public int ID
{
set
{
try
{
var client = _clientRepositories.GetClientById(value);
if (client == null) throw new InvalidDataException(nameof(client));
_clientID = client.ID;
textBoxFirstName.Text = client.FirstName;
textBoxSecondName.Text = client.SecondName;
textBoxSurname.Text = client.Surname;
textBoxPhoneNumber.Text = client.PhoneNumber;
comboBoxClientType.SelectedIndex = (int)client.ClientType;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormClient(IClientRepositiory clientRepositories)
{
InitializeComponent();
_clientRepositories = clientRepositories ??
throw new ArgumentNullException(nameof(clientRepositories));
comboBoxClientType.DataSource = Enum.GetValues(typeof(ClientType));
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(textBoxSecondName.Text) || string.IsNullOrEmpty(textBoxSurname.Text) || string.IsNullOrEmpty(textBoxFirstName.Text))
{
throw new Exception("Имеются незаполненные данные");
}
if (_clientID.HasValue)
{
_clientRepositories.UpdateClient(CreateClient(_clientID.Value));
}
else
{
_clientRepositories.CreateClient(CreateClient(0));
}
Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
Close();
}
private Client CreateClient(int id)
{
return Client.CreateEntity(id, (ClientType)comboBoxClientType.SelectedIndex, textBoxFirstName.Text, textBoxSecondName.Text, textBoxSurname.Text, textBoxPhoneNumber.Text);
}
}
}

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,107 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormClientCostRatioReport
{
/// <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()
{
buttonSelectFileName = new Button();
labelFileName = new Label();
buttonBuild = new Button();
dateTimePickerStartDate = new DateTimePicker();
labelStartDate = new Label();
SuspendLayout();
//
// buttonSelectFileName
//
buttonSelectFileName.Location = new Point(12, 12);
buttonSelectFileName.Name = "buttonSelectFileName";
buttonSelectFileName.Size = new Size(94, 29);
buttonSelectFileName.TabIndex = 0;
buttonSelectFileName.Text = "Выбрать";
buttonSelectFileName.UseVisualStyleBackColor = true;
buttonSelectFileName.Click += ButtonSelectFileName_Click;
//
// labelFileName
//
labelFileName.AutoSize = true;
labelFileName.Location = new Point(134, 16);
labelFileName.Name = "labelFileName";
labelFileName.Size = new Size(45, 20);
labelFileName.TabIndex = 1;
labelFileName.Text = "Файл";
//
// buttonBuild
//
buttonBuild.Location = new Point(93, 122);
buttonBuild.Name = "buttonBuild";
buttonBuild.Size = new Size(129, 29);
buttonBuild.TabIndex = 16;
buttonBuild.Text = "Сформировать";
buttonBuild.UseVisualStyleBackColor = true;
buttonBuild.Click += ButtonCreate_Click;
//
// dateTimePickerStartDate
//
dateTimePickerStartDate.Location = new Point(148, 68);
dateTimePickerStartDate.Name = "dateTimePickerStartDate";
dateTimePickerStartDate.Size = new Size(178, 27);
dateTimePickerStartDate.TabIndex = 18;
//
// labelStartDate
//
labelStartDate.AutoSize = true;
labelStartDate.Location = new Point(12, 68);
labelStartDate.Name = "labelStartDate";
labelStartDate.Size = new Size(44, 20);
labelStartDate.TabIndex = 17;
labelStartDate.Text = "Дата:";
//
// FormClientCostRatioReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(357, 172);
Controls.Add(dateTimePickerStartDate);
Controls.Add(labelStartDate);
Controls.Add(buttonBuild);
Controls.Add(labelFileName);
Controls.Add(buttonSelectFileName);
Name = "FormClientCostRatioReport";
Text = "Сформировать учет стоимостей клиентов";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSelectFileName;
private Label labelFileName;
private Button buttonBuild;
private DateTimePicker dateTimePickerStartDate;
private Label labelStartDate;
}
}

View File

@ -0,0 +1,63 @@
using ProjectOptika.Scripts.Reports;
using ProjectOptika.Scripts.Repositories;
using Unity;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormClientCostRatioReport : Form
{
private string _fileName = string.Empty;
private readonly IUnityContainer _container;
public FormClientCostRatioReport(IAccessoriesRepository accessoriesRepository, IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void ButtonSelectFileName_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Pdf Files | *.pdf"
};
if (sfd.ShowDialog() == DialogResult.OK)
{
_fileName = sfd.FileName;
labelFileName.Text = Path.GetFileName(_fileName);
}
}
private void ButtonCreate_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(_fileName))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if
(_container.Resolve<ChartReport>().CreateChart(_fileName, dateTimePickerStartDate.Value))
{
MessageBox.Show("Документ сформирован",
"Формирование документа",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

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

View File

@ -0,0 +1,127 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormClients
{
/// <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()
{
buttonRemove = new Button();
buttonUpdate = new Button();
buttonAdd = new Button();
panel = new Panel();
dataGridView = new DataGridView();
panel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// buttonRemove
//
buttonRemove.BackgroundImage = Properties.Resources.Remove;
buttonRemove.BackgroundImageLayout = ImageLayout.Stretch;
buttonRemove.Location = new Point(3, 166);
buttonRemove.Name = "buttonRemove";
buttonRemove.Size = new Size(96, 71);
buttonRemove.TabIndex = 2;
buttonRemove.UseVisualStyleBackColor = true;
buttonRemove.Click += ButtonRemove_Click;
//
// buttonUpdate
//
buttonUpdate.BackgroundImage = Properties.Resources.Update;
buttonUpdate.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpdate.Location = new Point(3, 89);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(96, 71);
buttonUpdate.TabIndex = 1;
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpdate_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(3, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(96, 71);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// panel
//
panel.Controls.Add(buttonRemove);
panel.Controls.Add(buttonUpdate);
panel.Controls.Add(buttonAdd);
panel.Dock = DockStyle.Right;
panel.Location = new Point(696, 0);
panel.Name = "panel";
panel.Size = new Size(104, 450);
panel.TabIndex = 8;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(800, 450);
dataGridView.TabIndex = 9;
//
// FormClients
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(panel);
Controls.Add(dataGridView);
Name = "FormClients";
StartPosition = FormStartPosition.CenterParent;
Text = "Клиенты";
Load += Form_Load;
panel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Button buttonRemove;
private Button buttonUpdate;
private Button buttonAdd;
private Panel panel;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,102 @@
using ProjectOptika.Scripts.Repositories;
using Unity;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormClients : Form
{
private readonly IUnityContainer _container;
private readonly IClientRepositiory _clientRepositories;
public FormClients(IUnityContainer container, IClientRepositiory clientRepositories)
{
InitializeComponent();
_container = container ??
throw new ArgumentException(nameof(container));
_clientRepositories = clientRepositories ??
throw new ArgumentException(nameof(clientRepositories));
}
private void Form_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormClient>().ShowDialog();
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpdate_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRows(out var findID)) return;
try
{
var form = _container.Resolve<FormClient>();
form.ID = findID;
form.ShowDialog();
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonRemove_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRows(out var findID)) return;
if (MessageBox.Show("Удалить запись?", "Удалить", MessageBoxButtons.YesNo) != DialogResult.Yes) return;
try
{
_clientRepositories.DeleteClient(findID);
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridView.DataSource = _clientRepositories.GetClients();
dataGridView.Columns["ID"].Visible = false;
dataGridView.Columns["FullName"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRows(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ID"].Value);
return true;
}
}
}

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,164 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormClientsReport
{
/// <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()
{
buttonSelectPathFile = new Button();
textBoxFilePath = new TextBox();
labelFilePath = new Label();
comboBoxEmployees = new ComboBox();
labelEmployees = new Label();
labelStartDate = new Label();
labelEndDate = new Label();
dateTimePickerStartDate = new DateTimePicker();
dateTimePickerEndDate = new DateTimePicker();
buttonMakeReport = new Button();
SuspendLayout();
//
// buttonSelectPathFile
//
buttonSelectPathFile.Location = new Point(261, 14);
buttonSelectPathFile.Name = "buttonSelectPathFile";
buttonSelectPathFile.Size = new Size(25, 29);
buttonSelectPathFile.TabIndex = 0;
buttonSelectPathFile.Text = "...";
buttonSelectPathFile.UseVisualStyleBackColor = true;
buttonSelectPathFile.Click += ButtonSelectPathFile_Click;
//
// textBoxFilePath
//
textBoxFilePath.Location = new Point(130, 16);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.ReadOnly = true;
textBoxFilePath.Size = new Size(125, 27);
textBoxFilePath.TabIndex = 1;
//
// labelFilePath
//
labelFilePath.AutoSize = true;
labelFilePath.Location = new Point(12, 19);
labelFilePath.Name = "labelFilePath";
labelFilePath.Size = new Size(112, 20);
labelFilePath.TabIndex = 2;
labelFilePath.Text = "Путь до файла:";
//
// comboBoxEmployees
//
comboBoxEmployees.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxEmployees.FormattingEnabled = true;
comboBoxEmployees.Location = new Point(130, 78);
comboBoxEmployees.Name = "comboBoxEmployees";
comboBoxEmployees.Size = new Size(156, 28);
comboBoxEmployees.TabIndex = 3;
//
// labelEmployees
//
labelEmployees.AutoSize = true;
labelEmployees.Location = new Point(12, 81);
labelEmployees.Name = "labelEmployees";
labelEmployees.Size = new Size(82, 20);
labelEmployees.TabIndex = 4;
labelEmployees.Text = "Сотрудник";
//
// labelStartDate
//
labelStartDate.AutoSize = true;
labelStartDate.Location = new Point(12, 144);
labelStartDate.Name = "labelStartDate";
labelStartDate.Size = new Size(97, 20);
labelStartDate.TabIndex = 5;
labelStartDate.Text = "Дата начала:";
//
// labelEndDate
//
labelEndDate.AutoSize = true;
labelEndDate.Location = new Point(12, 209);
labelEndDate.Name = "labelEndDate";
labelEndDate.Size = new Size(90, 20);
labelEndDate.TabIndex = 6;
labelEndDate.Text = "Дата конца:";
//
// dateTimePickerStartDate
//
dateTimePickerStartDate.Location = new Point(130, 144);
dateTimePickerStartDate.Name = "dateTimePickerStartDate";
dateTimePickerStartDate.Size = new Size(156, 27);
dateTimePickerStartDate.TabIndex = 7;
//
// dateTimePickerEndDate
//
dateTimePickerEndDate.Location = new Point(130, 204);
dateTimePickerEndDate.Name = "dateTimePickerEndDate";
dateTimePickerEndDate.Size = new Size(156, 27);
dateTimePickerEndDate.TabIndex = 8;
//
// buttonMakeReport
//
buttonMakeReport.Location = new Point(64, 265);
buttonMakeReport.Name = "buttonMakeReport";
buttonMakeReport.Size = new Size(136, 29);
buttonMakeReport.TabIndex = 9;
buttonMakeReport.Text = "Сформировать";
buttonMakeReport.UseVisualStyleBackColor = true;
buttonMakeReport.Click += ButtonMakeReport_Click;
//
// FormClientsReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(311, 323);
Controls.Add(buttonMakeReport);
Controls.Add(dateTimePickerEndDate);
Controls.Add(dateTimePickerStartDate);
Controls.Add(labelEndDate);
Controls.Add(labelStartDate);
Controls.Add(labelEmployees);
Controls.Add(comboBoxEmployees);
Controls.Add(labelFilePath);
Controls.Add(textBoxFilePath);
Controls.Add(buttonSelectPathFile);
Name = "FormClientsReport";
Text = "Отчет по клиентам";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSelectPathFile;
private TextBox textBoxFilePath;
private Label labelFilePath;
private ComboBox comboBoxEmployees;
private Label labelEmployees;
private Label labelStartDate;
private Label labelEndDate;
private DateTimePicker dateTimePickerStartDate;
private DateTimePicker dateTimePickerEndDate;
private Button buttonMakeReport;
}
}

View File

@ -0,0 +1,73 @@
using ProjectOptika.Scripts.Reports;
using ProjectOptika.Scripts.Repositories;
using Unity;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormClientsReport : Form
{
private readonly IUnityContainer _container;
public FormClientsReport(IUnityContainer container, IEmployeeRepository employeeRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
comboBoxEmployees.DataSource = employeeRepository.GetEmployees();
comboBoxEmployees.DisplayMember = "Surname";
comboBoxEmployees.ValueMember = "ID";
}
private void ButtonSelectPathFile_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Excel Files | *.xlsx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
return;
}
textBoxFilePath.Text = sfd.FileName;
}
private void ButtonMakeReport_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFilePath.Text))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (comboBoxEmployees.SelectedIndex < 0)
{
throw new Exception("Не выбран доктор");
}
if (dateTimePickerEndDate.Value <= dateTimePickerStartDate.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
if
(_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text,
(int)comboBoxEmployees.SelectedValue!,
dateTimePickerStartDate.Value, dateTimePickerEndDate.Value))
{
MessageBox.Show("Документ сформирован",
"Формирование документа",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

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

View File

@ -0,0 +1,112 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormDirectoryReport
{
/// <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()
{
checkBoxAccessories = new CheckBox();
checkBoxEmplyees = new CheckBox();
checkBoxSpecification = new CheckBox();
checkBoxClients = new CheckBox();
buttonBuild = new Button();
SuspendLayout();
//
// checkBoxAccessories
//
checkBoxAccessories.AutoSize = true;
checkBoxAccessories.Location = new Point(23, 26);
checkBoxAccessories.Name = "checkBoxAccessories";
checkBoxAccessories.Size = new Size(112, 24);
checkBoxAccessories.TabIndex = 0;
checkBoxAccessories.Text = "Аксессуары";
checkBoxAccessories.UseVisualStyleBackColor = true;
//
// checkBoxEmplyees
//
checkBoxEmplyees.AutoSize = true;
checkBoxEmplyees.Location = new Point(23, 78);
checkBoxEmplyees.Name = "checkBoxEmplyees";
checkBoxEmplyees.Size = new Size(113, 24);
checkBoxEmplyees.TabIndex = 1;
checkBoxEmplyees.Text = "Сотрудники";
checkBoxEmplyees.UseVisualStyleBackColor = true;
//
// checkBoxSpecification
//
checkBoxSpecification.AutoSize = true;
checkBoxSpecification.Location = new Point(23, 126);
checkBoxSpecification.Name = "checkBoxSpecification";
checkBoxSpecification.Size = new Size(142, 24);
checkBoxSpecification.TabIndex = 2;
checkBoxSpecification.Text = "Характеристики";
checkBoxSpecification.UseVisualStyleBackColor = true;
//
// checkBoxClients
//
checkBoxClients.AutoSize = true;
checkBoxClients.Location = new Point(23, 174);
checkBoxClients.Name = "checkBoxClients";
checkBoxClients.Size = new Size(91, 24);
checkBoxClients.TabIndex = 3;
checkBoxClients.Text = "Клиенты";
checkBoxClients.UseVisualStyleBackColor = true;
//
// buttonBuild
//
buttonBuild.Location = new Point(88, 223);
buttonBuild.Name = "buttonBuild";
buttonBuild.Size = new Size(129, 29);
buttonBuild.TabIndex = 4;
buttonBuild.Text = "Сформировать";
buttonBuild.UseVisualStyleBackColor = true;
buttonBuild.Click += ButtonBuild_Click;
//
// FormDirectoryReport
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(308, 276);
Controls.Add(buttonBuild);
Controls.Add(checkBoxClients);
Controls.Add(checkBoxSpecification);
Controls.Add(checkBoxEmplyees);
Controls.Add(checkBoxAccessories);
Name = "FormDirectoryReport";
Text = "Документ со справочниками";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckBox checkBoxAccessories;
private CheckBox checkBoxEmplyees;
private CheckBox checkBoxSpecification;
private CheckBox checkBoxClients;
private Button buttonBuild;
}
}

View File

@ -0,0 +1,53 @@
using ProjectOptika.Scripts.Reports;
using Unity;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormDirectoryReport : Form
{
private readonly IUnityContainer _container;
public FormDirectoryReport(IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void ButtonBuild_Click(object sender, EventArgs e)
{
try
{
if (!checkBoxAccessories.Checked &&
!checkBoxClients.Checked && !checkBoxEmplyees.Checked && !checkBoxSpecification.Checked)
{
throw new Exception("Не выбран ни один справочник для выгрузки");
}
var sfd = new SaveFileDialog()
{
Filter = "Docx Files | *.docx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
throw new Exception("Не выбран файла для отчета");
}
if
(_container.Resolve<DocReport>().CreateDoc(sfd.FileName, checkBoxAccessories.Checked,
checkBoxSpecification.Checked, checkBoxEmplyees.Checked, checkBoxClients.Checked))
{
MessageBox.Show("Документ сформирован", "Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах",
"Формирование документа", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании отчета", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

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

View File

@ -0,0 +1,163 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormEmployee
{
/// <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()
{
checkedListBoxPositionEmployee = new CheckedListBox();
labelFirstName = new Label();
textBoxFirstName = new TextBox();
textBoxSecondName = new TextBox();
labelSecondName = new Label();
textBoxSurname = new TextBox();
labelSurname = new Label();
labelPositionEmployee = new Label();
buttonCancel = new Button();
buttonSave = new Button();
SuspendLayout();
//
// checkedListBoxPositionEmployee
//
checkedListBoxPositionEmployee.FormattingEnabled = true;
checkedListBoxPositionEmployee.Location = new Point(298, 45);
checkedListBoxPositionEmployee.Name = "checkedListBoxPositionEmployee";
checkedListBoxPositionEmployee.Size = new Size(225, 180);
checkedListBoxPositionEmployee.TabIndex = 0;
//
// labelFirstName
//
labelFirstName.AutoSize = true;
labelFirstName.Location = new Point(12, 9);
labelFirstName.Name = "labelFirstName";
labelFirstName.Size = new Size(39, 20);
labelFirstName.TabIndex = 1;
labelFirstName.Text = "Имя";
//
// textBoxFirstName
//
textBoxFirstName.Location = new Point(109, 6);
textBoxFirstName.Name = "textBoxFirstName";
textBoxFirstName.Size = new Size(125, 27);
textBoxFirstName.TabIndex = 2;
//
// textBoxSecondName
//
textBoxSecondName.Location = new Point(109, 54);
textBoxSecondName.Name = "textBoxSecondName";
textBoxSecondName.Size = new Size(125, 27);
textBoxSecondName.TabIndex = 4;
//
// labelSecondName
//
labelSecondName.AutoSize = true;
labelSecondName.Location = new Point(12, 57);
labelSecondName.Name = "labelSecondName";
labelSecondName.Size = new Size(72, 20);
labelSecondName.TabIndex = 3;
labelSecondName.Text = "Отчество";
//
// textBoxSurname
//
textBoxSurname.Location = new Point(109, 105);
textBoxSurname.Name = "textBoxSurname";
textBoxSurname.Size = new Size(125, 27);
textBoxSurname.TabIndex = 6;
//
// labelSurname
//
labelSurname.AutoSize = true;
labelSurname.Location = new Point(12, 108);
labelSurname.Name = "labelSurname";
labelSurname.Size = new Size(74, 20);
labelSurname.TabIndex = 5;
labelSurname.Text = "Фимилия";
//
// labelPositionEmployee
//
labelPositionEmployee.AutoSize = true;
labelPositionEmployee.Location = new Point(298, 13);
labelPositionEmployee.Name = "labelPositionEmployee";
labelPositionEmployee.Size = new Size(86, 20);
labelPositionEmployee.TabIndex = 7;
labelPositionEmployee.Text = "Должность";
//
// buttonCancel
//
buttonCancel.Location = new Point(151, 196);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 15;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(12, 196);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 14;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// FormEmployee
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(537, 255);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(labelPositionEmployee);
Controls.Add(textBoxSurname);
Controls.Add(labelSurname);
Controls.Add(textBoxSecondName);
Controls.Add(labelSecondName);
Controls.Add(textBoxFirstName);
Controls.Add(labelFirstName);
Controls.Add(checkedListBoxPositionEmployee);
Name = "FormEmployee";
StartPosition = FormStartPosition.CenterParent;
Text = "Сотрудник";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckedListBox checkedListBoxPositionEmployee;
private Label labelFirstName;
private TextBox textBoxFirstName;
private TextBox textBoxSecondName;
private Label labelSecondName;
private TextBox textBoxSurname;
private Label labelSurname;
private Label labelPositionEmployee;
private Button buttonCancel;
private Button buttonSave;
}
}

View File

@ -0,0 +1,99 @@
using ProjectOptika.Scripts.Entities.Enums;
using ProjectOptika.Scripts.Entities;
using ProjectOptika.Scripts.Repositories;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormEmployee : Form
{
private readonly IEmployeeRepository _employeeRepositories;
private int? _employeeID;
public int ID
{
set
{
try
{
var employee = _employeeRepositories.GetEmployeerByID(value);
if (employee == null) throw new InvalidDataException(nameof(employee));
_employeeID = employee.ID;
textBoxFirstName.Text = employee.FirstName;
textBoxSecondName.Text = employee.SecondName;
textBoxSurname.Text = employee.Surname;
foreach(PositionEmployee element in Enum.GetValues(typeof(PositionEmployee)))
{
if ((element & employee.PositionEmployee) != 0)
{
checkedListBoxPositionEmployee.SetItemChecked(checkedListBoxPositionEmployee.Items.IndexOf(element), true);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormEmployee(IEmployeeRepository employeeRepositories)
{
InitializeComponent();
_employeeRepositories = employeeRepositories ??
throw new ArgumentNullException(nameof(employeeRepositories));
foreach (var i in Enum.GetValues(typeof(PositionEmployee)))
{
checkedListBoxPositionEmployee.Items.Add(i);
}
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(textBoxSecondName.Text) || string.IsNullOrEmpty(textBoxSurname.Text) || string.IsNullOrEmpty(textBoxFirstName.Text))
{
throw new Exception("Имеются незаполненные данные");
}
if (_employeeID.HasValue)
{
_employeeRepositories.UpdateEmployee(CreateEmployee(_employeeID.Value));
}
else
{
_employeeRepositories.CreateEmployee(CreateEmployee(0));
}
Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
Close();
}
private Employee CreateEmployee(int id)
{
PositionEmployee positionEmployee = PositionEmployee.None;
foreach(var element in checkedListBoxPositionEmployee.CheckedItems)
{
positionEmployee |= (PositionEmployee)element;
}
return Employee.CreateEntity(id, positionEmployee, textBoxFirstName.Text, textBoxSecondName.Text, textBoxSurname.Text);
}
}
}

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,127 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormEmplyees
{
/// <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()
{
panel = new Panel();
buttonRemove = new Button();
buttonUpdate = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
panel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// panel
//
panel.Controls.Add(buttonRemove);
panel.Controls.Add(buttonUpdate);
panel.Controls.Add(buttonAdd);
panel.Dock = DockStyle.Right;
panel.Location = new Point(696, 0);
panel.Name = "panel";
panel.Size = new Size(104, 450);
panel.TabIndex = 6;
//
// buttonRemove
//
buttonRemove.BackgroundImage = Properties.Resources.Remove;
buttonRemove.BackgroundImageLayout = ImageLayout.Stretch;
buttonRemove.Location = new Point(3, 166);
buttonRemove.Name = "buttonRemove";
buttonRemove.Size = new Size(96, 71);
buttonRemove.TabIndex = 2;
buttonRemove.UseVisualStyleBackColor = true;
buttonRemove.Click += ButtonRemove_Click;
//
// buttonUpdate
//
buttonUpdate.BackgroundImage = Properties.Resources.Update;
buttonUpdate.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpdate.Location = new Point(3, 89);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(96, 71);
buttonUpdate.TabIndex = 1;
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpdate_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(3, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(96, 71);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(800, 450);
dataGridView.TabIndex = 7;
//
// FormEmplyees
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(panel);
Controls.Add(dataGridView);
Name = "FormEmplyees";
StartPosition = FormStartPosition.CenterParent;
Text = "Сотрудники";
Load += Form_Load;
panel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel;
private Button buttonRemove;
private Button buttonUpdate;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,102 @@
using ProjectOptika.Scripts.Repositories;
using Unity;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormEmplyees : Form
{
private readonly IUnityContainer _container;
private readonly IEmployeeRepository _employeeRepositories;
public FormEmplyees(IUnityContainer container, IEmployeeRepository employeeRepositories)
{
InitializeComponent();
_container = container ??
throw new ArgumentException(nameof(container));
_employeeRepositories = employeeRepositories ??
throw new ArgumentException(nameof(employeeRepositories));
}
private void Form_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormEmployee>().ShowDialog();
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpdate_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRows(out var findID)) return;
try
{
var form = _container.Resolve<FormEmployee>();
form.ID = findID;
form.ShowDialog();
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonRemove_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRows(out var findID)) return;
if (MessageBox.Show("Удалить запись?", "Удалить", MessageBoxButtons.YesNo) != DialogResult.Yes) return;
try
{
_employeeRepositories.DeleteEmployee(findID);
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridView.DataSource = _employeeRepositories.GetEmployees();
dataGridView.Columns["ID"].Visible = false;
dataGridView.Columns["FullName"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRows(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ID"].Value);
return true;
}
}
}

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,217 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormItemOrder
{
/// <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()
{
buttonCancel = new Button();
buttonSave = new Button();
groupBoxAccessories = new GroupBox();
dataGridViewAccessories = new DataGridView();
ColumnAccessory = new DataGridViewComboBoxColumn();
ColumnCount = new DataGridViewTextBoxColumn();
labelEmployee = new Label();
labelClient = new Label();
labelDate = new Label();
labelTotalCost = new Label();
comboBoxEmployee = new ComboBox();
comboBoxClient = new ComboBox();
dateTimePickerData = new DateTimePicker();
numericUpDownNumTotalCost = new NumericUpDown();
groupBoxAccessories.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewAccessories).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownNumTotalCost).BeginInit();
SuspendLayout();
//
// buttonCancel
//
buttonCancel.Location = new Point(215, 445);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(122, 41);
buttonCancel.TabIndex = 8;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(12, 445);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(122, 41);
buttonSave.TabIndex = 7;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// groupBoxAccessories
//
groupBoxAccessories.Controls.Add(dataGridViewAccessories);
groupBoxAccessories.Location = new Point(464, 12);
groupBoxAccessories.Name = "groupBoxAccessories";
groupBoxAccessories.Size = new Size(307, 445);
groupBoxAccessories.TabIndex = 13;
groupBoxAccessories.TabStop = false;
groupBoxAccessories.Text = "Аксессуары:";
//
// dataGridViewAccessories
//
dataGridViewAccessories.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewAccessories.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewAccessories.Columns.AddRange(new DataGridViewColumn[] { ColumnAccessory, ColumnCount });
dataGridViewAccessories.Location = new Point(6, 26);
dataGridViewAccessories.Name = "dataGridViewAccessories";
dataGridViewAccessories.RowHeadersVisible = false;
dataGridViewAccessories.RowHeadersWidth = 51;
dataGridViewAccessories.Size = new Size(295, 413);
dataGridViewAccessories.TabIndex = 0;
//
// ColumnAccessory
//
ColumnAccessory.HeaderText = "Аксессуары";
ColumnAccessory.MinimumWidth = 6;
ColumnAccessory.Name = "ColumnAccessory";
//
// ColumnCount
//
ColumnCount.HeaderText = "Количество";
ColumnCount.MinimumWidth = 6;
ColumnCount.Name = "ColumnCount";
//
// labelEmployee
//
labelEmployee.AutoSize = true;
labelEmployee.Location = new Point(12, 24);
labelEmployee.Name = "labelEmployee";
labelEmployee.Size = new Size(82, 20);
labelEmployee.TabIndex = 14;
labelEmployee.Text = "Сотрудник";
//
// labelClient
//
labelClient.AutoSize = true;
labelClient.Location = new Point(12, 104);
labelClient.Name = "labelClient";
labelClient.Size = new Size(58, 20);
labelClient.TabIndex = 15;
labelClient.Text = "Клиент";
//
// labelDate
//
labelDate.AutoSize = true;
labelDate.Location = new Point(12, 192);
labelDate.Name = "labelDate";
labelDate.Size = new Size(41, 20);
labelDate.TabIndex = 16;
labelDate.Text = "Дата";
//
// labelTotalCost
//
labelTotalCost.AutoSize = true;
labelTotalCost.Location = new Point(12, 274);
labelTotalCost.Name = "labelTotalCost";
labelTotalCost.Size = new Size(133, 20);
labelTotalCost.TabIndex = 17;
labelTotalCost.Text = "Общая стоимость";
//
// comboBoxEmployee
//
comboBoxEmployee.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxEmployee.FormattingEnabled = true;
comboBoxEmployee.Location = new Point(194, 21);
comboBoxEmployee.Name = "comboBoxEmployee";
comboBoxEmployee.Size = new Size(238, 28);
comboBoxEmployee.TabIndex = 18;
//
// comboBoxClient
//
comboBoxClient.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxClient.FormattingEnabled = true;
comboBoxClient.Location = new Point(194, 101);
comboBoxClient.Name = "comboBoxClient";
comboBoxClient.Size = new Size(238, 28);
comboBoxClient.TabIndex = 19;
//
// dateTimePickerData
//
dateTimePickerData.Enabled = false;
dateTimePickerData.Location = new Point(194, 187);
dateTimePickerData.Name = "dateTimePickerData";
dateTimePickerData.Size = new Size(238, 27);
dateTimePickerData.TabIndex = 20;
//
// numericUpDownNumTotalCost
//
numericUpDownNumTotalCost.Location = new Point(194, 272);
numericUpDownNumTotalCost.Name = "numericUpDownNumTotalCost";
numericUpDownNumTotalCost.Size = new Size(238, 27);
numericUpDownNumTotalCost.TabIndex = 21;
numericUpDownNumTotalCost.Value = new decimal(new int[] { 1, 0, 0, 0 });
//
// FormItemOrder
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 498);
Controls.Add(numericUpDownNumTotalCost);
Controls.Add(dateTimePickerData);
Controls.Add(comboBoxClient);
Controls.Add(comboBoxEmployee);
Controls.Add(labelTotalCost);
Controls.Add(labelDate);
Controls.Add(labelClient);
Controls.Add(labelEmployee);
Controls.Add(groupBoxAccessories);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Name = "FormItemOrder";
StartPosition = FormStartPosition.CenterParent;
Text = "Заказ";
groupBoxAccessories.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewAccessories).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownNumTotalCost).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonCancel;
private Button buttonSave;
private GroupBox groupBoxAccessories;
private DataGridView dataGridViewAccessories;
private DataGridViewComboBoxColumn ColumnAccessory;
private DataGridViewTextBoxColumn ColumnCount;
private Label labelEmployee;
private Label labelClient;
private Label labelDate;
private Label labelTotalCost;
private ComboBox comboBoxEmployee;
private ComboBox comboBoxClient;
private DateTimePicker dateTimePickerData;
private NumericUpDown numericUpDownNumTotalCost;
}
}

View File

@ -0,0 +1,75 @@
using ProjectOptika.Scripts.Entities;
using ProjectOptika.Scripts.Repositories;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormItemOrder : Form
{
private readonly IOrderRepository _orderRepository;
public FormItemOrder(IOrderRepository orderRepository, IEmployeeRepository employeeRepository, IClientRepositiory clientRepositiory, IAccessoriesRepository accessoriesRepository)
{
InitializeComponent();
_orderRepository = orderRepository ??
throw new ArgumentNullException(nameof(orderRepository));
comboBoxEmployee.DataSource = employeeRepository.GetEmployees();
comboBoxEmployee.DisplayMember = "FullName";
comboBoxEmployee.ValueMember = "ID";
comboBoxClient.DataSource = clientRepositiory.GetClients();
comboBoxClient.DisplayMember = "FullName";
comboBoxClient.ValueMember = "ID";
ColumnAccessory.DataSource = accessoriesRepository.GetAccessories();
ColumnAccessory.DisplayMember = "Name";
ColumnAccessory.ValueMember = "ID";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (comboBoxClient.SelectedIndex < 0 ||
comboBoxEmployee.SelectedIndex < 0 ||
dataGridViewAccessories.RowCount < 1)
{
throw new Exception("Имеются незаполненные поля");
}
_orderRepository.CreateOrder(Order.CreateOperation(0,
(int)comboBoxEmployee.SelectedValue!,
(int)comboBoxClient.SelectedValue!,
(double)numericUpDownNumTotalCost.Value,
CreateListAccessoriesOrderReceptionsFromDataGrid()));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private List<AccessoriesOrder> CreateListAccessoriesOrderReceptionsFromDataGrid()
{
var list = new List<AccessoriesOrder>();
foreach (DataGridViewRow row in dataGridViewAccessories.Rows)
{
if (row.Cells["ColumnAccessory"].Value == null ||
row.Cells["ColumnCount"].Value == null)
{
continue;
}
list.Add(AccessoriesOrder.CreateElement(0,
Convert.ToInt32(row.Cells["ColumnAccessory"].Value),
Convert.ToInt32(row.Cells["ColumnCount"].Value)));
}
return list;
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
}
}

View File

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

View File

@ -0,0 +1,113 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormItemOrders
{
/// <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()
{
panel = new Panel();
buttonRemove = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
panel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// panel
//
panel.Controls.Add(buttonRemove);
panel.Controls.Add(buttonAdd);
panel.Dock = DockStyle.Right;
panel.Location = new Point(696, 0);
panel.Name = "panel";
panel.Size = new Size(104, 450);
panel.TabIndex = 8;
//
// buttonRemove
//
buttonRemove.BackgroundImage = Properties.Resources.Remove;
buttonRemove.BackgroundImageLayout = ImageLayout.Stretch;
buttonRemove.Location = new Point(3, 89);
buttonRemove.Name = "buttonRemove";
buttonRemove.Size = new Size(96, 71);
buttonRemove.TabIndex = 2;
buttonRemove.UseVisualStyleBackColor = true;
buttonRemove.Click += ButtonDel_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(3, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(96, 71);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Left;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(693, 450);
dataGridView.TabIndex = 9;
//
// FormItemOrders
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(panel);
Controls.Add(dataGridView);
Name = "FormItemOrders";
StartPosition = FormStartPosition.CenterParent;
Text = "Заказы";
Load += Form_Load;
panel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel;
private Button buttonRemove;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,92 @@
using ProjectOptika.Scripts.Repositories;
using Unity;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormItemOrders : Form
{
private readonly IUnityContainer _container;
private readonly IOrderRepository _orderRepository;
public FormItemOrders(IUnityContainer container, IOrderRepository orderRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_orderRepository = orderRepository ??
throw new ArgumentNullException(nameof(orderRepository));
}
private void Form_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridView.DataSource = _orderRepository.GetOrders();
dataGridView.Columns["ID"].Visible = false;
dataGridView.Columns["OrderDate"].DefaultCellStyle.Format = "dd MM yyyy";
}
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id =
Convert.ToInt32(dataGridView.SelectedRows[0].Cells["Id"].Value);
return true;
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormItemOrder>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDel_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление",
MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_orderRepository.DeleteOrder(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

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

View File

@ -0,0 +1,169 @@
namespace ProjectOptika
{
partial class FormOptika
{
/// <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()
{
menuStrip = new MenuStrip();
справочникиToolStripMenuItem = new ToolStripMenuItem();
аксессуарыToolStripMenuItem = new ToolStripMenuItem();
характеристикиToolStripMenuItem = new ToolStripMenuItem();
сотрудникToolStripMenuItem = new ToolStripMenuItem();
клиентToolStripMenuItem = new ToolStripMenuItem();
операцииToolStripMenuItem = new ToolStripMenuItem();
заказToolStripMenuItem = new ToolStripMenuItem();
отчетToolStripMenuItem = new ToolStripMenuItem();
directoryReportToolStripMenuItem = new ToolStripMenuItem();
productRatioToolStripMenuItem = new ToolStripMenuItem();
clientsReportToolStripMenuItem = new ToolStripMenuItem();
menuStrip.SuspendLayout();
SuspendLayout();
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { справочникиToolStripMenuItem, операцииToolStripMenuItem, отчетToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(800, 28);
menuStrip.TabIndex = 0;
menuStrip.Text = "menuStrip1";
//
// справочникиToolStripMenuItem
//
справочникиToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { аксессуарыToolStripMenuItem, характеристикиToolStripMenuItem, сотрудникToolStripMenuItem, клиентToolStripMenuItem });
справочникиToolStripMenuItem.Name = "справочникиToolStripMenuItem";
справочникиToolStripMenuItem.Size = new Size(117, 24);
справочникиToolStripMenuItem.Text = "Справочники";
//
// аксессуарыToolStripMenuItem
//
аксессуарыToolStripMenuItem.Name = "аксессуарыToolStripMenuItem";
аксессуарыToolStripMenuItem.Size = new Size(203, 26);
аксессуарыToolStripMenuItem.Text = "Аксессуар";
аксессуарыToolStripMenuItem.Click += AccessoriesToolStripMenuItem_Click;
//
// характеристикиToolStripMenuItem
//
характеристикиToolStripMenuItem.Name = "характеристикиToolStripMenuItem";
характеристикиToolStripMenuItem.Size = new Size(203, 26);
характеристикиToolStripMenuItem.Text = "Характеристики";
характеристикиToolStripMenuItem.Click += SpecificationToolStripMenuItem_Click;
//
// сотрудникToolStripMenuItem
//
сотрудникToolStripMenuItem.Name = "сотрудникToolStripMenuItem";
сотрудникToolStripMenuItem.Size = new Size(203, 26);
сотрудникToolStripMenuItem.Text = "Сотрудник";
сотрудникToolStripMenuItem.Click += EmplyeeToolStripMenuItem_Click;
//
// клиентToolStripMenuItem
//
клиентToolStripMenuItem.Name = "клиентToolStripMenuItem";
клиентToolStripMenuItem.Size = new Size(203, 26);
клиентToolStripMenuItem.Text = "Клиент";
клиентToolStripMenuItem.Click += ClientToolStripMenuItem_Click;
//
// операцииToolStripMenuItem
//
операцииToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { заказToolStripMenuItem });
операцииToolStripMenuItem.Name = "операцииToolStripMenuItem";
операцииToolStripMenuItem.Size = new Size(95, 24);
операцииToolStripMenuItem.Text = "Операции";
//
// заказToolStripMenuItem
//
заказToolStripMenuItem.Name = аказToolStripMenuItem";
заказToolStripMenuItem.Size = new Size(196, 26);
заказToolStripMenuItem.Text = "Оптовый заказ";
заказToolStripMenuItem.Click += ItemOrderToolStripMenuItem_Click;
//
// отчетToolStripMenuItem
//
отчетToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { directoryReportToolStripMenuItem, productRatioToolStripMenuItem, clientsReportToolStripMenuItem });
отчетToolStripMenuItem.Name = "отчетToolStripMenuItem";
отчетToolStripMenuItem.Size = new Size(73, 24);
отчетToolStripMenuItem.Text = "Отчеты";
//
// directoryReportToolStripMenuItem
//
directoryReportToolStripMenuItem.Name = "directoryReportToolStripMenuItem";
directoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W;
directoryReportToolStripMenuItem.Size = new Size(350, 26);
directoryReportToolStripMenuItem.Text = "Документ со справочниками";
directoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click;
//
// productRatioToolStripMenuItem
//
productRatioToolStripMenuItem.Name = "productRatioToolStripMenuItem";
productRatioToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.P;
productRatioToolStripMenuItem.Size = new Size(350, 26);
productRatioToolStripMenuItem.Text = "Сформировать учет оплат";
productRatioToolStripMenuItem.Click += ProductRatioToolStripMenuItem_Click;
//
// clientsReportToolStripMenuItem
//
clientsReportToolStripMenuItem.Name = "clientsReportToolStripMenuItem";
clientsReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E;
clientsReportToolStripMenuItem.Size = new Size(350, 26);
clientsReportToolStripMenuItem.Text = "Отчет по клиентам";
clientsReportToolStripMenuItem.Click += ClientsReportToolStripMenuItem_Click;
//
// FormOptika
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
BackgroundImage = Properties.Resources.optika;
BackgroundImageLayout = ImageLayout.Stretch;
ClientSize = new Size(800, 450);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormOptika";
StartPosition = FormStartPosition.CenterParent;
Text = "Оптика";
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private MenuStrip menuStrip;
private ToolStripMenuItem справочникиToolStripMenuItem;
private ToolStripMenuItem операцииToolStripMenuItem;
private ToolStripMenuItem отчетToolStripMenuItem;
private ToolStripMenuItem аксессуарыToolStripMenuItem;
private ToolStripMenuItem заказToolStripMenuItem;
private ToolStripMenuItem характеристикиToolStripMenuItem;
private ToolStripMenuItem сотрудникToolStripMenuItem;
private ToolStripMenuItem клиентToolStripMenuItem;
private ToolStripMenuItem directoryReportToolStripMenuItem;
private ToolStripMenuItem productRatioToolStripMenuItem;
private ToolStripMenuItem clientsReportToolStripMenuItem;
}
}

View File

@ -0,0 +1,117 @@
using ProjectOptika.Scripts.Forms;
using Unity;
namespace ProjectOptika
{
public partial class FormOptika : Form
{
private IUnityContainer _container;
public FormOptika(IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void AccessoriesToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormAccessories>().ShowDialog();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void SpecificationToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormSpecifications>().ShowDialog();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ItemOrderToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormItemOrders>().ShowDialog();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void EmplyeeToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormEmplyees>().ShowDialog();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ClientToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormClients>().ShowDialog();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDirectoryReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ProductRatioToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormClientCostRatioReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ClientsReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormClientsReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

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

View File

@ -0,0 +1,210 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormSpecification
{
/// <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()
{
labelMaterial = new Label();
textBoxMaterial = new TextBox();
textBoxAstigmatism = new TextBox();
labelAstigmatism = new Label();
textBoxDioptericity = new TextBox();
labelDioptericity = new Label();
textBoxOriginCountry = new TextBox();
labelOriginCountry = new Label();
labelTimeProduction = new Label();
numericUpDownTimeProduction = new NumericUpDown();
buttonCancel = new Button();
buttonSave = new Button();
comboBoxAccessory = new ComboBox();
labelAccessory = new Label();
((System.ComponentModel.ISupportInitialize)numericUpDownTimeProduction).BeginInit();
SuspendLayout();
//
// labelMaterial
//
labelMaterial.AutoSize = true;
labelMaterial.Location = new Point(12, 69);
labelMaterial.Name = "labelMaterial";
labelMaterial.Size = new Size(78, 20);
labelMaterial.TabIndex = 0;
labelMaterial.Text = "Материал";
//
// textBoxMaterial
//
textBoxMaterial.Location = new Point(175, 66);
textBoxMaterial.Name = "textBoxMaterial";
textBoxMaterial.Size = new Size(125, 27);
textBoxMaterial.TabIndex = 1;
//
// textBoxAstigmatism
//
textBoxAstigmatism.Location = new Point(175, 122);
textBoxAstigmatism.Name = "textBoxAstigmatism";
textBoxAstigmatism.Size = new Size(125, 27);
textBoxAstigmatism.TabIndex = 3;
//
// labelAstigmatism
//
labelAstigmatism.AutoSize = true;
labelAstigmatism.Location = new Point(12, 125);
labelAstigmatism.Name = "labelAstigmatism";
labelAstigmatism.Size = new Size(99, 20);
labelAstigmatism.TabIndex = 2;
labelAstigmatism.Text = "Астигматизм";
//
// textBoxDioptericity
//
textBoxDioptericity.Location = new Point(175, 178);
textBoxDioptericity.Name = "textBoxDioptericity";
textBoxDioptericity.Size = new Size(125, 27);
textBoxDioptericity.TabIndex = 5;
//
// labelDioptericity
//
labelDioptericity.AutoSize = true;
labelDioptericity.Location = new Point(12, 181);
labelDioptericity.Name = "labelDioptericity";
labelDioptericity.Size = new Size(118, 20);
labelDioptericity.TabIndex = 4;
labelDioptericity.Text = "Диоптрийность";
//
// textBoxOriginCountry
//
textBoxOriginCountry.Location = new Point(175, 227);
textBoxOriginCountry.Name = "textBoxOriginCountry";
textBoxOriginCountry.Size = new Size(125, 27);
textBoxOriginCountry.TabIndex = 7;
//
// labelOriginCountry
//
labelOriginCountry.AutoSize = true;
labelOriginCountry.Location = new Point(12, 230);
labelOriginCountry.Name = "labelOriginCountry";
labelOriginCountry.Size = new Size(155, 20);
labelOriginCountry.TabIndex = 6;
labelOriginCountry.Text = "Страна изготовителя";
//
// labelTimeProduction
//
labelTimeProduction.AutoSize = true;
labelTimeProduction.Location = new Point(12, 280);
labelTimeProduction.Name = "labelTimeProduction";
labelTimeProduction.Size = new Size(121, 20);
labelTimeProduction.TabIndex = 8;
labelTimeProduction.Text = "Время поставки";
//
// numericUpDownTimeProduction
//
numericUpDownTimeProduction.Location = new Point(175, 278);
numericUpDownTimeProduction.Name = "numericUpDownTimeProduction";
numericUpDownTimeProduction.Size = new Size(125, 27);
numericUpDownTimeProduction.TabIndex = 9;
//
// buttonCancel
//
buttonCancel.Location = new Point(175, 331);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(94, 29);
buttonCancel.TabIndex = 11;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(36, 331);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(94, 29);
buttonSave.TabIndex = 10;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// comboBoxAccessory
//
comboBoxAccessory.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxAccessory.FormattingEnabled = true;
comboBoxAccessory.Location = new Point(175, 12);
comboBoxAccessory.Name = "comboBoxAccessory";
comboBoxAccessory.Size = new Size(125, 28);
comboBoxAccessory.TabIndex = 20;
//
// labelAccessory
//
labelAccessory.AutoSize = true;
labelAccessory.Location = new Point(12, 20);
labelAccessory.Name = "labelAccessory";
labelAccessory.Size = new Size(79, 20);
labelAccessory.TabIndex = 19;
labelAccessory.Text = "Аксессуар";
//
// FormSpecification
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(316, 378);
Controls.Add(comboBoxAccessory);
Controls.Add(labelAccessory);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(numericUpDownTimeProduction);
Controls.Add(labelTimeProduction);
Controls.Add(textBoxOriginCountry);
Controls.Add(labelOriginCountry);
Controls.Add(textBoxDioptericity);
Controls.Add(labelDioptericity);
Controls.Add(textBoxAstigmatism);
Controls.Add(labelAstigmatism);
Controls.Add(textBoxMaterial);
Controls.Add(labelMaterial);
Name = "FormSpecification";
StartPosition = FormStartPosition.CenterParent;
Text = "Характеристика";
((System.ComponentModel.ISupportInitialize)numericUpDownTimeProduction).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelMaterial;
private TextBox textBoxMaterial;
private TextBox textBoxAstigmatism;
private Label labelAstigmatism;
private TextBox textBoxDioptericity;
private Label labelDioptericity;
private TextBox textBoxOriginCountry;
private Label labelOriginCountry;
private Label labelTimeProduction;
private NumericUpDown numericUpDownTimeProduction;
private Button buttonCancel;
private Button buttonSave;
private ComboBox comboBoxAccessory;
private Label labelAccessory;
}
}

View File

@ -0,0 +1,85 @@
using ProjectOptika.Scripts.Entities;
using ProjectOptika.Scripts.Repositories;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormSpecification : Form
{
private readonly ISpecificationsRepository _specificationsRepositories;
private int? _specificationsID;
public int ID
{
set
{
try
{
var specifications = _specificationsRepositories.GetSpecificationsByID(value);
if (specifications == null) throw new InvalidDataException(nameof(specifications));
_specificationsID = specifications.ID;
textBoxMaterial.Text = specifications.Material;
textBoxAstigmatism.Text = specifications.Astigmatism;
textBoxDioptericity.Text = specifications.Dioptericity;
textBoxOriginCountry.Text = specifications.OriginCountry;
numericUpDownTimeProduction.Value = (decimal)specifications.TimeProduction;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormSpecification(ISpecificationsRepository specifications, IAccessoriesRepository accessories)
{
InitializeComponent();
_specificationsRepositories = specifications
?? throw new ArgumentNullException(nameof(specifications));
comboBoxAccessory.DataSource = accessories.GetAccessories();
comboBoxAccessory.DisplayMember = "Name";
comboBoxAccessory.ValueMember = "ID";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrEmpty(textBoxMaterial.Text) || string.IsNullOrEmpty(textBoxAstigmatism.Text) ||
string.IsNullOrEmpty(textBoxDioptericity.Text) || string.IsNullOrEmpty(textBoxOriginCountry.Text))
{
throw new Exception("Имеются незаполненные данные");
}
if (_specificationsID.HasValue)
{
_specificationsRepositories.UpdateSpecifications(CreateSpecifications(_specificationsID.Value));
}
else
{
_specificationsRepositories.CreateSpecifications(CreateSpecifications(0));
}
Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении сохранении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e)
{
Close();
}
private Specifications CreateSpecifications(int id)
{
return Specifications.CreateEntity(id, (int)comboBoxAccessory.SelectedValue!, textBoxMaterial.Text, textBoxAstigmatism.Text, textBoxDioptericity.Text, textBoxOriginCountry.Text, (double)numericUpDownTimeProduction.Value);
}
}
}

View File

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

View File

@ -0,0 +1,127 @@
namespace ProjectOptika.Scripts.Forms
{
partial class FormSpecifications
{
/// <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()
{
panel = new Panel();
buttonRemove = new Button();
buttonUpdate = new Button();
buttonAdd = new Button();
dataGridView = new DataGridView();
panel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// panel
//
panel.Controls.Add(buttonRemove);
panel.Controls.Add(buttonUpdate);
panel.Controls.Add(buttonAdd);
panel.Dock = DockStyle.Right;
panel.Location = new Point(696, 0);
panel.Name = "panel";
panel.Size = new Size(104, 450);
panel.TabIndex = 6;
//
// buttonRemove
//
buttonRemove.BackgroundImage = Properties.Resources.Remove;
buttonRemove.BackgroundImageLayout = ImageLayout.Stretch;
buttonRemove.Location = new Point(3, 166);
buttonRemove.Name = "buttonRemove";
buttonRemove.Size = new Size(96, 71);
buttonRemove.TabIndex = 2;
buttonRemove.UseVisualStyleBackColor = true;
buttonRemove.Click += ButtonRemove_Click;
//
// buttonUpdate
//
buttonUpdate.BackgroundImage = Properties.Resources.Update;
buttonUpdate.BackgroundImageLayout = ImageLayout.Stretch;
buttonUpdate.Location = new Point(3, 89);
buttonUpdate.Name = "buttonUpdate";
buttonUpdate.Size = new Size(96, 71);
buttonUpdate.TabIndex = 1;
buttonUpdate.UseVisualStyleBackColor = true;
buttonUpdate.Click += ButtonUpdate_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.Add;
buttonAdd.BackgroundImageLayout = ImageLayout.Stretch;
buttonAdd.Location = new Point(3, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(96, 71);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridView
//
dataGridView.AllowUserToAddRows = false;
dataGridView.AllowUserToDeleteRows = false;
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(0, 0);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.ReadOnly = true;
dataGridView.RowHeadersVisible = false;
dataGridView.RowHeadersWidth = 51;
dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView.Size = new Size(800, 450);
dataGridView.TabIndex = 7;
//
// FormSpecifications
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(panel);
Controls.Add(dataGridView);
Name = "FormSpecifications";
StartPosition = FormStartPosition.CenterParent;
Text = "Характеристики";
Load += Form_Load;
panel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel;
private Button buttonRemove;
private Button buttonUpdate;
private Button buttonAdd;
private DataGridView dataGridView;
}
}

View File

@ -0,0 +1,101 @@
using ProjectOptika.Scripts.Repositories;
using Unity;
namespace ProjectOptika.Scripts.Forms
{
public partial class FormSpecifications : Form
{
private readonly IUnityContainer _container;
private readonly ISpecificationsRepository _specificationRepositories;
public FormSpecifications(IUnityContainer container, ISpecificationsRepository lensRepositories)
{
InitializeComponent();
_container = container ??
throw new ArgumentException(nameof(container));
_specificationRepositories = lensRepositories ??
throw new ArgumentException(nameof(lensRepositories));
}
private void Form_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormSpecification>().ShowDialog();
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonUpdate_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRows(out var findID)) return;
try
{
var form = _container.Resolve<FormSpecification>();
form.ID = findID;
form.ShowDialog();
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonRemove_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRows(out var findID)) return;
if (MessageBox.Show("Удалить запись?", "Удалить", MessageBoxButtons.YesNo) != DialogResult.Yes) return;
try
{
_specificationRepositories.DeleteSpecifications(findID);
LoadList();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList()
{
dataGridView.DataSource = _specificationRepositories.GetSpecifications();
dataGridView.Columns["ID"].Visible = false;
}
private bool TryGetIdentifierFromSelectedRows(out int id)
{
id = 0;
if (dataGridView.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridView.SelectedRows[0].Cells["ID"].Value);
return true;
}
}
}

View File

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

View File

@ -1,3 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ProjectOptika.Scripts.Repositories;
using ProjectOptika.Scripts.Repositories.Implementations;
using Serilog;
using Unity;
using Unity.Microsoft.Logging;
namespace ProjectOptika.Scripts namespace ProjectOptika.Scripts
{ {
internal static class Program internal static class Program
@ -11,7 +19,35 @@ namespace ProjectOptika.Scripts
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new Form1()); Application.Run(CreateContainer().Resolve<FormOptika>());
}
private static UnityContainer CreateContainer () {
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType<IAccessoriesRepository, AccessoriesRepository>();
container.RegisterType<IClientRepositiory, ClientRepositiory>();
container.RegisterType<IEmployeeRepository, EmployeeRepository>();
container.RegisterType<ISpecificationsRepository, SpecificationsRepository>();
container.RegisterType<IOrderRepository, OrderRepository>();
container.RegisterType<IConnectionString, ConnectionString>();
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
} }
} }
} }

View File

@ -0,0 +1,45 @@
using Microsoft.Extensions.Logging;
using ProjectOptika.Scripts.Repositories;
namespace ProjectOptika.Scripts.Reports
{
internal class ChartReport
{
private readonly IOrderRepository _orderRepository;
private readonly ILogger<ChartReport> _logger;
public ChartReport(IOrderRepository orderRepository,
ILogger<ChartReport> logger)
{
_orderRepository = orderRepository ??
throw new ArgumentNullException(nameof(orderRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateChart(string filePath, DateTime dateTime)
{
try
{
new PdfBuilder(filePath)
.AddHeader("Учет оплат клиентов")
.AddPieChart($"Оплаты клиентов за {dateTime: dd MMMM yyyy}", GetData(dateTime))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<(string Caption, double Value)> GetData(DateTime dateTime)
{
return _orderRepository.GetOrders(startDate: dateTime.Date, endDate: dateTime.Date.AddDays(1))
.GroupBy(x => x.ClientFullName, (key, group) => new {
Client = key,
Count = group.Sum(x => x.TotalCost)
})
.Select(x => (x.Client, (double)x.Count))
.ToList();
}
}
}

View File

@ -0,0 +1,105 @@
using Microsoft.Extensions.Logging;
using ProjectOptika.Scripts.Repositories;
namespace ProjectOptika.Scripts.Reports
{
internal class DocReport
{
private readonly IAccessoriesRepository _accessoriesRepository;
private readonly IClientRepositiory _clientRepositiory;
private readonly IEmployeeRepository _employeeRepository;
private readonly ISpecificationsRepository _specificationsRepository;
private readonly ILogger<DocReport> _logger;
public DocReport(IAccessoriesRepository accessoriesRepository, IClientRepositiory clientRepositiory, IEmployeeRepository employeeRepository, ISpecificationsRepository specificationsRepository,
ILogger<DocReport> logger)
{
_accessoriesRepository = accessoriesRepository ??
throw new ArgumentNullException(nameof(accessoriesRepository));
_clientRepositiory = clientRepositiory ??
throw new ArgumentNullException(nameof(clientRepositiory));
_employeeRepository = employeeRepository ??
throw new ArgumentNullException(nameof(employeeRepository));
_specificationsRepository = specificationsRepository ??
throw new ArgumentNullException(nameof(specificationsRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateDoc(string filePath, bool includeAccessories, bool includeSpecification,
bool includeEmployees, bool includeClients)
{
try
{
var builder = new WordBuilder(filePath).AddHeader("Документ со справочниками");
if (includeAccessories)
{
builder.AddParagraph("Аксессуары")
.AddTable([2400, 2400, 2400, 1200, 1200, 1200, 2400],
GetAccessories());
}
if (includeSpecification)
{
builder.AddParagraph("Характеристики")
.AddTable([1200, 1200, 2400, 1200, 1200, 2400], GetSpecification());
}
if (includeEmployees)
{
builder.AddParagraph("Сотрудники")
.AddTable([2400, 2400, 2400, 2400], GetEmploeyees());
}
if (includeClients)
{
builder.AddParagraph("Клиент")
.AddTable([2400, 2400, 2400, 2400, 2400], GetClients());
}
builder.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetAccessories()
{
return [
["Название", "Бренд", "Стоимость", "Наличие в магазине", "Наличие на складе", "Дата доставки", "Тип"],
.. _accessoriesRepository.GetAccessories()
.Select(x => new string[] { x.Name, x.Brand, x.Cost.ToString(), x.StockAvailability.ToString(), x.AvailabilityStore.ToString(), x.DeliveryDate.ToString(), x.CategoryName.ToString() }),
];
}
private List<string[]> GetSpecification()
{
return [
["ID аксессуара", "Материал", "Астигматизм", "Диоптрийность", "Страна изготовителя", "Время доставки"],
.. _specificationsRepository
.GetSpecifications()
.Select(x => new string[] { x.AccessoriesID.ToString(), x.Material, x.Astigmatism, x.Dioptericity, x.OriginCountry, x.TimeProduction.ToString()}),
];
}
private List<string[]> GetEmploeyees()
{
return [
["Имя", "Отчество", "Фамилия", "Должность"],
.. _employeeRepository
.GetEmployees()
.Select(x => new string[] { x.FirstName, x.SecondName, x.Surname, x.PositionEmployee.ToString() }),
];
}
private List<string[]> GetClients()
{
return [
["Имя", "Отчество", "Фамилия", "Номер телефона", "Тип клиента"],
.. _clientRepositiory
.GetClients()
.Select(x => new string[] { x.FirstName, x.SecondName, x.Surname, x.PhoneNumber, x.ClientType.ToString() }),
];
}
}
}

View File

@ -0,0 +1,318 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace ProjectOptika.Scripts.Reports
{
internal class ExcelBuilder
{
private readonly string _filePath;
private readonly SheetData _sheetData;
private readonly MergeCells _mergeCells;
private readonly Columns _columns;
private uint _rowIndex = 0;
public ExcelBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_sheetData = new SheetData();
_mergeCells = new MergeCells();
_columns = new Columns();
_rowIndex = 1;
}
public ExcelBuilder AddHeader(string header, int startIndex, int count)
{
CreateCell(startIndex, _rowIndex, header, StyleIndex.BoldTextWithBorders);
for (int i = startIndex + 1; i < startIndex + count; ++i)
{
CreateCell(i, _rowIndex, "", StyleIndex.BoldTextWithBorders);
}
_mergeCells.Append(new MergeCell()
{
Reference = new StringValue($"{GetExcelColumnName(startIndex)}{_rowIndex}:{GetExcelColumnName(startIndex + count - 1)}{_rowIndex}")
});
_rowIndex++;
return this;
}
public ExcelBuilder AddParagraph(string text, int columnIndex)
{
CreateCell(columnIndex, _rowIndex++, text, StyleIndex.SimpleTextWithoutBorder);
return this;
}
public ExcelBuilder AddTable(int[] columnsWidths, List<string[]> data)
{
if (columnsWidths == null || columnsWidths.Length == 0)
{
throw new ArgumentNullException(nameof(columnsWidths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != columnsWidths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
uint counter = 1;
int coef = 2;
_columns.Append(columnsWidths.Select(x => new Column
{
Min = counter,
Max = counter++,
Width = x * coef,
CustomWidth = true
}));
for (var j = 0; j < data.First().Length; ++j)
{
CreateCell(j, _rowIndex, data.First()[j], StyleIndex.BoldTextWithBorders);
}
_rowIndex++;
for (var i = 1; i < data.Count - 1; ++i)
{
for (var j = 0; j < data[i].Length; ++j)
{
CreateCell(j, _rowIndex, data[i][j], StyleIndex.SimpleTextWithBorders);
}
_rowIndex++;
}
for (var j = 0; j < data.Last().Length; ++j)
{
CreateCell(j, _rowIndex, data.Last()[j], StyleIndex.BoldTextWithBorders);
}
_rowIndex++;
return this;
}
public void Build()
{
using var spreadsheetDocument = SpreadsheetDocument.Create(_filePath, SpreadsheetDocumentType.Workbook);
var workbookpart = spreadsheetDocument.AddWorkbookPart();
GenerateStyle(workbookpart);
workbookpart.Workbook = new Workbook();
var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
if (_columns.HasChildren)
{
worksheetPart.Worksheet.Append(_columns);
}
worksheetPart.Worksheet.Append(_sheetData);
var sheets = spreadsheetDocument.WorkbookPart!.Workbook.AppendChild(new Sheets());
var sheet = new Sheet()
{
Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Лист 1"
};
sheets.Append(sheet);
if (_mergeCells.HasChildren)
{
worksheetPart.Worksheet.InsertAfter(_mergeCells, worksheetPart.Worksheet.Elements<SheetData>().First());
}
}
private static void GenerateStyle(WorkbookPart workbookPart)
{
var workbookStylesPart = workbookPart.AddNewPart<WorkbookStylesPart>();
workbookStylesPart.Stylesheet = new Stylesheet();
var fonts = new Fonts()
{
Count = 2,
KnownFonts = BooleanValue.FromBoolean(true)
};
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
}
});
fonts.Append(new DocumentFormat.OpenXml.Spreadsheet.Font
{
FontSize = new FontSize() { Val = 11 },
FontName = new FontName() { Val = "Calibri" },
FontFamilyNumbering = new FontFamilyNumbering() { Val = 2 },
FontScheme = new FontScheme()
{
Val = new EnumValue<FontSchemeValues>(FontSchemeValues.Minor)
},
Bold = new Bold()
});
workbookStylesPart.Stylesheet.Append(fonts);
var fills = new Fills() { Count = 1 };
fills.Append(new Fill
{
PatternFill = new PatternFill()
{
PatternType = new EnumValue<PatternValues>(PatternValues.None)
}
});
workbookStylesPart.Stylesheet.Append(fills);
var borders = new Borders() { Count = 2 };
borders.Append(new Border
{
LeftBorder = new LeftBorder(),
RightBorder = new RightBorder(),
TopBorder = new TopBorder(),
BottomBorder = new BottomBorder(),
DiagonalBorder = new DiagonalBorder()
});
borders.Append(new Border
{
LeftBorder = new LeftBorder() { Style = BorderStyleValues.Thin },
RightBorder = new RightBorder() { Style = BorderStyleValues.Thin },
TopBorder = new TopBorder() { Style = BorderStyleValues.Thin },
BottomBorder = new BottomBorder() { Style = BorderStyleValues.Thin },
DiagonalBorder = new DiagonalBorder()
});
workbookStylesPart.Stylesheet.Append(borders);
var cellFormats = new CellFormats() { Count = 4 };
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 0,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 0,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
cellFormats.Append(new CellFormat
{
NumberFormatId = 0,
FormatId = 0,
FontId = 1,
BorderId = 1,
FillId = 0,
Alignment = new Alignment()
{
Horizontal = HorizontalAlignmentValues.Left,
Vertical = VerticalAlignmentValues.Center,
WrapText = true
}
});
workbookStylesPart.Stylesheet.Append(cellFormats);
}
private enum StyleIndex
{
SimpleTextWithoutBorder = 0,
SimpleTextWithBorders = 1,
BoldTextWithoutBorders = 2,
BoldTextWithBorders = 3
}
private void CreateCell(int columnIndex, uint rowIndex, string text, StyleIndex styleIndex)
{
var columnName = GetExcelColumnName(columnIndex);
var cellReference = columnName + rowIndex;
var row = _sheetData.Elements<Row>().FirstOrDefault(r => r.RowIndex == rowIndex);
if (row == null)
{
row = new Row() { RowIndex = rowIndex };
_sheetData.Append(row);
}
var newCell = row.Elements<Cell>()
.FirstOrDefault(c => c.CellReference != null && c.CellReference.Value == columnName + rowIndex);
if (newCell == null)
{
Cell? refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if (cell.CellReference?.Value != null && cell.CellReference.Value.Length == cellReference.Length)
{
if (string.Compare(cell.CellReference.Value, cellReference, true) > 0)
{
refCell = cell;
break;
}
}
}
newCell = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell, refCell);
}
newCell.CellValue = new CellValue(text);
newCell.DataType = CellValues.String;
newCell.StyleIndex = (uint)styleIndex;
}
private static string GetExcelColumnName(int columnNumber)
{
columnNumber += 1;
int dividend = columnNumber;
string columnName = string.Empty;
int modulo;
while (dividend > 0)
{
modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
}
}

View File

@ -0,0 +1,83 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
namespace ProjectOptika.Scripts.Reports
{
internal class PdfBuilder
{
private readonly string _filePath;
private readonly Document _document;
public PdfBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
DefineStyles();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
public PdfBuilder AddHeader(string header)
{
_document.AddSection().AddParagraph(header, "NormalBold");
return this;
}
public PdfBuilder AddPieChart(string title, List<(string Caption, double Value)> data)
{
if (data == null || data.Count == 0)
{
return this;
}
var chart = new Chart(ChartType.Pie2D);
var series = chart.SeriesCollection.AddSeries();
series.Add(data.Select(x => x.Value).ToArray());
var xseries = chart.XValues.AddXSeries();
xseries.Add(data.Select(x => x.Caption).ToArray());
chart.DataLabel.Type = DataLabelType.Percent;
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(12);
chart.TopArea.AddParagraph(title);
chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true;
chart.PlotArea.LineFormat.Width = 1;
chart.PlotArea.LineFormat.Visible = true;
chart.TopArea.AddLegend();
_document.LastSection.Add(chart);
return this;
}
public void Build()
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(_filePath);
}
private void DefineStyles()
{
// Создаем стиль для заголовка (жирный)
var headerStyle = _document.Styles.AddStyle("NormalBold", "Normal");
headerStyle.Font.Bold = true;
}
}
}

View File

@ -0,0 +1,88 @@
using Microsoft.Extensions.Logging;
using ProjectOptika.Scripts.Repositories;
namespace ProjectOptika.Scripts.Reports
{
internal class TableReport
{
private readonly IOrderRepository _orderRepository;
private readonly IEmployeeRepository _employeeRepository;
private readonly IClientRepositiory _clientRepositiory;
private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Дата", "Сотрудник", "Общее количество клиентов"];
public TableReport(IOrderRepository orderRepository, IClientRepositiory clientRepositiory, IEmployeeRepository employeeRepository, ILogger<TableReport> logger)
{
_orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
_clientRepositiory = clientRepositiory ?? throw new ArgumentNullException(nameof(clientRepositiory));
_employeeRepository = employeeRepository ?? throw new ArgumentNullException(nameof(employeeRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int emplyeeID, DateTime startDate, DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка по заказам", 0, 4)
.AddParagraph($"за период c {startDate: dd.MM.yyyy} по {endDate:dd.MM.yyyy}", 0)
.AddTable([15, 20, 25], GetData(emplyeeID, startDate, endDate))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetData(int employeeID, DateTime startDate, DateTime endDate)
{
var orders = _orderRepository.GetOrders(startDate: startDate, endDate: endDate, employeeID: employeeID);
var employees = _employeeRepository.GetEmployees();
var employeesNames = _employeeRepository.GetEmployees().ToDictionary(d => d.ID, d => d.FullName);
var clientsNames = _clientRepositiory.GetClients().ToList();
var data = orders
.Join(employees, r => r.EmployeeID, p => p.ID, (r, p) => new
{
Date = r.OrderDate,
EmployeeID = p.ID,
ClientID = r.ClientID,
TotalCost = r.TotalCost
})
.OrderBy(x => x.Date)
.GroupBy(x => x.Date)
.Select(g => new
{
Date = g.Key,
Totals = g.Count()
});
var result = new List<string[]> { item };
Random r = new Random();
foreach (var entry in data)
{
result.Add(new string[]
{
entry.Date.ToString("dd.MM.yyyy"),
employeesNames.ContainsKey(employeeID) ? employeesNames[employeeID] : string.Empty,
entry.Totals.ToString(),
});
}
var totalPatients = data.Sum(x => x.Totals);
result.Add(new string[]
{
"Всего",
"",
totalPatients.ToString()
});
return result;
}
}
}

View File

@ -0,0 +1,94 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
namespace ProjectOptika.Scripts.Reports
{
internal class WordBuilder
{
private readonly string _filePath;
private readonly Document _document;
private readonly Body _body;
public WordBuilder(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentNullException(nameof(filePath));
}
if (File.Exists(filePath))
{
File.Delete(filePath);
}
_filePath = filePath;
_document = new Document();
_body = _document.AppendChild(new Body());
}
public WordBuilder AddHeader(string header)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
// прописать настройки под жирный текст
run.RunProperties = new RunProperties(new Bold());
run.AppendChild(new Text(header));
return this;
}
public WordBuilder AddParagraph(string text)
{
var paragraph = _body.AppendChild(new Paragraph());
var run = paragraph.AppendChild(new Run());
run.AppendChild(new Text(text));
return this;
}
public WordBuilder AddTable(int[] widths, List<string[]> data)
{
if (widths == null || widths.Length == 0)
{
throw new ArgumentNullException(nameof(widths));
}
if (data == null || data.Count == 0)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Any(x => x.Length != widths.Length))
{
throw new InvalidOperationException("widths.Length != data.Length");
}
var table = new Table();
table.AppendChild(new TableProperties(
new TableBorders(
new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 },
new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 12 }
)
));
// Заголовок
var tr = new TableRow();
for (var j = 0; j < widths.Length; ++j)
{
tr.Append(new TableCell(
new TableCellProperties(new TableCellWidth() { Width = widths[j].ToString() }),
new Paragraph(new Run(new RunProperties(new Bold()), new Text(data.First()[j])))));
}
table.Append(tr);
// Данные
table.Append(data.Skip(1).Select(x =>
new TableRow(x.Select(y => new TableCell(new Paragraph(new Run(new Text(y))))))));
_body.Append(table);
return this;
}
public void Build()
{
using var wordDocument = WordprocessingDocument.Create(_filePath, WordprocessingDocumentType.Document);
var mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = _document;
}
}
}

View File

@ -0,0 +1,17 @@
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories
{
public interface IAccessoriesRepository
{
IEnumerable<Accessories> GetAccessories();
Accessories GetAccessoriesByID(int id);
void CreateAccessories(Accessories accessories);
void UpdateAccessories(Accessories accessories);
void DeleteAccessories(int id);
}
}

View File

@ -0,0 +1,18 @@
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories
{
public interface IClientRepositiory
{
IEnumerable<Client> GetClients();
Client GetClientById(int id);
void CreateClient(Client client);
void UpdateClient(Client client);
void DeleteClient(int id);
}
}

View File

@ -0,0 +1,8 @@
namespace ProjectOptika.Scripts.Repositories
{
public interface IConnectionString
{
public string ConnectionString { get; }
}
}

View File

@ -0,0 +1,17 @@
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories
{
public interface IEmployeeRepository
{
IEnumerable<Employee> GetEmployees();
Employee GetEmployeerByID(int id);
void CreateEmployee(Employee employee);
void UpdateEmployee(Employee employee);
void DeleteEmployee(int id);
}
}

View File

@ -0,0 +1,13 @@
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories
{
public interface IOrderRepository
{
IEnumerable<Order> GetOrders(DateTime? startDate = null, DateTime? endDate = null, double? totalCost = null, int? id = null, int? employeeID = null, int? clientID = null);
void CreateOrder(Order order);
void DeleteOrder(int id);
}
}

View File

@ -0,0 +1,17 @@
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories
{
public interface ISpecificationsRepository
{
IEnumerable<Specifications> GetSpecifications();
Specifications GetSpecificationsByID(int id);
void CreateSpecifications(Specifications specifications);
void UpdateSpecifications(Specifications specifications);
void DeleteSpecifications(int id);
}
}

View File

@ -0,0 +1,126 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories.Implementations
{
public class AccessoriesRepository : IAccessoriesRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<AccessoriesRepository> _logger;
public AccessoriesRepository(IConnectionString connectionString, ILogger<AccessoriesRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateAccessories(Accessories accessories)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(accessories));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Accessories (Name, Brand, Cost, StockAvailability, AvailabilityStore, DeliveryDate, CategoryName)
VALUES (@Name, @Brand, @Cost, @StockAvailability, @AvailabilityStore, @DeliveryDate, @CategoryName)";
connection.Execute(queryInsert, accessories);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteAccessories(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Accessories
WHERE ID=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Accessories> GetAccessories()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Accessories";
var accessory = connection.Query<Accessories>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(accessory));
return accessory;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Accessories GetAccessoriesByID(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Accessories
WHERE ID=@id";
var accessory = connection.QueryFirst<Accessories>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(accessory));
return accessory;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateAccessories(Accessories accessories)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(accessories));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Accessories
SET
Name=@Name,
Brand=@Brand,
Cost=@Cost,
StockAvailability=@StockAvailability,
AvailabilityStore=@AvailabilityStore,
DeliveryDate=@DeliveryDate,
CategoryName=@CategoryName
WHERE ID=@ID";
connection.Execute(queryUpdate, accessories);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -0,0 +1,124 @@
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOptika.Scripts.Entities;
using Dapper;
namespace ProjectOptika.Scripts.Repositories.Implementations
{
public class ClientRepositiory : IClientRepositiory
{
private readonly IConnectionString _connectionString;
private readonly ILogger<ClientRepositiory> _logger;
public ClientRepositiory(IConnectionString connectionString, ILogger<ClientRepositiory> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateClient(Client client)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(client));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Client (ClientType, FirstName, SecondName, Surname, PhoneNumber)
VALUES (@ClientType, @FirstName, @SecondName, @Surname, @PhoneNumber)";
connection.Execute(queryInsert, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteClient(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Client
WHERE ID=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Client GetClientById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Client
WHERE ID=@id";
var client = connection.QueryFirst<Client>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(client));
return client;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Client> GetClients()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Client";
var clients = connection.Query<Client>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(clients));
return clients;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateClient(Client client)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(client));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Client
SET
ClientType=@ClientType,
FirstName=@FirstName,
SecondName=@SecondName,
Surname=@Surname,
PhoneNumber=@PhoneNumber
WHERE ID=@ID";
connection.Execute(queryUpdate, client);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -0,0 +1,7 @@
namespace ProjectOptika.Scripts.Repositories.Implementations
{
internal class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=localhost;Port=5432;Database=dboptika;Username=postgres;Password=admin";
}
}

View File

@ -0,0 +1,123 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories.Implementations
{
public class EmployeeRepository : IEmployeeRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<EmployeeRepository> _logger;
public EmployeeRepository(IConnectionString connectionString, ILogger<EmployeeRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateEmployee(Employee employee)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(employee));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Employee (PositionEmployee, FirstName, SecondName, Surname)
VALUES (@PositionEmployee, @FirstName, @SecondName, @Surname)";
connection.Execute(queryInsert, employee);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteEmployee(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Employee
WHERE ID=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Employee GetEmployeerByID(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Employee
WHERE ID=@id";
var employee = connection.QueryFirst<Employee>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(employee));
return employee;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Employee> GetEmployees()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Employee";
var employees = connection.Query<Employee>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(employees));
return employees;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public void UpdateEmployee(Employee employee)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(employee));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Employee
SET
PositionEmployee=@PositionEmployee,
FirstName=@FirstName,
SecondName=@SecondName,
Surname=@Surname
WHERE ID=@ID";
connection.Execute(queryUpdate, employee);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -0,0 +1,163 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories.Implementations
{
public class OrderRepository : IOrderRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<OrderRepository> _logger;
public OrderRepository(IConnectionString connectionString, ILogger<OrderRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateOrder(Order order)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}",
JsonConvert.SerializeObject(order));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO Zakaz (EmployeeID, ClientID, OrderDate, TotalCost)
VALUES (@EmployeeID, @ClientID, @OrderDate, @TotalCost);
SELECT MAX(Id) FROM Zakaz";
var orderID = connection.QueryFirst<int>(queryInsert, order, transaction);
var querySubInsert = @"
INSERT INTO AccessoriesOrder (ZakazID, AccessoriesID, Count)
VALUES (@orderID, @AccesoryId, @Count)";
foreach (var elem in order.AccesoriesOrders)
{
connection.Execute(querySubInsert, new
{
orderID,
elem.AccesoryId,
elem.Count
}, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteOrder(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryDelete = @"
DELETE FROM AccessoriesOrder
WHERE ZakazID = @id";
var queryDeleteReceptions = @"
DELETE FROM Zakaz
WHERE ID=@id";
connection.Execute(queryDelete, new { id });
connection.Execute(queryDeleteReceptions, new { id });
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Order> GetOrders(DateTime? startDate = null, DateTime? endDate = null, double? totalCost = null, int? id = null, int? employeeID = null, int? clientID = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
var builder = new QueryBuilder();
if (startDate.HasValue)
{
builder.AddCondition("z.OrderDate >= @startDate");
}
if (endDate.HasValue)
{
builder.AddCondition("z.OrderDate <= @endDate");
}
if (id.HasValue)
{
builder.AddCondition("z.ID = @id");
}
if (employeeID.HasValue)
{
builder.AddCondition("z.EmployeeID = @employeeID");
}
if (clientID.HasValue)
{
builder.AddCondition("z.ClientID = @clientID");
}
if (totalCost.HasValue)
{
builder.AddCondition("z.TotalCost = @totalCost");
}
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @$"
SELECT
z.*,
CONCAT(c.Surname, ' ', c.FirstName) as ClientFullName,
CONCAT(e.Surname, ' ', e.FirstName) as EmployeeFullName,
a.Name as AccessoryName,
ao.AccessoriesID,
ao.Count
FROM Zakaz z
LEFT JOIN Client c ON c.ID = z.ClientID
LEFT JOIN Employee e ON e.ID = z.EmployeeID
INNER JOIN AccessoriesOrder ao ON ao.ZakazID = z.ID
LEFT JOIN Accessories a ON a.ID = ao.AccessoriesID
{builder.Build()}";
var orderHelperDict = new Dictionary<int, List<AccessoriesOrder>>();
var orderes = new Dictionary<int, List<Order>>();
var orders = connection.Query<Order, AccessoriesOrder, Order>(querySelect,
(order, accessoriesOrders) =>
{
if (!orderHelperDict.TryGetValue(order.ID, out var z))
{
z = new List<AccessoriesOrder>();
orderHelperDict.Add(order.ID, z);
}
z.Add(accessoriesOrders);
return order;
}, splitOn: "AccessoryName", param: new { startDate, endDate, totalCost, id, employeeID, clientID });
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(orders));
return orderHelperDict.Select(x =>
{
var r = orders.First(y => y.ID == x.Key);
r.SetAccessriesOrderReplenishment(x.Value);
return r;
}).ToArray();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
}
}

View File

@ -0,0 +1,125 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectOptika.Scripts.Entities;
namespace ProjectOptika.Scripts.Repositories.Implementations
{
public class SpecificationsRepository : ISpecificationsRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<SpecificationsRepository> _logger;
public SpecificationsRepository(IConnectionString connectionString, ILogger<SpecificationsRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateSpecifications(Specifications specification)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(specification));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO Specifications (AccessoriesID, Material, Astigmatism, Dioptericity, OriginCountry, TimeProduction)
VALUES (@AccessoriesID, @Material, @Astigmatism, @Dioptericity, @OriginCountry, @TimeProduction)";
connection.Execute(queryInsert, specification);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteSpecifications(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM Specifications
WHERE ID=@id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<Specifications> GetSpecifications()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = "SELECT * FROM Specifications";
var specifications = connection.Query<Specifications>(querySelect);
_logger.LogDebug("Полученные объекты: {json}",
JsonConvert.SerializeObject(specifications));
return specifications;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при чтении объектов");
throw;
}
}
public Specifications GetSpecificationsByID(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Specifications
WHERE ID=@id";
var specifications = connection.QueryFirst<Specifications>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(specifications));
return specifications;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void UpdateSpecifications(Specifications specification)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(specification));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Specifications
SET
AccessoriesID=@AccessoriesID,
Material=@Material,
Astigmatism=@Astigmatism,
Dioptericity=@Dioptericity,
OriginCountry=@OriginCountry,
TimeProduction=@TimeProduction
WHERE ID=@ID";
connection.Execute(queryUpdate, specification);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}
}

View File

@ -0,0 +1,27 @@
using System.Text;
internal class QueryBuilder
{
private readonly StringBuilder _builder;
public QueryBuilder()
{
_builder = new();
}
public QueryBuilder AddCondition(string condition)
{
if (_builder.Length > 0)
{
_builder.Append(" AND ");
}
_builder.Append(condition);
return this;
}
public string Build()
{
if (_builder.Length == 0)
{
return string.Empty;
}
return $"WHERE {_builder}";
}
}

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/optika_log.txt",
"rollingInterval": "Day"
}
}
]
}
}