This commit is contained in:
bulatova_karina 2024-10-29 09:22:02 +04:00
parent 334111d632
commit 36b3dccf49
68 changed files with 3336 additions and 626 deletions

View File

@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Version>$(VersionPrefix)1.0.1</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Aspose.Words" Version="24.10.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.0" />
<PackageReference Include="Microsoft.Office.Interop.Excel" Version="15.0.4795.1001" />
<PackageReference Include="Microsoft.Office.Interop.Word" Version="15.0.4797.1004" />
<PackageReference Include="System.Xml.XmlDocument" Version="4.3.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,58 @@
namespace BulatovaComponents.Components
{
partial class ComboBoxControl
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.comboBoxCustom = new System.Windows.Forms.ComboBox();
this.SuspendLayout();
//
// comboBoxCustom
//
this.comboBoxCustom.FormattingEnabled = true;
this.comboBoxCustom.Location = new System.Drawing.Point(3, 3);
this.comboBoxCustom.Name = "comboBoxCustom";
this.comboBoxCustom.Size = new System.Drawing.Size(321, 28);
this.comboBoxCustom.TabIndex = 0;
this.comboBoxCustom.SelectedIndexChanged += new System.EventHandler(this.comboBoxCustom_SelectedIndexChanged);
//
// ComboBoxControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.comboBoxCustom);
this.Name = "ComboBoxControl";
this.Size = new System.Drawing.Size(328, 35);
this.ResumeLayout(false);
}
#endregion
private ComboBox comboBoxCustom;
}
}

View File

@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BulatovaComponents.Components
{
public partial class ComboBoxControl : UserControl
{
public ComboBoxControl()
{
InitializeComponent();
}
public string SelectedValue
{
get
{
return comboBoxCustom.SelectedItem != null ? comboBoxCustom.SelectedItem.ToString() : "";
}
set
{
if (comboBoxCustom.Items.Contains(value)) //если есть такой элемент, то помечаем, если нет, ничего не делаем
{
comboBoxCustom.SelectedItem = value;
}
}
}
public event Action<string?> SelectedValueChange;
public void addItems(List<string> items)
{
foreach (string item in items)
{
comboBoxCustom.Items.Add(item);
}
}
public void clear()
{
comboBoxCustom.Items.Clear();
}
private void comboBoxCustom_SelectedIndexChanged(object sender, EventArgs e)
{
SelectedValueChange?.Invoke(comboBoxCustom.SelectedItem.ToString());
}
}
}

View File

@ -0,0 +1,58 @@
namespace BulatovaComponents.Components
{
partial class ListBoxControl
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.listBox = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// listBox
//
this.listBox.FormattingEnabled = true;
this.listBox.ItemHeight = 20;
this.listBox.Location = new System.Drawing.Point(0, 8);
this.listBox.Name = "listBox";
this.listBox.Size = new System.Drawing.Size(599, 224);
this.listBox.TabIndex = 0;
//
// ListBoxControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.listBox);
this.Name = "ListBoxControl";
this.Size = new System.Drawing.Size(599, 250);
this.ResumeLayout(false);
}
#endregion
private ListBox listBox;
}
}

View File

@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BulatovaComponents.Components
{
public partial class ListBoxControl : UserControl
{
public ListBoxControl()
{
InitializeComponent();
}
public string? template;
public char? fromChar;
public char? toChar;
public void setItems<T>(List<T> items)
where T : class
{
if (template == null || !fromChar.HasValue || !toChar.HasValue) throw new ArgumentException("Не хватает данных!");
listBox.Items.Clear();
var type = typeof(T);
var fields = type.GetFields();
foreach (T item in items)
{
string result = template;
foreach (var field in fields)
{
string search = fromChar.Value + field.Name + toChar.Value;
result = result.Replace(search, field.GetValue(item).ToString());
}
listBox.Items.Add(result);
}
}
public T? getSelectedItem<T>()
{
if (template == null || !fromChar.HasValue || !toChar.HasValue || listBox.SelectedIndex == -1) throw new ArgumentException("Не хватает данных!");
var type = typeof(T);
var fields = type.GetFields();
var item = Activator.CreateInstance(type);
string[] wordsTemplate = template.Split(' ');
string[] words = listBox.SelectedItem.ToString().Split(' ');
for (int i = 0; i < wordsTemplate.Length; i++)
{
string word = wordsTemplate[i];
if (word.StartsWith(fromChar.Value))
{
string fieldName = word.Substring(1, word.Length - 2);
var field = fields.FirstOrDefault(x => x.Name == fieldName);
if (field == null) continue;
int indexBefore = i > 0 ? Array.IndexOf(words, wordsTemplate[i - 1]) : -1;
int indexAfter = i < wordsTemplate.Length - 1 ? Array.IndexOf(words, wordsTemplate[i + 1]) : wordsTemplate.Length - 1;
var fieldValue = String.Join(' ', words.Skip(indexBefore + 1).Take(indexAfter - indexBefore - 1).ToArray());
field.SetValue(item, Convert.ChangeType(fieldValue, field.FieldType));
}
}
return item != null ? (T)item : default(T);
}
public int SelectedIndex
{
get
{
return listBox.SelectedIndex;
}
set
{
listBox.SelectedIndex = value;
}
}
public void setParams(string template, char fromChar, char toChar)
{
this.template = template;
this.fromChar = fromChar;
this.toChar = toChar;
}
}
}

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,67 @@
namespace BulatovaComponents.Components
{
partial class MailControl
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.textBoxMail = new System.Windows.Forms.TextBox();
this.toolTipEmail = new System.Windows.Forms.ToolTip(this.components);
this.SuspendLayout();
//
// textBoxMail
//
this.textBoxMail.Location = new System.Drawing.Point(3, 3);
this.textBoxMail.Name = "textBoxMail";
this.textBoxMail.Size = new System.Drawing.Size(257, 27);
this.textBoxMail.TabIndex = 0;
this.textBoxMail.TextChanged += new System.EventHandler(this.textBoxMail_TextChanged);
this.textBoxMail.MouseEnter += new System.EventHandler(this.textBoxMail_MouseEnter);
//
// toolTipEmail
//
this.toolTipEmail.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info;
this.toolTipEmail.ToolTipTitle = "Пример ввода";
//
// MailControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.textBoxMail);
this.Name = "MailControl";
this.Size = new System.Drawing.Size(264, 34);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private TextBox textBoxMail;
private ToolTip toolTipEmail;
}
}

View File

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BulatovaComponents.Components
{
public partial class MailControl : UserControl
{
public MailControl()
{
InitializeComponent();
}
public Regex? validateEmailRegex
{
get;
set;
}
public event Action<string> TextChange;
private string? tooltipText;
public string errorMessage = "";
public string? Email
{
get
{
//не забыл ли пользователь ввести регулярку и соответствует ли она
if (validateEmailRegex == null)
{
errorMessage = "Пустой шаблон!";
return null;
}
else if (!validateEmailRegex.IsMatch(textBoxMail.Text))
{
errorMessage = "Некорректный адрес эл. почты!";
return null;
}
else return textBoxMail.Text;
}
set
{
if (validateEmailRegex == null) errorMessage = "Пустой шаблон!";
else if (!validateEmailRegex.IsMatch(value)) errorMessage = "Некорректный адрес эл. почты!";
else
{
textBoxMail.Text = value;
}
}
}
private void textBoxMail_TextChanged(object sender, EventArgs e)
{
TextChange?.Invoke(textBoxMail.Text);
Email = textBoxMail.Text;
}
public void setTooltipText(string text)
{
tooltipText = text;
}
private void textBoxMail_MouseEnter(object sender, EventArgs e)
{
toolTipEmail.Show(tooltipText ?? "", textBoxMail);
}
}
}

View File

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

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace BulatovaComponents.Exceptions
{
[Serializable]
public class NotMatchPatternException : ApplicationException
{
public NotMatchPatternException() : base() { }
public NotMatchPatternException(string message) : base(message) { }
public NotMatchPatternException(string message, Exception exception) : base(message, exception) { }
protected NotMatchPatternException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace BulatovaComponents.Exceptions
{
[Serializable]
public class NullPatternException : ApplicationException
{
public NullPatternException() : base() { }
public NullPatternException(string message) : base(message) { }
public NullPatternException(string message, Exception exception) : base(message, exception) { }
protected NullPatternException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BulatovaComponents.NonVisualComponents
{
public enum DiagramLegendEnum
{
TopLeft = 0,
TopRight = 1,
BottomRight = 2,
BottomLeft = 3,
}
}

View File

@ -0,0 +1,36 @@
namespace BulatovaComponents.NonVisualComponents
{
partial class WordDiagramComponent
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,142 @@
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BulatovaComponents.NonVisualComponents
{
public partial class WordDiagramComponent : Component
{
public WordDiagramComponent()
{
InitializeComponent();
}
public WordDiagramComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
}
private object missing = System.Reflection.Missing.Value;
private string GetExcelColumnName(int columnNumber)
{
string columnName = "";
while (columnNumber > 0)
{
int modulo = (columnNumber - 1) % 26;
columnName = Convert.ToChar('A' + modulo) + columnName;
columnNumber = (columnNumber - modulo) / 26;
}
return columnName;
}
public void createWithDiagram<T>(string path, string title, string diagramTitle, DiagramLegendEnum diagramLegendAnchor, List<T> data, string seriesNameField, string valueField)
{
var excelApp = new Microsoft.Office.Interop.Excel.Application { SheetsInNewWorkbook = 1 };
Workbook workbook = excelApp.Workbooks.Add(Type.Missing);
Worksheet worksheet = (Worksheet)workbook.Worksheets.get_Item(1);
FieldInfo? seriesName = typeof(T).GetField(seriesNameField);
FieldInfo? value = typeof(T).GetField(valueField);
if (seriesName == null || value == null) throw new ArgumentException("Переданного поля не существует");
int offsetX = 1;
int offsetYMax = -1;
foreach (var item in data)
{
string columnChar = GetExcelColumnName(offsetX);
var cell = worksheet.get_Range(columnChar + "2", columnChar + "2");
cell.Font.Size = 14;
cell.Font.Name = "Times New Roman";
cell.ColumnWidth = 8;
cell.RowHeight = 25;
cell.HorizontalAlignment = Constants.xlCenter;
cell.VerticalAlignment = Constants.xlCenter;
cell.Value2 = seriesName.GetValue(item);
int offsetY = 3;
foreach (var val in (value.GetValue(item) as IEnumerable))
{
cell = worksheet.get_Range(columnChar + offsetY, columnChar + offsetY);
cell.Value2 = val;
offsetY++;
}
if (offsetY > offsetYMax) offsetYMax = offsetY;
offsetX++;
}
var charts = worksheet.ChartObjects() as ChartObjects;
int chartWidth = 300;
int chartHeight = 300;
var chartObject = charts.Add(250, 10, chartWidth, chartHeight);
var chart = chartObject.Chart;
var endColumn = GetExcelColumnName(offsetX - 1);
var range = worksheet.get_Range($"A2", endColumn + (offsetYMax - 1));
chart.SetSourceData(range);
chart.ChartType = XlChartType.xlLine;
switch (diagramLegendAnchor)
{
case DiagramLegendEnum.TopLeft:
chart.Legend.Top = 0;
chart.Legend.Left = 0;
break;
case DiagramLegendEnum.TopRight:
chart.Legend.Top = 0;
chart.Legend.Left = chartWidth - chart.Legend.Width;
break;
case DiagramLegendEnum.BottomLeft:
chart.Legend.Top = chartHeight - chart.Legend.Height;
chart.Legend.Left = 0;
break;
case DiagramLegendEnum.BottomRight:
chart.Legend.Top = chartHeight - chart.Legend.Height;
chart.Legend.Left = chartWidth - chart.Legend.Width;
break;
}
chart.ChartWizard(Source: range, Title: diagramTitle);
chart.Export(path.Substring(0, path.Length - 5) + ".jpg", "JPG", false);
workbook.Close(SaveChanges: false);
excelApp.Quit();
var winword = new Microsoft.Office.Interop.Word.Application();
var document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
document.PageSetup.RightMargin = 50;
document.PageSetup.LeftMargin = 50;
var header = document.Content.Paragraphs.Add(Type.Missing);
header.Range.Text = title;
header.Format.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
header.Range.Font.Name = "Times New Roman";
header.Range.Font.Size = 22;
header.Range.Font.Bold = 2;
header.Format.SpaceAfter = 18;
header.Range.InsertParagraphAfter();
document.Shapes.AddPicture(path.Substring(0, path.Length - 5) + ".jpg", Top: 200);
document.SaveAs(path, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
document.Close(ref missing, ref missing, ref missing);
document = null;
winword.Quit(ref missing, ref missing, ref missing);
}
}
}

View File

@ -0,0 +1,36 @@
namespace BulatovaComponents.NonVisualComponents
{
partial class WordLongTextComponent
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,65 @@
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BulatovaComponents.NonVisualComponents
{
public partial class WordLongTextComponent : Component
{
public WordLongTextComponent()
{
InitializeComponent();
}
public WordLongTextComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
}
private object missing = System.Reflection.Missing.Value;
public void createWithLongText(WordLongTextInfo wordInfo)
{
var winword = new Microsoft.Office.Interop.Word.Application();
var document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
document.PageSetup.RightMargin = 50;
document.PageSetup.LeftMargin = 50;
var header = document.Content.Paragraphs.Add(Type.Missing);
header.Range.Text = wordInfo.header;
header.Format.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
header.Range.Font.Name = "Times New Roman";
header.Range.Font.Size = 22;
header.Range.Font.Bold = 2;
header.Format.SpaceAfter = 18;
header.Range.InsertParagraphAfter();
foreach (string text in wordInfo.paragraphs)
{
var paragraph = document.Content.Paragraphs.Add(Type.Missing);
paragraph.Range.Text = text;
paragraph.Format.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
paragraph.Range.Font.Name = "Times New Roman";
paragraph.Range.Font.Size = 14;
paragraph.Range.Font.Bold = 0;
paragraph.Format.SpaceAfter = 18;
paragraph.Range.InsertParagraphAfter();
}
document.SaveAs(wordInfo.path, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
document.Close(ref missing, ref missing, ref missing);
document = null;
winword.Quit(ref missing, ref missing, ref missing);
}
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BulatovaComponents.NonVisualComponents
{
public class WordLongTextInfo
{
public string path;
public string header;
public string[] paragraphs;
public WordLongTextInfo(string path, string header, string[] paragraphs)
{
this.path = path;
this.header = header;
this.paragraphs = paragraphs;
}
}
}

View File

@ -0,0 +1,36 @@
namespace BulatovaComponents.NonVisualComponents
{
partial class WordTableComponent
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,170 @@
using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BulatovaComponents.NonVisualComponents
{
public partial class WordTableComponent : Component
{
public WordTableComponent()
{
InitializeComponent();
}
public WordTableComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
}
private object missing = System.Reflection.Missing.Value;
public void createWithTable<T>(string path, string title, List<(int, int)> merges, List<int> widths, List<(string, string)> headers, List<T> items)
{
if (merges.Count == 0 || widths.Count == 0 || headers.Count == 0 || items.Count == 0) throw new ArgumentException("Недостаточно данных");
int[] cellsArray = new int[widths.Count];
foreach (var merge in merges)
{
if (merge.Item1 >= merge.Item2) throw new ArgumentException("Неправильно заполнены объединения строк");
for (int i = merge.Item1; i < merge.Item2 + 1; i++)
{
cellsArray[i]++;
}
}
foreach (int cell in cellsArray)
{
if (cell > 1) throw new ArgumentException("Объединения заходят друг на друга");
}
var winword = new Microsoft.Office.Interop.Word.Application();
var document = winword.Documents.Add(ref missing, ref missing, ref missing, ref missing);
document.PageSetup.RightMargin = 50;
document.PageSetup.LeftMargin = 50;
document.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
var header = document.Content.Paragraphs.Add(Type.Missing);
header.Range.Text = title;
header.Format.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
header.Range.Font.Name = "Times New Roman";
header.Range.Font.Size = 22;
header.Range.Font.Bold = 2;
header.Format.SpaceAfter = 18;
header.Range.InsertParagraphAfter();
var table = document.Tables.Add(document.Bookmarks.get_Item("\\endofdoc").Range,
items.Count + 2, widths.Count, Type.Missing, Type.Missing);
table.Borders.Enable = 1;
for (int i = 0; i < widths.Count; i++)
{
table.Cell(1, i + 1).Width = widths[i];
table.Cell(1, i + 1).Height = 20;
table.Cell(2, i + 1).Width = widths[i];
table.Cell(2, i + 1).Height = 20;
}
//checks
List<Cell> ranges = new List<Cell>();
foreach (var merge in merges)
{
ranges.Add(table.Rows[1].Cells[merge.Item1 + 1]);
}
//number of merged cell
int rangeIndex = 0;
//number of cell
int headerIndex = 0;
List<PropertyInfo> cellProperties = new List<PropertyInfo>();
var type = typeof(T);
for (int i = 0; i < widths.Count; i++)
{
if (cellsArray[i] == 1)
{
//work with merge
if (!string.IsNullOrEmpty(headers[headerIndex].Item1)) throw new ArgumentException("Заголовки и объединения строк не совпадают");
var headerCell = ranges[rangeIndex];
headerCell.Range.Text = headers[headerIndex].Item2;
headerCell.Range.Font.Size = 11;
headerIndex++;
//work with cells in merge
for (; i <= merges[rangeIndex].Item2; i++)
{
//work with cell
if (string.IsNullOrEmpty(headers[headerIndex].Item1)) throw new ArgumentException("Заголовки и объединения строк не совпадают");
var property = type.GetProperty(headers[headerIndex].Item1);
if (property == null) throw new ArgumentException("В заголовках указано поле, которого нет в переданном классе");
//format header
var cell = table.Cell(2, i + 1);
cell.Range.Text = headers[headerIndex].Item2;
cell.Width = widths[i];
cell.Range.Font.Size = 11;
cellProperties.Add(property);
headerIndex++;
}
i--;
rangeIndex++;
}
else
{
//work with cell
if (string.IsNullOrEmpty(headers[headerIndex].Item1)) throw new ArgumentException("Заголовки и объединения строк не совпадают");
var property = type.GetProperty(headers[headerIndex].Item1);
if (property == null) throw new ArgumentException("В заголовках указано поле, которого нет в переданном классе");
//format header
var cell = table.Cell(1, i + 1);
cell.Merge(table.Cell(2, i + 1));
cell.Range.Text = headers[headerIndex].Item2;
cell.Width = widths[i];
cell.Range.Font.Size = 11;
cellProperties.Add(property);
headerIndex++;
}
}
int xOffset = 0;
foreach (var merge in merges)
{
table.Cell(1, merge.Item1 + 1 - xOffset).Merge(table.Cell(1, merge.Item2 + 1 - xOffset));
xOffset += merge.Item2 - merge.Item1;
}
int rowNum = 3;
foreach (T item in items)
{
int columnNum = 1;
foreach (var cellProperty in cellProperties)
{
var cell = table.Cell(rowNum, columnNum);
cell.Range.Text = cellProperty.GetValue(item)?.ToString();
cell.Width = widths[columnNum - 1];
cell.Range.Bold = 0;
cell.Range.Font.Size = 11;
cell.Height = 20;
columnNum++;
}
rowNum++;
}
document.SaveAs(path, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
document.Close(ref missing, ref missing, ref missing);
document = null;
winword.Quit(ref missing, ref missing, ref missing);
}
}
}

View File

@ -5,7 +5,17 @@ VisualStudioVersion = 17.3.32825.248
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Components", "Components\Components.csproj", "{218522CC-CD60-403C-9B12-C683EEA06E32}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinForms", "WinForms\WinForms.csproj", "{AFFC45E9-4318-4446-89E4-FEB441CD92F0}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinForms", "WinForms\WinForms.csproj", "{AFFC45E9-4318-4446-89E4-FEB441CD92F0}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClientBusinessLogic", "ClientBusinessLogic\ClientBusinessLogic.csproj", "{56A00FAB-A39A-4110-BBC5-F07CB0465A13}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClientsContracts", "ClientsContracts\ClientsContracts.csproj", "{74DDFCEC-CE98-4A60-8EF6-ADEA8BB202CA}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClientsDatabaseImplement", "ClientsDatabaseImplement\ClientsDatabaseImplement.csproj", "{725F3378-1474-4195-9F76-B9C98690CC76}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BulatovaComponents", "BulatovaComponents\BulatovaComponents.csproj", "{A8DDA2DE-1B0C-4870-BA0B-BDE84B705B3E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ClientsDataModels", "ClientsDataModels\ClientsDataModels.csproj", "{83105892-317C-4442-B064-E489D2CFE39D}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -21,6 +31,26 @@ Global
{AFFC45E9-4318-4446-89E4-FEB441CD92F0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AFFC45E9-4318-4446-89E4-FEB441CD92F0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AFFC45E9-4318-4446-89E4-FEB441CD92F0}.Release|Any CPU.Build.0 = Release|Any CPU
{56A00FAB-A39A-4110-BBC5-F07CB0465A13}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{56A00FAB-A39A-4110-BBC5-F07CB0465A13}.Debug|Any CPU.Build.0 = Debug|Any CPU
{56A00FAB-A39A-4110-BBC5-F07CB0465A13}.Release|Any CPU.ActiveCfg = Release|Any CPU
{56A00FAB-A39A-4110-BBC5-F07CB0465A13}.Release|Any CPU.Build.0 = Release|Any CPU
{74DDFCEC-CE98-4A60-8EF6-ADEA8BB202CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{74DDFCEC-CE98-4A60-8EF6-ADEA8BB202CA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{74DDFCEC-CE98-4A60-8EF6-ADEA8BB202CA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{74DDFCEC-CE98-4A60-8EF6-ADEA8BB202CA}.Release|Any CPU.Build.0 = Release|Any CPU
{725F3378-1474-4195-9F76-B9C98690CC76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{725F3378-1474-4195-9F76-B9C98690CC76}.Debug|Any CPU.Build.0 = Debug|Any CPU
{725F3378-1474-4195-9F76-B9C98690CC76}.Release|Any CPU.ActiveCfg = Release|Any CPU
{725F3378-1474-4195-9F76-B9C98690CC76}.Release|Any CPU.Build.0 = Release|Any CPU
{A8DDA2DE-1B0C-4870-BA0B-BDE84B705B3E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A8DDA2DE-1B0C-4870-BA0B-BDE84B705B3E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A8DDA2DE-1B0C-4870-BA0B-BDE84B705B3E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A8DDA2DE-1B0C-4870-BA0B-BDE84B705B3E}.Release|Any CPU.Build.0 = Release|Any CPU
{83105892-317C-4442-B064-E489D2CFE39D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{83105892-317C-4442-B064-E489D2CFE39D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{83105892-317C-4442-B064-E489D2CFE39D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{83105892-317C-4442-B064-E489D2CFE39D}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -0,0 +1,88 @@
using ClientsContracts.BindingModels;
using ClientsContracts.BusinessLogicContracts;
using ClientsContracts.SearchModels;
using ClientsContracts.StorageContracts;
using ClientsContracts.ViewModels;
namespace ClientBusinessLogic.BusinessLogics
{
public class ClientLogic : IClientLogic
{
private readonly IClientStorage _clientStorage;
public ClientLogic(IClientStorage clientStorage)
{
_clientStorage = clientStorage;
}
public bool Create(ClientBindingModel model)
{
CheckModel(model);
if (_clientStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Delete(ClientBindingModel model)
{
CheckModel(model, false);
if (_clientStorage.Delete(model) == null)
{
return false;
}
return true;
}
public ClientViewModel? ReadElement(ClientSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
var element = _clientStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public List<ClientViewModel>? ReadList(ClientSearchModel? model)
{
var list = _clientStorage.GetFullList();
if (list == null)
{
return null;
}
return list;
}
public bool Update(ClientBindingModel model)
{
CheckModel(model);
if (_clientStorage.Update(model) == null)
{
return false;
}
return true;
}
private void CheckModel(ClientBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.Name))
{
throw new ArgumentNullException("Client's name is missing!", nameof(model.Name));
}
}
}
}

View File

@ -0,0 +1,88 @@
using ClientsContracts.BindingModels;
using ClientsContracts.BusinessLogicContracts;
using ClientsContracts.SearchModels;
using ClientsContracts.StorageContracts;
using ClientsContracts.ViewModels;
namespace ClientBusinessLogic.BusinessLogics
{
public class StatusLogic : IStatusLogic
{
private readonly IStatusStorage _statusStorage;
public StatusLogic(IStatusStorage statusStorage)
{
_statusStorage = statusStorage;
}
public bool Create(StatusBindingModel model)
{
CheckModel(model);
if (_statusStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Delete(StatusBindingModel model)
{
CheckModel(model, false);
if (_statusStorage.Delete(model) == null)
{
return false;
}
return true;
}
public StatusViewModel? ReadElement(StatusSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
var element = _statusStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public List<StatusViewModel>? ReadList()
{
var list = _statusStorage.GetFullList();
if (list == null)
{
return null;
}
return list;
}
public bool Update(StatusBindingModel model)
{
CheckModel(model);
if (_statusStorage.Update(model) == null)
{
return false;
}
return true;
}
private void CheckModel(StatusBindingModel model, bool withParams = true)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (!withParams)
{
return;
}
if (string.IsNullOrEmpty(model.StatusName))
{
throw new ArgumentNullException("Status's name is missing!", nameof(model.StatusName));
}
}
}
}

View File

@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\ClientsContracts\ClientsContracts.csproj" />
<ProjectReference Include="..\ClientsDataModels\ClientsDataModels.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClientsContracts.BindingModels
{
public class ClientBindingModel
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string? Reviews { get; set; } = string.Empty;
public float? Amount { get; set; } = null;
public int StatusId { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClientsContracts.BindingModels
{
public class StatusBindingModel
{
public int Id { get; set; }
public string StatusName { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,15 @@
using ClientsContracts.BindingModels;
using ClientsContracts.SearchModels;
using ClientsContracts.ViewModels;
namespace ClientsContracts.BusinessLogicContracts
{
public interface IClientLogic
{
List<ClientViewModel>? ReadList(ClientSearchModel? model);
ClientViewModel? ReadElement(ClientSearchModel model);
bool Create(ClientBindingModel model);
bool Update(ClientBindingModel model);
bool Delete(ClientBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using ClientsContracts.BindingModels;
using ClientsContracts.SearchModels;
using ClientsContracts.ViewModels;
namespace ClientsContracts.BusinessLogicContracts
{
public interface IStatusLogic
{
List<StatusViewModel> ReadList();
StatusViewModel? ReadElement(StatusSearchModel model);
bool Create(StatusBindingModel model);
bool Update(StatusBindingModel model);
bool Delete(StatusBindingModel model);
}
}

View File

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

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClientsContracts.SearchModels
{
public class ClientSearchModel
{
public int? Id { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClientsContracts.SearchModels
{
public class StatusSearchModel
{
public int? Id { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using ClientsContracts.BindingModels;
using ClientsContracts.SearchModels;
using ClientsContracts.ViewModels;
namespace ClientsContracts.StorageContracts
{
public interface IClientStorage
{
List<ClientViewModel> GetFullList();
ClientViewModel? GetElement(ClientSearchModel model);
ClientViewModel? Insert(ClientBindingModel model);
ClientViewModel? Update(ClientBindingModel model);
ClientViewModel? Delete(ClientBindingModel model);
}
}

View File

@ -0,0 +1,15 @@
using ClientsContracts.BindingModels;
using ClientsContracts.SearchModels;
using ClientsContracts.ViewModels;
namespace ClientsContracts.StorageContracts
{
public interface IStatusStorage
{
List<StatusViewModel> GetFullList();
StatusViewModel? GetElement(StatusSearchModel model);
StatusViewModel? Insert(StatusBindingModel model);
StatusViewModel? Update(StatusBindingModel model);
StatusViewModel? Delete(StatusBindingModel model);
}
}

View File

@ -0,0 +1,21 @@
using System.ComponentModel;
using ClientsDataModels.Models;
namespace ClientsContracts.ViewModels
{
public class ClientViewModel : IClientModel
{
public int Id { get; set; } = 0;
[DisplayName("ФИО")]
public string Name { get; set; } = string.Empty;
[DisplayName("Сумма покупок")]
public float? Amount { get; set; } = null;
[DisplayName("Отзывы")]
public string? Reviews { get; set; } = string.Empty;
public int StatusId { get; set; } = 0;
[DisplayName("Статус")]
public string StatusName { get; set; } = string.Empty;
public float ViewAmount { get; set; } = 0;
public string DocAmount { get; set; } = string.Empty;
}
}

View File

@ -0,0 +1,18 @@
using ClientsContracts.BusinessLogicContracts;
using ClientsDataModels.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClientsContracts.ViewModels
{
public class StatusViewModel : IStatusModel
{
public int Id { get; set; }
[DisplayName("Название")]
public string StatusName { get; set; } = string.Empty;
}
}

View File

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

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ClientsDataModels
{
public interface IId
{
int Id { get; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ClientsDataModels.Models
{
public interface IClientModel : IId
{
string Name { get; }
float? Amount { get; }
string? Reviews { get; }
int StatusId { get; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ClientsDataModels.Models
{
public interface IStatusModel : IId
{
string StatusName { get; }
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore;
using ClientsDatabaseImplement.Models;
using System.Collections.Generic;
using System.Data;
namespace ClientsDatabaseImplement
{
public class ClientsDatabase : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured == false)
{
optionsBuilder.UseSqlServer(@"Data Source=DESKTOP-1DE5E8N\SQLEXPRESS;Initial Catalog=ClientsDatabase2;
Integrated Security=True;MultipleActiveResultSets=True;;TrustServerCertificate=True");
}
base.OnConfiguring(optionsBuilder);
}
public virtual DbSet<Status> Statuses { set; get; }
public virtual DbSet<Client> Clients { set; get; }
}
}

View File

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

View File

@ -0,0 +1,68 @@
using ClientsContracts.StorageContracts;
using ClientsContracts.BindingModels;
using ClientsContracts.ViewModels;
using ClientsDatabaseImplement.Models;
using ClientsContracts.SearchModels;
using Microsoft.EntityFrameworkCore;
namespace ClientsDatabaseImplement.Implements
{
public class ClientStorage : IClientStorage
{
public List<ClientViewModel> GetFullList()
{
using var context = new ClientsDatabase();
return context.Clients.Include(x => x.Status)
.Select(x => x.GetViewModel)
.ToList();
}
public ClientViewModel? GetElement(ClientSearchModel model)
{
if (!model.Id.HasValue)
{
return new();
}
using var context = new ClientsDatabase();
return context.Clients.Include(x => x.Status)
.FirstOrDefault(x => model.Id.HasValue && x.Id == model.Id)
?.GetViewModel;
}
public ClientViewModel? Insert(ClientBindingModel model)
{
using var context = new ClientsDatabase();
var newClient = Client.Create(model, context);
if (newClient == null)
{
return null;
}
context.Clients.Add(newClient);
context.SaveChanges();
return newClient.GetViewModel;
}
public ClientViewModel? Update(ClientBindingModel model)
{
using var context = new ClientsDatabase();
var client = context.Clients.FirstOrDefault(x => x.Id == model.Id);
if (client == null)
{
return null;
}
client.Update(model);
context.SaveChanges();
return client.GetViewModel;
}
public ClientViewModel? Delete(ClientBindingModel model)
{
using var context = new ClientsDatabase();
var element = context.Clients.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Clients.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,68 @@
using ClientsContracts.StorageContracts;
using ClientsContracts.BindingModels;
using ClientsContracts.ViewModels;
using ClientsDatabaseImplement.Models;
using System.Data;
using ClientsContracts.SearchModels;
namespace ClientsDatabaseImplement.Implements
{
public class StatusStorage : IStatusStorage
{
public List<StatusViewModel> GetFullList()
{
using var context = new ClientsDatabase();
return context.Statuses
.Select(x => x.GetViewModel)
.ToList();
}
public StatusViewModel? GetElement(StatusSearchModel model)
{
using var context = new ClientsDatabase();
return context.Statuses
.FirstOrDefault(x => (model.Id.HasValue && x.Id == model.Id))
?.GetViewModel;
}
public StatusViewModel? Insert(StatusBindingModel model)
{
var newStatus = Status.Create(model);
if (newStatus == null)
{
return null;
}
using var context = new ClientsDatabase();
context.Statuses.Add(newStatus);
context.SaveChanges();
return newStatus.GetViewModel;
}
public StatusViewModel? Update(StatusBindingModel model)
{
using var context = new ClientsDatabase();
var status = context.Statuses.FirstOrDefault(x => x.Id == model.Id);
if (status == null)
{
return null;
}
status.Update(model);
context.SaveChanges();
return status.GetViewModel;
}
public StatusViewModel? Delete(StatusBindingModel model)
{
using var context = new ClientsDatabase();
var element = context.Statuses.FirstOrDefault(rec => rec.Id == model.Id);
if (element != null)
{
context.Statuses.Remove(element);
context.SaveChanges();
return element.GetViewModel;
}
return null;
}
}
}

View File

@ -0,0 +1,86 @@
// <auto-generated />
using System;
using ClientsDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace ClientsDatabaseImplement.Migrations
{
[DbContext(typeof(ClientsDatabase))]
[Migration("20241028162549_InitialCreate")]
partial class InitialCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.20")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ClientsDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<float?>("Amount")
.HasColumnType("real");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Reviews")
.HasColumnType("nvarchar(max)");
b.Property<int>("StatusId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("StatusId");
b.ToTable("Clients");
});
modelBuilder.Entity("ClientsDatabaseImplement.Models.Status", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("StatusName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Statuses");
});
modelBuilder.Entity("ClientsDatabaseImplement.Models.Client", b =>
{
b.HasOne("ClientsDatabaseImplement.Models.Status", "Status")
.WithMany()
.HasForeignKey("StatusId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Status");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,64 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace ClientsDatabaseImplement.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Statuses",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
StatusName = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Statuses", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Clients",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
Reviews = table.Column<string>(type: "nvarchar(max)", nullable: true),
Amount = table.Column<float>(type: "real", nullable: true),
StatusId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Clients", x => x.Id);
table.ForeignKey(
name: "FK_Clients_Statuses_StatusId",
column: x => x.StatusId,
principalTable: "Statuses",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Clients_StatusId",
table: "Clients",
column: "StatusId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Clients");
migrationBuilder.DropTable(
name: "Statuses");
}
}
}

View File

@ -0,0 +1,83 @@
// <auto-generated />
using System;
using ClientsDatabaseImplement;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace ClientsDatabaseImplement.Migrations
{
[DbContext(typeof(ClientsDatabase))]
partial class ClientsDatabaseModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.20")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("ClientsDatabaseImplement.Models.Client", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<float?>("Amount")
.HasColumnType("real");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Reviews")
.HasColumnType("nvarchar(max)");
b.Property<int>("StatusId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("StatusId");
b.ToTable("Clients");
});
modelBuilder.Entity("ClientsDatabaseImplement.Models.Status", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("StatusName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Statuses");
});
modelBuilder.Entity("ClientsDatabaseImplement.Models.Client", b =>
{
b.HasOne("ClientsDatabaseImplement.Models.Status", "Status")
.WithMany()
.HasForeignKey("StatusId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Status");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,59 @@
using ClientsContracts.BindingModels;
using ClientsContracts.ViewModels;
using ClientsDataModels.Models;
using System.ComponentModel.DataAnnotations;
using System.Data;
namespace ClientsDatabaseImplement.Models
{
public class Client : IClientModel
{
public int Id { get; private set; }
[Required]
public string Name { get; set; }
public string? Reviews { get; set; } = null;
public float? Amount { get; set; } = null;
[Required]
public int StatusId { get; set; }
public virtual Status Status { get; set; } = new();
public static Client? Create(ClientBindingModel? model, ClientsDatabase context)
{
if (model == null)
{
return null;
}
return new Client()
{
Id = model.Id,
Name = model.Name,
Reviews = model.Reviews,
Amount = model.Amount,
StatusId = model.StatusId,
Status = context.Statuses.First(x => x.Id == model.StatusId),
};
}
public void Update(ClientBindingModel? model)
{
if (model == null)
{
return;
}
Name = model.Name;
Reviews = model.Reviews;
Amount = model.Amount;
}
public ClientViewModel GetViewModel => new()
{
Id = Id,
Name = Name,
Reviews = Reviews,
Amount = Amount,
StatusId = StatusId,
StatusName = Status.StatusName,
};
}
}

View File

@ -0,0 +1,49 @@
using ClientsContracts.BindingModels;
using ClientsContracts.ViewModels;
using ClientsDataModels.Models;
using System.ComponentModel.DataAnnotations;
namespace ClientsDatabaseImplement.Models
{
public class Status : IStatusModel
{
public int Id { get; private set; }
[Required]
public string StatusName { get; private set; } = string.Empty;
public static Status? Create(StatusBindingModel model)
{
if (model == null)
{
return null;
}
return new Status()
{
Id = model.Id,
StatusName = model.StatusName,
};
}
public static Status Create(StatusViewModel model)
{
return new Status
{
Id = model.Id,
StatusName = model.StatusName,
};
}
public void Update(StatusBindingModel model)
{
if (model == null)
{
return;
}
StatusName = model.StatusName;
}
public StatusViewModel GetViewModel => new()
{
Id = Id,
StatusName = StatusName,
};
}
}

View File

@ -5,6 +5,7 @@
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>

View File

@ -24,6 +24,7 @@ namespace Components.NonVisualComponents
InitializeComponent();
}
public void CreateTable<T>(BigTable<T> bigTable)
{
if (bigTable.Data == null)
@ -31,11 +32,11 @@ namespace Components.NonVisualComponents
throw new ArgumentException("Не заданы все данные");
}
foreach (var columnDefenition in bigTable.ColumnDefenitions)
foreach (var columnDefinition in bigTable.ColumnDefinitions)
{
if (string.IsNullOrEmpty(columnDefenition.PropertyName))
if (string.IsNullOrEmpty(columnDefinition.PropertyName))
{
throw new ArgumentException($"Не задано свойство столбца: {columnDefenition.Header}");
throw new ArgumentException($"Не задано свойство столбца: {columnDefinition.Header}");
}
}
@ -52,13 +53,13 @@ namespace Components.NonVisualComponents
Table table = builder.StartTable();
foreach (var columnDefenition in bigTable.ColumnDefenitions)
foreach (var columnDefinition in bigTable.ColumnDefinitions)
{
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnDefenition.Weight);
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnDefinition.Weight);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write(columnDefenition.Header);
builder.Write(columnDefinition.Header);
}
foreach (var mergedColumn in bigTable.MergedColumns)
@ -82,25 +83,25 @@ namespace Components.NonVisualComponents
}
builder.EndRow();
foreach (var columnDefenition in bigTable.ColumnDefenitions)
foreach (var columnDefinition2 in bigTable.ColumnDefinitions2)
{
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnDefenition.Weight);
builder.Write(columnDefenition.Header);
builder.CellFormat.PreferredWidth = PreferredWidth.FromPoints(columnDefinition2.Weight);
builder.Write(columnDefinition2.Header);
}
builder.EndRow();
int columnIndex;
foreach (var columnDefinition in bigTable.ColumnDefenitions)
foreach (var columnDefinition in bigTable.ColumnDefinitions)
{
string currentHeader = columnDefinition.Header;
string currentPropertyName = columnDefinition.PropertyName;
columnIndex = 0;
foreach (var columnDefenition in bigTable.ColumnDefenitions)
foreach (var columnDefinition2 in bigTable.ColumnDefinitions2)
{
string currentHeader1 = columnDefenition.Header;
string currentPropertyName1 = columnDefinition2.PropertyName;
if (currentHeader == currentHeader1)
if (currentPropertyName == currentPropertyName1)
{
table.Rows[0].Cells[columnIndex].CellFormat.VerticalMerge = CellMerge.First;
table.Rows[1].Cells[columnIndex].CellFormat.VerticalMerge = CellMerge.Previous;
@ -112,11 +113,11 @@ namespace Components.NonVisualComponents
foreach (var item in bigTable.Data)
{
foreach (var columnDefenition in bigTable.ColumnDefenitions)
foreach (var columnDefinition2 in bigTable.ColumnDefinitions2)
{
builder.InsertCell();
var propertyValue = item.GetType()
.GetProperty(columnDefenition.PropertyName)?
.GetProperty(columnDefinition2.PropertyName)?
.GetValue(item)?.ToString();
builder.Write(propertyValue ?? "");

View File

@ -12,20 +12,20 @@ namespace Components.SupportClasses
public string DocumentTitle = string.Empty;
public List<string> Header;
public List<ColumnDefenitions> ColumnDefenitions;
public List<ColumnDefinition> ColumnDefinitions;
public List<ColumnDefinition> ColumnDefinitions2;
public List<T> Data;
public List<int[]> MergedColumns;
public BigTable(string filePath, string documentTitle, List<string> header, List<ColumnDefenitions> columnDefenitions, List<T> data, List<int[]> mergedColumns)
public BigTable(string filePath, string documentTitle, List<ColumnDefinition> columnDefinitions, List<ColumnDefinition> columnDefinitions2, List<T> data, List<int[]> mergedColumns)
{
FilePath = filePath;
DocumentTitle = documentTitle;
Header = header;
ColumnDefinitions = columnDefinitions;
Data = data;
MergedColumns = mergedColumns;
ColumnDefenitions = columnDefenitions;
ColumnDefinitions2 = columnDefinitions2;
}
}
}

View File

@ -6,7 +6,7 @@ using System.Threading.Tasks;
namespace Components.SupportClasses
{
public class ColumnDefenitions
public class ColumnDefinition
{
public string Header;
public string PropertyName;

155
COP/WinForms/FormClient.Designer.cs generated Normal file
View File

@ -0,0 +1,155 @@
using ControlsLibraryNet60.Input;
namespace WinForms
{
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()
{
this.controlInputAmount = new ControlsLibraryNet60.Input.ControlInputNullableDouble();
this.comboBoxControlStatus = new BulatovaComponents.Components.ComboBoxControl();
this.textBoxName = new System.Windows.Forms.TextBox();
this.textBoxReviews = new System.Windows.Forms.TextBox();
this.labelName = new System.Windows.Forms.Label();
this.labelReviews = new System.Windows.Forms.Label();
this.labelAmount = new System.Windows.Forms.Label();
this.labelClient = new System.Windows.Forms.Label();
this.buttonAdd = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// controlInputAmount
//
this.controlInputAmount.Location = new System.Drawing.Point(14, 219);
this.controlInputAmount.Margin = new System.Windows.Forms.Padding(5, 8, 5, 8);
this.controlInputAmount.Name = "controlInputAmount";
this.controlInputAmount.Size = new System.Drawing.Size(331, 36);
this.controlInputAmount.TabIndex = 0;
this.controlInputAmount.Value = null;
//
// comboBoxControlStatus
//
this.comboBoxControlStatus.Location = new System.Drawing.Point(22, 34);
this.comboBoxControlStatus.Name = "comboBoxControlStatus";
this.comboBoxControlStatus.SelectedValue = "";
this.comboBoxControlStatus.Size = new System.Drawing.Size(333, 44);
this.comboBoxControlStatus.TabIndex = 1;
//
// textBoxName
//
this.textBoxName.Location = new System.Drawing.Point(22, 93);
this.textBoxName.Name = "textBoxName";
this.textBoxName.Size = new System.Drawing.Size(323, 27);
this.textBoxName.TabIndex = 2;
//
// textBoxReviews
//
this.textBoxReviews.Location = new System.Drawing.Point(22, 151);
this.textBoxReviews.Name = "textBoxReviews";
this.textBoxReviews.Size = new System.Drawing.Size(323, 27);
this.textBoxReviews.TabIndex = 3;
//
// labelName
//
this.labelName.AutoSize = true;
this.labelName.Location = new System.Drawing.Point(22, 70);
this.labelName.Name = "labelName";
this.labelName.Size = new System.Drawing.Size(52, 20);
this.labelName.TabIndex = 4;
this.labelName.Text = "ФИО";
//
// labelReviews
//
this.labelReviews.AutoSize = true;
this.labelReviews.Location = new System.Drawing.Point(22, 128);
this.labelReviews.Name = "labelReviews";
this.labelReviews.Size = new System.Drawing.Size(131, 20);
this.labelReviews.TabIndex = 5;
this.labelReviews.Text = "Отзывы";
//
// labelAmount
//
this.labelAmount.AutoSize = true;
this.labelAmount.Location = new System.Drawing.Point(26, 191);
this.labelAmount.Name = "labelAmount";
this.labelAmount.Size = new System.Drawing.Size(64, 20);
this.labelAmount.TabIndex = 6;
this.labelAmount.Text = "Сумма покупок";
//
// labelClient
//
this.labelClient.AutoSize = true;
this.labelClient.Location = new System.Drawing.Point(25, 8);
this.labelClient.Name = "labelClient";
this.labelClient.Size = new System.Drawing.Size(63, 20);
this.labelClient.TabIndex = 7;
this.labelClient.Text = "Клиент";
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(36, 262);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(94, 29);
this.buttonAdd.TabIndex = 8;
this.buttonAdd.Text = "Добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonSave_Click);
//
// FormClient
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(404, 307);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.labelClient);
this.Controls.Add(this.labelAmount);
this.Controls.Add(this.labelReviews);
this.Controls.Add(this.labelName);
this.Controls.Add(this.textBoxReviews);
this.Controls.Add(this.textBoxName);
this.Controls.Add(this.comboBoxControlStatus);
this.Controls.Add(this.controlInputAmount);
this.Name = "FormClient";
this.Text = "FormClient";
this.Load += new System.EventHandler(this.FormClient_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private ControlsLibraryNet60.Input.ControlInputNullableDouble controlInputAmount;
private BulatovaComponents.Components.ComboBoxControl comboBoxControlStatus;
private TextBox textBoxName;
private TextBox textBoxReviews;
private Label labelName;
private Label labelReviews;
private Label labelAmount;
private Label labelClient;
private Button buttonAdd;
}
}

102
COP/WinForms/FormClient.cs Normal file
View File

@ -0,0 +1,102 @@
using ClientsContracts.BindingModels;
using ClientsContracts.BusinessLogicContracts;
using ClientsContracts.SearchModels;
using ClientsContracts.ViewModels;
using ControlsLibraryNet60.Input;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinForms
{
public partial class FormClient : Form
{
private int? _id;
private readonly IClientLogic _logic;
private readonly IStatusLogic _roleLogic;
private List<StatusViewModel> _roles;
public int Id { set { _id = value; } }
public FormClient(IClientLogic logic, IStatusLogic roleLogic)
{
InitializeComponent();
_logic = logic;
_roleLogic = roleLogic;
_roles = new List<StatusViewModel>();
}
private void FormClient_Load(object sender, EventArgs e)
{
_roles = _roleLogic.ReadList();
comboBoxControlStatus.addItems(_roles.Select(x => x.StatusName).ToList());
if (_id.HasValue)
{
try
{
var view = _logic.ReadElement(new ClientSearchModel { Id = _id.Value });
if (view != null)
{
textBoxName.Text = view.Name;
textBoxReviews.Text = view.Reviews;
controlInputAmount.Value = view.Amount;
comboBoxControlStatus.SelectedValue = view.StatusName;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void buttonCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void buttonSave_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxName.Text))
{
MessageBox.Show("Заполните ФИО", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (string.IsNullOrEmpty(comboBoxControlStatus.SelectedValue))
{
MessageBox.Show("Выберете статус", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
var model = new ClientBindingModel
{
Id = _id ?? 0,
Name = textBoxName.Text,
Reviews = textBoxReviews.Text,
Amount = controlInputAmount.Value.HasValue ? (float)controlInputAmount.Value.GetValueOrDefault() : null,
StatusId = _roles.First(x => x.StatusName == comboBoxControlStatus.SelectedValue).Id,
};
var operationResult = _id.HasValue ? _logic.Update(model) : _logic.Create(model);
if (!operationResult)
{
throw new Exception("Ошибка при сохранении. Дополнительная информация в логах.");
}
MessageBox.Show("Сохранение прошло успешно", "Сообщение", MessageBoxButtons.OK, MessageBoxIcon.Information);
DialogResult = DialogResult.OK;
Close();
}
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

@ -1,228 +0,0 @@
namespace WinForms
{
partial class FormForComponents
{
/// <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.dropDownList = new Components.Components.UserDropDownList();
this.buttonAdd = new System.Windows.Forms.Button();
this.buttonInfo = new System.Windows.Forms.Button();
this.labelInfo = new System.Windows.Forms.Label();
this.buttonClear = new System.Windows.Forms.Button();
this.emailTextBox = new Components.Components.UserEmailTextBox();
this.labelShow = new System.Windows.Forms.Label();
this.buttonShow = new System.Windows.Forms.Button();
this.buttonSetExample = new System.Windows.Forms.Button();
this.labelExample = new System.Windows.Forms.Label();
this.textBoxExample = new System.Windows.Forms.TextBox();
this.listBoxObj = new Components.Components.UserListBoxObject();
this.buttonAddObjects = new System.Windows.Forms.Button();
this.buttonShowItem = new System.Windows.Forms.Button();
this.labelShowInput = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// dropDownList
//
this.dropDownList.Location = new System.Drawing.Point(3, 3);
this.dropDownList.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.dropDownList.Name = "dropDownList";
this.dropDownList.SelectedValue = "";
this.dropDownList.Size = new System.Drawing.Size(196, 36);
this.dropDownList.TabIndex = 0;
//
// buttonAdd
//
this.buttonAdd.Location = new System.Drawing.Point(3, 46);
this.buttonAdd.Name = "buttonAdd";
this.buttonAdd.Size = new System.Drawing.Size(92, 29);
this.buttonAdd.TabIndex = 1;
this.buttonAdd.Text = "добавить";
this.buttonAdd.UseVisualStyleBackColor = true;
this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
//
// buttonInfo
//
this.buttonInfo.Location = new System.Drawing.Point(211, 46);
this.buttonInfo.Name = "buttonInfo";
this.buttonInfo.Size = new System.Drawing.Size(94, 29);
this.buttonInfo.TabIndex = 2;
this.buttonInfo.Text = "показать";
this.buttonInfo.UseVisualStyleBackColor = true;
this.buttonInfo.Click += new System.EventHandler(this.buttonInfo_Click);
//
// labelInfo
//
this.labelInfo.AutoSize = true;
this.labelInfo.Location = new System.Drawing.Point(205, 9);
this.labelInfo.Name = "labelInfo";
this.labelInfo.Size = new System.Drawing.Size(154, 20);
this.labelInfo.TabIndex = 3;
this.labelInfo.Text = "Выбранный элемент";
//
// buttonClear
//
this.buttonClear.Location = new System.Drawing.Point(101, 46);
this.buttonClear.Name = "buttonClear";
this.buttonClear.Size = new System.Drawing.Size(94, 29);
this.buttonClear.TabIndex = 4;
this.buttonClear.Text = "очистить";
this.buttonClear.UseVisualStyleBackColor = true;
this.buttonClear.Click += new System.EventHandler(this.buttonClear_Click);
//
// emailTextBox
//
this.emailTextBox.Location = new System.Drawing.Point(12, 132);
this.emailTextBox.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.emailTextBox.Name = "emailTextBox";
this.emailTextBox.Pattern = null;
this.emailTextBox.Size = new System.Drawing.Size(179, 34);
this.emailTextBox.TabIndex = 5;
//
// labelShow
//
this.labelShow.AutoSize = true;
this.labelShow.Location = new System.Drawing.Point(12, 170);
this.labelShow.Name = "labelShow";
this.labelShow.Size = new System.Drawing.Size(76, 20);
this.labelShow.TabIndex = 10;
this.labelShow.Text = "проверка";
//
// buttonShow
//
this.buttonShow.Location = new System.Drawing.Point(12, 196);
this.buttonShow.Name = "buttonShow";
this.buttonShow.Size = new System.Drawing.Size(94, 29);
this.buttonShow.TabIndex = 9;
this.buttonShow.Text = "Проверка";
this.buttonShow.UseVisualStyleBackColor = true;
//
// buttonSetExample
//
this.buttonSetExample.Location = new System.Drawing.Point(12, 328);
this.buttonSetExample.Name = "buttonSetExample";
this.buttonSetExample.Size = new System.Drawing.Size(188, 29);
this.buttonSetExample.TabIndex = 8;
this.buttonSetExample.Text = "Поменять пример";
this.buttonSetExample.UseVisualStyleBackColor = true;
//
// labelExample
//
this.labelExample.AutoSize = true;
this.labelExample.Location = new System.Drawing.Point(12, 263);
this.labelExample.Name = "labelExample";
this.labelExample.Size = new System.Drawing.Size(147, 20);
this.labelExample.TabIndex = 7;
this.labelExample.Text = "Для ввода примера";
//
// textBoxExample
//
this.textBoxExample.Location = new System.Drawing.Point(12, 295);
this.textBoxExample.Name = "textBoxExample";
this.textBoxExample.Size = new System.Drawing.Size(188, 27);
this.textBoxExample.TabIndex = 6;
//
// listBoxObj
//
this.listBoxObj.Location = new System.Drawing.Point(388, 13);
this.listBoxObj.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.listBoxObj.Name = "listBoxObj";
this.listBoxObj.SelectedIndex = -1;
this.listBoxObj.Size = new System.Drawing.Size(368, 159);
this.listBoxObj.TabIndex = 11;
//
// buttonAddObjects
//
this.buttonAddObjects.Location = new System.Drawing.Point(388, 179);
this.buttonAddObjects.Name = "buttonAddObjects";
this.buttonAddObjects.Size = new System.Drawing.Size(380, 29);
this.buttonAddObjects.TabIndex = 12;
this.buttonAddObjects.Text = "Добавить";
this.buttonAddObjects.UseVisualStyleBackColor = true;
//
// buttonShowItem
//
this.buttonShowItem.Location = new System.Drawing.Point(388, 310);
this.buttonShowItem.Name = "buttonShowItem";
this.buttonShowItem.Size = new System.Drawing.Size(380, 29);
this.buttonShowItem.TabIndex = 13;
this.buttonShowItem.Text = "Получить";
this.buttonShowItem.UseVisualStyleBackColor = true;
//
// labelShowInput
//
this.labelShowInput.AutoSize = true;
this.labelShowInput.Location = new System.Drawing.Point(388, 273);
this.labelShowInput.Name = "labelShowInput";
this.labelShowInput.Size = new System.Drawing.Size(54, 20);
this.labelShowInput.TabIndex = 14;
this.labelShowInput.Text = "Вывод";
//
// FormForComponents
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.dropDownList);
this.Controls.Add(this.buttonAdd);
this.Controls.Add(this.buttonInfo);
this.Controls.Add(this.labelInfo);
this.Controls.Add(this.buttonClear);
this.Controls.Add(this.emailTextBox);
this.Controls.Add(this.textBoxExample);
this.Controls.Add(this.labelExample);
this.Controls.Add(this.buttonSetExample);
this.Controls.Add(this.labelShow);
this.Controls.Add(this.buttonShow);
this.Controls.Add(this.listBoxObj);
this.Controls.Add(this.buttonAddObjects);
this.Controls.Add(this.buttonShowItem);
this.Controls.Add(this.labelShowInput);
this.Name = "FormForComponents";
this.Text = "FormForComponents";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Components.Components.UserDropDownList dropDownList;
private Button buttonAdd;
private Button buttonInfo;
private Label labelInfo;
private Button buttonClear;
private Components.Components.UserEmailTextBox emailTextBox;
private TextBox textBoxExample;
private Label labelExample;
private Button buttonSetExample;
private Label labelShow;
private Button buttonShow;
private Components.Components.UserListBoxObject listBoxObj;
private Button buttonAddObjects;
private Button buttonShowItem;
private Label labelShowInput;
}
}

View File

@ -1,75 +0,0 @@
using Components.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinForms
{
public partial class FormForComponents : Form
{
List<string> list = new List<string>();
List<Worker> students = new List<Worker>();
public FormForComponents()
{
InitializeComponent();
list = new List<string>();
list.AddRange(new string[] { "слон", "волк", "кролик" });
listBoxObj.SetParams("Имя: {FirstName}, Фамилия: {LastName}. {Experience} ({Age}) лет.", '{', '}');
listBoxObj.AddItems(new List<Worker> { new() { Name = "Иван", LastName = "Иванов", Age = 23, Experience = 5 },
new() { Name = "Егор", LastName = "Булаткин", Age = 30, Experience = 10 },
new() { Name = "Арбуз", LastName = "Арбуз", Age = 40, Experience = 7 } });
dropDownList.LoadValues(new List<string>() { "котенок", "собачка", "лиса" });
emailTextBox.Pattern = @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$";
}
private void CustomEventHandler(object sender, EventArgs e)
{
MessageBox.Show("Выбранный элемент изменен");
}
private void buttonAdd_Click(object sender, EventArgs e)
{
dropDownList.LoadValues(list);
}
private void buttonInfo_Click(object sender, EventArgs e)
{
labelInfo.Text = dropDownList.SelectedValue;
}
private void buttonClear_Click(object sender, EventArgs e)
{
dropDownList.Clear();
}
private void buttonSetExample_Click(object sender, EventArgs e)
{
if (textBoxExample.Text == String.Empty)
{
return;
}
//emailTextBox.setExample(textBoxExample.Text);
}
private void buttonShow_Click(object sender, EventArgs e)
{
try
{
if (emailTextBox.TextBoxValue != null)
{
labelShow.Text = "подходит";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}

182
COP/WinForms/FormMain.Designer.cs generated Normal file
View File

@ -0,0 +1,182 @@
namespace WinForms
{
partial class FormMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.клиентыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.создатьToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.редактироватьToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.удалитьToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.отчётыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.документToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.документСТаблицейToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.документСДиаграммойToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.статусыToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.myTreeView = new ChubykinaComponents.Components.UserTreeView();
this.wordLongTextComponent = new BulatovaComponents.NonVisualComponents.WordLongTextComponent(this.components);
this.excelDiagramComponent = new ChubykinaComponents.LogicalComponents.ExcelDiagramComponent(this.components);
this.componentDocumentWithTableMultiHeaderPdf = new ComponentsLibraryNet60.DocumentWithTable.ComponentDocumentWithTableMultiHeaderPdf(this.components);
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.клиентыToolStripMenuItem,
this.отчётыToolStripMenuItem,
this.статусыToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(800, 28);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// клиентыToolStripMenuItem
//
this.клиентыToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.создатьToolStripMenuItem,
this.редактироватьToolStripMenuItem,
this.удалитьToolStripMenuItem});
this.клиентыToolStripMenuItem.Name = "клиентыToolStripMenuItem";
this.клиентыToolStripMenuItem.Size = new System.Drawing.Size(83, 24);
this.клиентыToolStripMenuItem.Text = "Клиенты";
//
// создатьToolStripMenuItem
//
this.создатьToolStripMenuItem.Name = "создатьToolStripMenuItem";
this.создатьToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.A)));
this.создатьToolStripMenuItem.Size = new System.Drawing.Size(246, 26);
this.создатьToolStripMenuItem.Text = "Создать";
this.создатьToolStripMenuItem.Click += new System.EventHandler(this.создатьToolStripMenuItem_Click);
//
// редактироватьToolStripMenuItem
//
this.редактироватьToolStripMenuItem.Name = "редактироватьToolStripMenuItem";
this.редактироватьToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.U)));
this.редактироватьToolStripMenuItem.Size = new System.Drawing.Size(246, 26);
this.редактироватьToolStripMenuItem.Text = "Редактировать";
this.редактироватьToolStripMenuItem.Click += new System.EventHandler(this.редактироватьToolStripMenuItem_Click);
//
// удалитьToolStripMenuItem
//
this.удалитьToolStripMenuItem.Name = "удалитьToolStripMenuItem";
this.удалитьToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D)));
this.удалитьToolStripMenuItem.Size = new System.Drawing.Size(246, 26);
this.удалитьToolStripMenuItem.Text = "Удалить";
this.удалитьToolStripMenuItem.Click += new System.EventHandler(this.удалитьToolStripMenuItem_Click);
//
// отчётыToolStripMenuItem
//
this.отчётыToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.документToolStripMenuItem,
this.документСТаблицейToolStripMenuItem,
this.документСДиаграммойToolStripMenuItem});
this.отчётыToolStripMenuItem.Name = "отчётыToolStripMenuItem";
this.отчётыToolStripMenuItem.Size = new System.Drawing.Size(73, 24);
this.отчётыToolStripMenuItem.Text = "Отчёты";
//
// документToolStripMenuItem
//
this.документToolStripMenuItem.Name = окументToolStripMenuItem";
this.документToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.документToolStripMenuItem.Size = new System.Drawing.Size(313, 26);
this.документToolStripMenuItem.Text = "Документ";
this.документToolStripMenuItem.Click += new System.EventHandler(this.документToolStripMenuItem_Click);
//
// документСТаблицейToolStripMenuItem
//
this.документСТаблицейToolStripMenuItem.Name = окументСТаблицейToolStripMenuItem";
this.документСТаблицейToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.T)));
this.документСТаблицейToolStripMenuItem.Size = new System.Drawing.Size(313, 26);
this.документСТаблицейToolStripMenuItem.Text = "Документ с таблицей";
this.документСТаблицейToolStripMenuItem.Click += new System.EventHandler(this.документСТаблицейToolStripMenuItem_Click);
//
// документСДиаграммойToolStripMenuItem
//
this.документСДиаграммойToolStripMenuItem.Name = окументСДиаграммойToolStripMenuItem";
this.документСДиаграммойToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C)));
this.документСДиаграммойToolStripMenuItem.Size = new System.Drawing.Size(313, 26);
this.документСДиаграммойToolStripMenuItem.Text = "Документ с диаграммой";
this.документСДиаграммойToolStripMenuItem.Click += new System.EventHandler(this.документСДиаграммойToolStripMenuItem_Click);
//
// статусыToolStripMenuItem
//
this.статусыToolStripMenuItem.Name = "статусыToolStripMenuItem";
this.статусыToolStripMenuItem.Size = new System.Drawing.Size(77, 24);
this.статусыToolStripMenuItem.Text = "Статусы";
this.статусыToolStripMenuItem.Click += new System.EventHandler(this.статусыToolStripMenuItem_Click);
//
// myTreeView
//
this.myTreeView.Dock = System.Windows.Forms.DockStyle.Fill;
this.myTreeView.Location = new System.Drawing.Point(0, 28);
this.myTreeView.Name = "myTreeView";
this.myTreeView.SelectedNodeIndex = -1;
this.myTreeView.Size = new System.Drawing.Size(800, 422);
this.myTreeView.TabIndex = 1;
this.myTreeView.Load += new System.EventHandler(this.FormMain_Load);
//
// FormMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.myTreeView);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "FormMain";
this.Text = "Клиенты";
this.Load += new System.EventHandler(this.FormMain_Load);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem клиентыToolStripMenuItem;
private ToolStripMenuItem отчётыToolStripMenuItem;
private ToolStripMenuItem статусыToolStripMenuItem;
private ChubykinaComponents.Components.UserTreeView myTreeView;
private ToolStripMenuItem создатьToolStripMenuItem;
private ToolStripMenuItem редактироватьToolStripMenuItem;
private ToolStripMenuItem удалитьToolStripMenuItem;
private ToolStripMenuItem документToolStripMenuItem;
private ToolStripMenuItem документСТаблицейToolStripMenuItem;
private ToolStripMenuItem документСДиаграммойToolStripMenuItem;
private BulatovaComponents.NonVisualComponents.WordLongTextComponent wordLongTextComponent;
private ChubykinaComponents.LogicalComponents.ExcelDiagramComponent excelDiagramComponent;
private ComponentsLibraryNet60.DocumentWithTable.ComponentDocumentWithTableMultiHeaderPdf componentDocumentWithTableMultiHeaderPdf;
}
}

195
COP/WinForms/FormMain.cs Normal file
View File

@ -0,0 +1,195 @@
using ClientsContracts.BindingModels;
using ClientsContracts.BusinessLogicContracts;
using ClientsContracts.ViewModels;
using ChubykinaComponents.Components;
using BulatovaComponents.NonVisualComponents;
using ComponentsLibraryNet60.DocumentWithTable;
using ComponentsLibraryNet60.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ChubykinaComponents.LogicalComponents;
namespace WinForms
{
public partial class FormMain : Form
{
private IClientLogic _logic;
public FormMain(IClientLogic logic)
{
InitializeComponent();
_logic = logic;
myTreeView.setHierarchy(new List<(string, bool)> { ("StatusName", false), ("ViewAmount", false), ("Id", true), ("Name", true) });
}
private void статусыToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormStatus));
if (service is FormStatus form)
{
form.ShowDialog();
}
}
private void FormMain_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
//myTreeView.clear();
var clients = _logic.ReadList(null);
if (clients != null)
{
foreach (var client in clients)
{
if (!client.Amount.HasValue)
{
client.ViewAmount = 0;
}
else
{
client.ViewAmount = client.Amount.Value;
}
}
myTreeView.addItems(clients);
}
}
private void создатьToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClient));
if (service is FormClient form)
{
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void редактироватьToolStripMenuItem_Click(object sender, EventArgs e)
{
var service = Program.ServiceProvider?.GetService(typeof(FormClient));
if (service is FormClient form)
{
var selected = myTreeView.getSelecetedNodeValue<ClientViewModel>();
if (selected == null) return;
form.Id = selected.Id;
if (form.ShowDialog() == DialogResult.OK)
{
LoadData();
}
}
}
private void удалитьToolStripMenuItem_Click(object sender, EventArgs e)
{
var selected = myTreeView.getSelecetedNodeValue<ClientViewModel>();
if (selected == null) return;
if (MessageBox.Show("Удалить запись?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
if (_logic.Delete(new ClientBindingModel { Id = selected.Id }))
{
LoadData();
}
}
}
private void документToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new()
{
Filter = "Word Files|*.docx"
};
if (saveFileDialog.ShowDialog() != DialogResult.OK) return;
List<string> paragraphs = new List<string>();
foreach (var client in _logic.ReadList(null))
{
if (client.Amount == null)
{
paragraphs.Add(client.Name + ": " + client.Reviews);
}
}
string path = saveFileDialog.FileName;
wordLongTextComponent.createWithLongText(new WordLongTextInfo(path, "Клиенты без суммы покупок", paragraphs.ToArray()));
MessageBox.Show("Документ создан");
}
private void документСДиаграммойToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new()
{
Filter = "Excel Files|*.xlsx"
};
if (saveFileDialog.ShowDialog() != DialogResult.OK) return;
List<string> paragraphs = new List<string>();
string path = saveFileDialog.FileName;
var data = _logic.ReadList(null).Where(x => x.Amount == null).GroupBy(x => x.StatusName).Select(x => new
{
StatusName = x.Key,
StatusCount = x.Count(),
}).ToList();
excelDiagramComponent.createWithDiagram(path, "Статусы без суммы покупок", "Статусы без суммы покупок", ChubykinaComponents.LogicalComponents.DiagramLegendEnum.BottomRight,
data, "StatusName", "StatusCount");
MessageBox.Show("Документ создан");
}
private void документСТаблицейToolStripMenuItem_Click(object sender, EventArgs e)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
SaveFileDialog saveFileDialog = new()
{
Filter = "PDF Files|*.pdf"
};
if (saveFileDialog.ShowDialog() != DialogResult.OK) return;
List<string> paragraphs = new List<string>();
string path = saveFileDialog.FileName;
var clients = _logic.ReadList(null);
foreach (var client in clients)
{
if (!client.Amount.HasValue)
{
client.DocAmount = "нет";
}
else
{
client.DocAmount = client.Amount.Value.ToString();
}
}
ComponentDocumentWithTableHeaderDataConfig<ClientViewModel> config = new ComponentsLibraryNet60.Models.ComponentDocumentWithTableHeaderDataConfig<ClientViewModel>
{
Data = clients,
UseUnion = false,
Header = "Клиенты",
ColumnsRowsDataCount = (4, 1),
Headers = new List<(int ColumnIndex, int RowIndex, string Header, string PropertyName)>
{
(0, 0, "Id", "Id"),
(1, 0, "ФИО", "Name"),
(2, 0, "Статус", "StatusName"),
(3, 0, "Сумма покупок", "DocAmount")
},
ColumnsRowsWidth = new List<(int Column, int Row)>
{
(10, 10),
(10, 10),
(10, 10),
(10, 10)
},
ColumnUnion = new List<(int StartIndex, int Count)>(),
FilePath = path
};
componentDocumentWithTableMultiHeaderPdf.CreateDoc(config);
MessageBox.Show("Документ создан");
}
}
}

View File

@ -57,4 +57,19 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="wordLongTextComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>152, 17</value>
</metadata>
<metadata name="excelDiagramComponent.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>383, 17</value>
</metadata>
<metadata name="componentDocumentWithTableMultiHeaderPdf.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>609, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>65</value>
</metadata>
</root>

89
COP/WinForms/FormStatus.Designer.cs generated Normal file
View File

@ -0,0 +1,89 @@
namespace WinForms
{
partial class FormStatus
{
/// <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.dataGridView = new System.Windows.Forms.DataGridView();
this.NameCol = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Id = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
//
// dataGridView
//
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.NameCol,
this.Id});
this.dataGridView.Dock = System.Windows.Forms.DockStyle.Fill;
this.dataGridView.Location = new System.Drawing.Point(0, 0);
this.dataGridView.Name = "dataGridView";
this.dataGridView.RowHeadersWidth = 51;
this.dataGridView.RowTemplate.Height = 29;
this.dataGridView.Size = new System.Drawing.Size(800, 450);
this.dataGridView.TabIndex = 0;
this.dataGridView.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellValueChanged);
this.dataGridView.UserDeletingRow += new System.Windows.Forms.DataGridViewRowCancelEventHandler(this.dataGridView_UserDeletingRow);
this.dataGridView.KeyUp += new System.Windows.Forms.KeyEventHandler(this.dataGridView_KeyUp);
//
// NameCol
//
this.NameCol.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
this.NameCol.HeaderText = "Название";
this.NameCol.MinimumWidth = 6;
this.NameCol.Name = "NameCol";
//
// Id
//
this.Id.HeaderText = "Id";
this.Id.MinimumWidth = 6;
this.Id.Name = "Id";
this.Id.Visible = false;
this.Id.Width = 125;
//
// FormStatus
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.dataGridView);
this.Name = "FormStatus";
this.Text = "FormStatus";
this.Load += new System.EventHandler(this.FormStatus_Load);
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DataGridView dataGridView;
private DataGridViewTextBoxColumn NameCol;
private DataGridViewTextBoxColumn Id;
}
}

104
COP/WinForms/FormStatus.cs Normal file
View File

@ -0,0 +1,104 @@
using ClientsContracts.BindingModels;
using ClientsContracts.BusinessLogicContracts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinForms
{
public partial class FormStatus : Form
{
private readonly IStatusLogic _logic;
private bool loading = false;
public FormStatus(IStatusLogic logic)
{
InitializeComponent();
_logic = logic;
}
private void FormStatus_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
loading = true;
try
{
var list = _logic.ReadList();
if (list != null)
{
foreach (var role in list)
{
int rowIndex = dataGridView.Rows.Add();
dataGridView.Rows[rowIndex].Cells[0].Value = role.StatusName;
dataGridView.Rows[rowIndex].Cells[1].Value = role.Id;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
loading = false;
}
}
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (loading || e.RowIndex < 0 || e.ColumnIndex != 0) return;
if (dataGridView.Rows[e.RowIndex].Cells[1].Value != null && !string.IsNullOrEmpty(dataGridView.Rows[e.RowIndex].Cells[1].Value.ToString()))
{
var name = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (name is null) return;
_logic.Update(new StatusBindingModel { Id = Convert.ToInt32(dataGridView.Rows[e.RowIndex].Cells[1].Value), StatusName = name.ToString() });
}
else
{
var name = dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (name is null) return;
_logic.Create(new StatusBindingModel { Id = 0, StatusName = name.ToString() });
int newStatusId = _logic.ReadList().ToList().Last().Id;
dataGridView.Rows[e.RowIndex].Cells[1].Value = newStatusId;
}
}
private void dataGridView_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Insert:
dataGridView.Rows.Add();
break;
}
}
private void deleteRows(DataGridViewSelectedRowCollection rows)
{
for (int i = 0; i < rows.Count; i++)
{
DataGridViewRow row = rows[i];
if (!_logic.Delete(new StatusBindingModel { Id = Convert.ToInt32(row.Cells[1].Value) })) continue;
dataGridView.Rows.Remove(row);
}
}
private void dataGridView_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
e.Cancel = true;
if (dataGridView.SelectedRows == null) return;
if (MessageBox.Show("Удалить записи?", "Подтвердите действие", MessageBoxButtons.YesNo) == DialogResult.No) return;
deleteRows(dataGridView.SelectedRows);
}
}
}

View File

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

View File

@ -1,134 +0,0 @@
namespace WinForms
{
partial class FormWord
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
wordText = new Components.NonVisualComponents.WordText(components);
groupBox1 = new GroupBox();
button1 = new Button();
wordLineChart = new Components.NonVisualComponents.WordLineChart(components);
groupBox3 = new GroupBox();
button3 = new Button();
groupBox2 = new GroupBox();
button2 = new Button();
wordTable = new Components.NonVisualComponents.WordTable(components);
groupBox1.SuspendLayout();
groupBox3.SuspendLayout();
groupBox2.SuspendLayout();
SuspendLayout();
//
// groupBox1
//
groupBox1.Controls.Add(button1);
groupBox1.Location = new Point(12, 12);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(120, 80);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Большой текст";
//
// button1
//
button1.Location = new Point(6, 45);
button1.Name = "button1";
button1.Size = new Size(94, 29);
button1.TabIndex = 0;
button1.Text = "Создать";
button1.UseVisualStyleBackColor = true;
button1.Click += button1_Click;
//
// groupBox3
//
groupBox3.Controls.Add(button3);
groupBox3.Location = new Point(331, 12);
groupBox3.Name = "groupBox3";
groupBox3.Size = new Size(120, 80);
groupBox3.TabIndex = 1;
groupBox3.TabStop = false;
groupBox3.Text = "Линейная диаграмма";
//
// button3
//
button3.Location = new Point(6, 45);
button3.Name = "button3";
button3.Size = new Size(94, 29);
button3.TabIndex = 0;
button3.Text = "Создать";
button3.UseVisualStyleBackColor = true;
button3.Click += button3_Click;
//
// groupBox2
//
groupBox2.Controls.Add(button2);
groupBox2.Location = new Point(171, 12);
groupBox2.Name = "groupBox2";
groupBox2.Size = new Size(120, 80);
groupBox2.TabIndex = 1;
groupBox2.TabStop = false;
groupBox2.Text = "Таблица";
//
// button2
//
button2.Location = new Point(6, 45);
button2.Name = "button2";
button2.Size = new Size(94, 29);
button2.TabIndex = 0;
button2.Text = "Создать";
button2.UseVisualStyleBackColor = true;
button2.Click += button2_Click;
//
// FormWord
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(463, 114);
Controls.Add(groupBox2);
Controls.Add(groupBox3);
Controls.Add(groupBox1);
Name = "FormWord";
Text = "Невизуальные компоненты";
groupBox1.ResumeLayout(false);
groupBox3.ResumeLayout(false);
groupBox2.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private Components.NonVisualComponents.WordText wordText;
private GroupBox groupBox1;
private Button button1;
private Components.NonVisualComponents.WordLineChart wordLineChart;
private GroupBox groupBox3;
private Button button3;
private GroupBox groupBox2;
private Button button2;
private Components.NonVisualComponents.WordTable wordTable;
}
}

View File

@ -1,137 +0,0 @@
using Components.NonVisualComponents;
using Components.SupportClasses.Enums;
using Components.SupportClasses;
using DocumentFormat.OpenXml.Wordprocessing;
using Components.Components;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.WebRequestMethods;
namespace WinForms
{
public partial class FormWord : Form
{
string[] testArray = { "У психолога Сергея Васнецова большие проблемы. От него ушла жена, оставив пятерых дочерей. Да каких - с ума сойти! Первая - модница, вторая - отличница, третья - неформалка, " +
"четвертая - спортсменка, а пятая - совсем крошка Пуговка. Все очень шумные. " +
"И никто не умеет убирать и готовить! Кажется, доктору Васнецову самому скоро понадобится помощь специалиста..."};
public FormWord()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//фильтрация файлов для диалогового окна
using var dialog = new SaveFileDialog
{
Filter = "docx|*.docx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
LargeText largeText = new(dialog.FileName, "Папины дочки", testArray);
wordText.CreateWordText(largeText);
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
List<int[]> mergedColumns = new()
{
new int[] { 0, 1, 2 }
};
List<string> header = new List<string>
{
"Работа",
"",
"",
"Фамилия"
};
List<ColumnDefenitions> columnDefenitions = new List<ColumnDefenitions>
{
new ColumnDefenitions { Header = "Возраст", PropertyName = "Age", Weight = 20 },
new ColumnDefenitions { Header = "Опыт", PropertyName = "Experience", Weight = 20 },
new ColumnDefenitions { Header = "Должность", PropertyName = "Position", Weight = 20 },
new ColumnDefenitions { Header = "Фамилия", PropertyName = "LastName", Weight = 20 }
};
List<Worker> data = new List<Worker>
{
new Worker {Id = 1, Gender = "мужской", Name = "Егор", LastName = "Булаткин", Age = 30, Experience = 10, Position="певец"},
new Worker {Id = 2, Gender = "женский", Name = "Алевтина", LastName = "Антонова", Age = 22, Experience = 3, Position="стоматолог"},
new Worker {Id = 3, Gender = "женский", Name = "Брошка", LastName = "Кулончикова", Age = 25, Experience = 15, Position="комик"},
new Worker {Id = 4, Gender = "мужской", Name = "Милош", LastName = "Коваль", Age = 33, Experience = 1, Position="актер"},
new Worker {Id = 5, Gender = "женский", Name = "Василина", LastName = "Моисеева", Age = 20, Experience = 5, Position="Программист"}
};
using var dialog = new SaveFileDialog
{
Filter = "docx|*.docx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
BigTable<Worker> bigTable = new(dialog.FileName, "Задание 2", header, columnDefenitions, data, mergedColumns);
wordTable.CreateTable(bigTable);
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void button3_Click(object sender, EventArgs e)
{
//фильтрация файлов для диалогового окна
using var dialog = new SaveFileDialog
{
Filter = "docx|*.docx"
};
if (dialog.ShowDialog() == DialogResult.OK)
{
try
{
string[] month = { "Январь", "Февраль", "Март" };
double[] profit1 = { 300, 440, 270 };
double[] profit2 = { 500, 620, 310 };
double[] profit3 = { 420, 189, 430 };
SimpleLineChart lineChart = new(dialog.FileName, "Третье задание", "График прибыли", EnumAreaLegend.Right, new List<DataLineChart> {
new DataLineChart("Компания 1", month, profit1), new DataLineChart("Компания 2", month, profit2), new DataLineChart("Компания 3", month, profit3),
});
wordLineChart.AddLineChart(lineChart);
MessageBox.Show("Выполнено", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@ -1,7 +1,17 @@
using ClientBusinessLogic.BusinessLogics;
using ClientsContracts.BusinessLogicContracts;
using ClientsContracts.StorageContracts;
using ClientsDatabaseImplement.Implements;
using Microsoft.Extensions.DependencyInjection;
using System;
namespace WinForms
{
internal static class Program
{
private static ServiceProvider? _serviceProvider;
public static ServiceProvider? ServiceProvider => _serviceProvider;
/// <summary>
/// The main entry point for the application.
/// </summary>
@ -11,7 +21,21 @@ namespace WinForms
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormWord());
var services = new ServiceCollection();
ConfigureServices(services);
_serviceProvider = services.BuildServiceProvider();
Application.Run(_serviceProvider.GetRequiredService<FormMain>());
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddTransient<IStatusStorage, StatusStorage>();
services.AddTransient<IClientStorage, ClientStorage>();
services.AddTransient<IStatusLogic, StatusLogic>();
services.AddTransient<IClientLogic, ClientLogic>();
services.AddTransient<FormMain>();
services.AddTransient<FormClient>();
services.AddTransient<FormStatus>();
}
}
}

View File

@ -9,11 +9,20 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.0" />
<PackageReference Include="ChubykinaComponents" Version="1.0.1" />
<PackageReference Include="ComponentsLibraryNet60" Version="1.0.0" />
<PackageReference Include="ControlsLibraryNet60" Version="1.0.0" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.20">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Components\Components.csproj" />
<ProjectReference Include="..\BulatovaComponents\BulatovaComponents.csproj" />
<ProjectReference Include="..\ClientBusinessLogic\ClientBusinessLogic.csproj" />
<ProjectReference Include="..\ClientsDatabaseImplement\ClientsDatabaseImplement.csproj" />
</ItemGroup>
</Project>

View File

@ -1,25 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinForms
{
public class Worker
{
public int Id { get; set; }
public string Gender { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
public string LastName { get; set; } = string.Empty;
public int Age { get; set; }
public int Experience { get; set; }
public string Position { get; set; } = string.Empty;
}
}