Compare commits

...

12 Commits
main ... lab3

Author SHA1 Message Date
e461145e65 lab3 2024-12-25 03:43:10 +04:00
4d0f7d2693 exel 0.5 2024-12-09 14:52:14 +04:00
8ef203ae66 directory report 2024-12-09 07:08:43 +04:00
adc93488c9 lab2 done 2024-12-09 06:05:57 +04:00
1a50d8d5c4 without db and logs 2024-11-25 14:50:53 +04:00
0b03273946 log +logic 2.0 for cleaning and athlete 2024-11-25 10:54:16 +04:00
c1c71548a4 log + logic for cleaning and athlete 2024-11-25 10:52:52 +04:00
338521a88f Update lab2.vpp 2024-11-25 08:39:37 +04:00
1df413458a lab1 2024-11-25 08:31:54 +04:00
3435de98be 1233 2024-11-11 14:52:46 +04:00
bcd36cebc6 1 2024-11-11 10:59:50 +04:00
8f986c6beb 1/3 2024-10-28 01:37:59 +04:00
85 changed files with 6687 additions and 82 deletions

View File

@ -0,0 +1 @@
DELETE TABLE athletes

View File

@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.8.34525.116 VisualStudioVersion = 17.8.34525.116
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectHotel", "ProjectHotel\ProjectHotel.csproj", "{A2780283-9040-4F10-8929-96574BD22EAD}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectHotel", "ProjectHotel\ProjectHotel.csproj", "{C81DFC0D-3F51-4F84-AF78-1ADA30A157B1}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -11,15 +11,15 @@ Global
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A2780283-9040-4F10-8929-96574BD22EAD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C81DFC0D-3F51-4F84-AF78-1ADA30A157B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A2780283-9040-4F10-8929-96574BD22EAD}.Debug|Any CPU.Build.0 = Debug|Any CPU {C81DFC0D-3F51-4F84-AF78-1ADA30A157B1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A2780283-9040-4F10-8929-96574BD22EAD}.Release|Any CPU.ActiveCfg = Release|Any CPU {C81DFC0D-3F51-4F84-AF78-1ADA30A157B1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A2780283-9040-4F10-8929-96574BD22EAD}.Release|Any CPU.Build.0 = Release|Any CPU {C81DFC0D-3F51-4F84-AF78-1ADA30A157B1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {63AC2E5C-4881-4878-851B-89C4AC958820} SolutionGuid = {20DC1BC0-A8A5-4BA7-B0A2-533382967ACC}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View File

@ -0,0 +1,33 @@

using ProjectHotel.Entities.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Entities;
public class Athlete
{
public int Id { get; set; }
public string FirstName { get; private set; } = string.Empty;
public string LastName { get; private set; } = string.Empty;
public string FatherName { get; private set; } = string.Empty;
public Sport Sport { get; private set; }
public AthleteClass AthleteClass { get; private set; }
public static Athlete CreateEntity(int id, string first, string last, string father, Sport sport, AthleteClass athleteClass)
{
return new Athlete
{
Id = id,
FirstName = first ?? string.Empty,
LastName = last ?? string.Empty,
FatherName = father ?? string.Empty,
Sport = sport,
AthleteClass = athleteClass
};
}
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Entities;
public class AthletePlacingAthlete
{
public int Id { get; set; }
public int AthleteId { get; private set; }
public int PlacingAthleteId{ get; private set; }
public int LengthOfStay { get; private set; }
public static AthletePlacingAthlete CreateElement(int id, int athleteId, int lengthOfStay)
{
return new AthletePlacingAthlete
{
Id = id,
AthleteId = athleteId,
LengthOfStay = lengthOfStay
};
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Entities;
public class CleaningRoom
{
public int Id { get; set; }
public int RoomId { get; set; }
public DateTime CleaningDate { get; private set; }
public static CleaningRoom CreateOperation(int id, int roomId)
{
return new CleaningRoom
{
Id = id,
RoomId = roomId,
CleaningDate = DateTime.Now
};
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Entities.Enums;
public enum AthleteClass
{
None = 0,
MSMK = 1,
MS = 2,
KMS = 3
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Entities.Enums;
[Flags]
public enum Sport
{
None = 0,
Archery = 2,
Athletics = 4,
Badminton = 8,
Basketball = 16,
Boxing = 32,
Cycling = 64,
Fencing = 128,
Gymnastics = 256,
Rowing = 512,
Swimming = 1024
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Entities;
public class Hotel
{
public int Id { get; private set; }
public string Name { get; private set; } = string.Empty;
public string Address { get; private set; } = string.Empty;
public static Hotel CreateEntity(int id, string name, string address)
{
return new Hotel
{
Id = id,
Name = name,
Address = address
};
}
}

View File

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Entities;
public class PlacingAthlete
{
public int Id { get; private set; }
public int RoomId { get; private set; }
public DateTime PlacingDate { get; private set; }
public IEnumerable<AthletePlacingAthlete> AthletePlacingAthletes
{
get;
private set;
} = [];
public static PlacingAthlete CreateOpeartion(int id, int roomId, IEnumerable<AthletePlacingAthlete> athletePlacingAthletes)
{
return new PlacingAthlete
{
Id = id,
RoomId = roomId,
PlacingDate = DateTime.Now,
AthletePlacingAthletes = athletePlacingAthletes
};
}
public static PlacingAthlete CreateOpeartion(TempAthletePlacingAthlete tempAthletePlacingAthlete, IEnumerable<AthletePlacingAthlete> athletePlacingAthletes)
{
return new PlacingAthlete
{
Id = tempAthletePlacingAthlete.Id,
RoomId = tempAthletePlacingAthlete.RoomId,
PlacingDate = DateTime.Now,
AthletePlacingAthletes = athletePlacingAthletes
};
}
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace ProjectHotel.Entities;
public class Room
{
public int Id { get; private set; }
public int HotelId { get; private set; }
public string Name { get; private set; } = string.Empty;
public int Capacity { get; private set; }
public static Room CreateEntity(int id, int hotel, string name, int capacity)
{
return new Room
{
Id = id,
HotelId = hotel,
Name = name,
Capacity = capacity
};
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Entities;
public class TempAthletePlacingAthlete
{
public int Id { get; private set; }
public int RoomId { get; private set; }
public DateTime PlacingDate { get; private set; }
public int AthleteId { get; private set; }
public int PlacingAthleteId { get; private set; }
public int LengthOfStay { get; private set; }
}

View File

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

View File

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

View File

@ -0,0 +1,187 @@
namespace ProjectHotel.Forms
{
partial class FormAthlete
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
labelName = new Label();
labelSeckondName = new Label();
labelFatherName = new Label();
textBoxFirstName = new TextBox();
textBoxLastName = new TextBox();
textBoxFatherName = new TextBox();
comboBoxClass = new ComboBox();
labelClass = new Label();
label1 = new Label();
checkedListBoxSport = new CheckedListBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelName
//
labelName.AutoSize = true;
labelName.Location = new Point(12, 15);
labelName.Name = "labelName";
labelName.Size = new Size(31, 15);
labelName.TabIndex = 0;
labelName.Text = "Имя";
//
// labelSeckondName
//
labelSeckondName.AutoSize = true;
labelSeckondName.Location = new Point(12, 59);
labelSeckondName.Name = "labelSeckondName";
labelSeckondName.Size = new Size(58, 15);
labelSeckondName.TabIndex = 1;
labelSeckondName.Text = "Фамилия";
//
// labelFatherName
//
labelFatherName.AutoSize = true;
labelFatherName.Location = new Point(12, 104);
labelFatherName.Name = "labelFatherName";
labelFatherName.Size = new Size(58, 15);
labelFatherName.TabIndex = 2;
labelFatherName.Text = "Отчество";
//
// textBoxFirstName
//
textBoxFirstName.Location = new Point(99, 12);
textBoxFirstName.Name = "textBoxFirstName";
textBoxFirstName.Size = new Size(207, 23);
textBoxFirstName.TabIndex = 3;
//
// textBoxLastName
//
textBoxLastName.Location = new Point(99, 56);
textBoxLastName.Name = "textBoxLastName";
textBoxLastName.Size = new Size(207, 23);
textBoxLastName.TabIndex = 4;
//
// textBoxFatherName
//
textBoxFatherName.Location = new Point(99, 101);
textBoxFatherName.Name = "textBoxFatherName";
textBoxFatherName.Size = new Size(207, 23);
textBoxFatherName.TabIndex = 5;
//
// comboBoxClass
//
comboBoxClass.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxClass.FormattingEnabled = true;
comboBoxClass.Location = new Point(99, 144);
comboBoxClass.Name = "comboBoxClass";
comboBoxClass.Size = new Size(207, 23);
comboBoxClass.TabIndex = 6;
//
// labelClass
//
labelClass.AutoSize = true;
labelClass.Location = new Point(12, 147);
labelClass.Name = "labelClass";
labelClass.Size = new Size(44, 15);
labelClass.TabIndex = 7;
labelClass.Text = "Разряд";
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(12, 186);
label1.Name = "label1";
label1.Size = new Size(41, 15);
label1.TabIndex = 8;
label1.Text = "Спорт";
//
// checkedListBoxSport
//
checkedListBoxSport.FormattingEnabled = true;
checkedListBoxSport.Location = new Point(98, 193);
checkedListBoxSport.Name = "checkedListBoxSport";
checkedListBoxSport.Size = new Size(278, 112);
checkedListBoxSport.TabIndex = 9;
//
// buttonSave
//
buttonSave.Location = new Point(61, 324);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 11;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += buttonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(251, 324);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 10;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += buttonCancel_Click;
//
// FormAthlete
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(388, 359);
Controls.Add(buttonSave);
Controls.Add(buttonCancel);
Controls.Add(checkedListBoxSport);
Controls.Add(label1);
Controls.Add(labelClass);
Controls.Add(comboBoxClass);
Controls.Add(textBoxFatherName);
Controls.Add(textBoxLastName);
Controls.Add(textBoxFirstName);
Controls.Add(labelFatherName);
Controls.Add(labelSeckondName);
Controls.Add(labelName);
Name = "FormAthlete";
StartPosition = FormStartPosition.CenterParent;
Text = "Спортсмен";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelName;
private Label labelSeckondName;
private Label labelFatherName;
private TextBox textBoxFirstName;
private TextBox textBoxLastName;
private TextBox textBoxFatherName;
private ComboBox comboBoxClass;
private Label labelClass;
private Label label1;
private CheckedListBox checkedListBoxSport;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,105 @@
using Microsoft.VisualBasic.FileIO;
using ProjectHotel.Entities;
using ProjectHotel.Entities.Enums;
using ProjectHotel.Repositories;
using ProjectHotel.Repositories.Implementations;
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 ProjectHotel.Forms;
public partial class FormAthlete : Form
{
private readonly IAthleteRepository _athleteRepository;
private int? _athleteId;
public int Id
{
set
{
try
{
var athlete = _athleteRepository.ReadAthleteById(value);
if (athlete == null)
{
throw new
InvalidDataException(nameof(athlete));
}
foreach (Sport elem in Enum.GetValues(typeof(Sport)))
{
if ((elem & athlete.Sport) != 0)
{
checkedListBoxSport.SetItemChecked(checkedListBoxSport.Items.IndexOf(elem), true);
}
}
textBoxFirstName.Text = athlete.FirstName;
textBoxLastName.Text = athlete.LastName;
textBoxFatherName.Text = athlete.FatherName;
comboBoxClass.SelectedItem = athlete.AthleteClass;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormAthlete(IAthleteRepository athleteRepository)
{
InitializeComponent();
_athleteRepository = athleteRepository ??
throw new ArgumentNullException(nameof(athleteRepository));
foreach (var elem in Enum.GetValues(typeof(Sport)))
{
checkedListBoxSport.Items.Add(elem);
}
comboBoxClass.DataSource = Enum.GetValues(typeof(AthleteClass));
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFirstName.Text) ||
string.IsNullOrWhiteSpace(textBoxLastName.Text) ||
string.IsNullOrWhiteSpace(textBoxFatherName.Text) ||
comboBoxClass.SelectedIndex < 0 || checkedListBoxSport.SelectedIndex < 0)
{
throw new Exception("Имеются незаполненные поля");
}
if (_athleteId.HasValue)
{
_athleteRepository.UpdateAthlete(CreateAthlete(_athleteId.Value));
}
else
{
_athleteRepository.CreateAthlete(CreateAthlete(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void buttonCancel_Click(object sender, EventArgs e) =>
Close();
private Athlete CreateAthlete(int id)
{
Sport sport = Sport.None;
foreach (var elem in checkedListBoxSport.CheckedItems)
{
sport |= (Sport)elem;
}
return Athlete.CreateEntity(id, textBoxFirstName.Text, textBoxLastName.Text,
textBoxFatherName.Text, sport, (AthleteClass)comboBoxClass.SelectedItem!);
}
}

View File

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

View File

@ -0,0 +1,126 @@
namespace ProjectHotel.Forms
{
partial class FormAthletes
{
/// <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()
{
panel1 = new Panel();
buttonDelete = new Button();
buttonChange = new Button();
buttonAdd = new Button();
dataGridViewData = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(buttonDelete);
panel1.Controls.Add(buttonChange);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(632, 0);
panel1.Name = "panel1";
panel1.Size = new Size(168, 450);
panel1.TabIndex = 1;
//
// buttonDelete
//
buttonDelete.BackgroundImage = Properties.Resources.ImageDelete;
buttonDelete.BackgroundImageLayout = ImageLayout.Zoom;
buttonDelete.Location = new Point(24, 308);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(130, 130);
buttonDelete.TabIndex = 2;
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonChange
//
buttonChange.BackgroundImage = Properties.Resources.ImageChange;
buttonChange.BackgroundImageLayout = ImageLayout.Zoom;
buttonChange.Location = new Point(24, 158);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(130, 130);
buttonChange.TabIndex = 1;
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ButtonChange_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.AddImage;
buttonAdd.BackgroundImageLayout = ImageLayout.Zoom;
buttonAdd.Location = new Point(24, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(130, 130);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
dataGridViewData.AllowUserToDeleteRows = false;
dataGridViewData.AllowUserToResizeColumns = false;
dataGridViewData.AllowUserToResizeRows = false;
dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(632, 450);
dataGridViewData.TabIndex = 2;
//
// FormAthletes
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
Name = "FormAthletes";
StartPosition = FormStartPosition.CenterParent;
Text = "FormAthletes";
Load += FormAthletes_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button buttonDelete;
private Button buttonChange;
private Button buttonAdd;
private DataGridView dataGridViewData;
}
}

View File

@ -0,0 +1,107 @@
using ProjectHotel.Repositories;
using ProjectHotel.Repositories.Implementations;
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 Unity;
namespace ProjectHotel.Forms;
public partial class FormAthletes : Form
{
private readonly IUnityContainer _container;
private readonly IAthleteRepository _athleteRepository;
public FormAthletes(IUnityContainer container, IAthleteRepository athleteRepository)
{
InitializeComponent();
_container = container ?? throw new ArgumentNullException(nameof(container));
_athleteRepository = athleteRepository ?? throw new ArgumentNullException(nameof(athleteRepository));
}
private void FormAthletes_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormAthlete>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonChange_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormAthlete>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_athleteRepository.DeleteAthlete(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource = _athleteRepository.ReadAthletes();
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewData.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewData.SelectedRows[0].Cells["Id"].Value);
return true;
}
}

View File

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

View File

@ -0,0 +1,98 @@
namespace ProjectHotel.Forms
{
partial class FormCleaningRoom
{
/// <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()
{
labelRoom = new Label();
comboBoxRoom = new ComboBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// labelRoom
//
labelRoom.AutoSize = true;
labelRoom.Location = new Point(46, 54);
labelRoom.Name = "labelRoom";
labelRoom.Size = new Size(97, 15);
labelRoom.TabIndex = 0;
labelRoom.Text = "Номер комнаты";
//
// comboBoxRoom
//
comboBoxRoom.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxRoom.FormattingEnabled = true;
comboBoxRoom.Location = new Point(176, 51);
comboBoxRoom.Name = "comboBoxRoom";
comboBoxRoom.Size = new Size(161, 23);
comboBoxRoom.TabIndex = 1;
//
// buttonSave
//
buttonSave.Location = new Point(68, 149);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 2;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(218, 149);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 3;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormCleaningRoom
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(364, 194);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(comboBoxRoom);
Controls.Add(labelRoom);
Name = "FormCleaningRoom";
StartPosition = FormStartPosition.CenterParent;
Text = "FormCleaningRoom";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label labelRoom;
private ComboBox comboBoxRoom;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,49 @@
using ProjectHotel.Entities.Enums;
using ProjectHotel.Entities;
using ProjectHotel.Repositories;
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 ProjectHotel.Forms;
public partial class FormCleaningRoom : Form
{
private readonly ICleaningRoomRepository _cleaningRoomRepository;
public FormCleaningRoom(ICleaningRoomRepository cleaningRoomRepository, IRoomRepository roomRepository)
{
InitializeComponent();
_cleaningRoomRepository = cleaningRoomRepository ??
throw new ArgumentNullException(nameof(cleaningRoomRepository));
comboBoxRoom.DataSource = roomRepository.ReadRooms();
comboBoxRoom.DisplayMember = "Name";
comboBoxRoom.ValueMember = "Id";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (comboBoxRoom.SelectedIndex < 0)
{
throw new Exception("Имеются незаполненные поля");
}
_cleaningRoomRepository.CreateCleaningRoom(CleaningRoom.CreateOperation(0, (int)comboBoxRoom.SelectedValue!));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
}

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,98 @@
namespace ProjectHotel.Forms
{
partial class FormCleaningRooms
{
/// <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()
{
dataGridViewData = new DataGridView();
panel1 = new Panel();
buttonAdd = new Button();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
panel1.SuspendLayout();
SuspendLayout();
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
dataGridViewData.AllowUserToDeleteRows = false;
dataGridViewData.AllowUserToResizeColumns = false;
dataGridViewData.AllowUserToResizeRows = false;
dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(579, 445);
dataGridViewData.TabIndex = 5;
//
// panel1
//
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(579, 0);
panel1.Name = "panel1";
panel1.Size = new Size(168, 445);
panel1.TabIndex = 4;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.AddImage;
buttonAdd.BackgroundImageLayout = ImageLayout.Zoom;
buttonAdd.Location = new Point(26, 146);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(130, 130);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// FormCleaningRooms
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(747, 445);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
Name = "FormCleaningRooms";
StartPosition = FormStartPosition.CenterParent;
Text = "FormCleaningRooms";
Load += FormCleaningRooms_Load;
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
panel1.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private DataGridView dataGridViewData;
private Panel panel1;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,56 @@
using ProjectHotel.Repositories;
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 Unity;
namespace ProjectHotel.Forms;
public partial class FormCleaningRooms : Form
{
private readonly IUnityContainer _container;
private readonly ICleaningRoomRepository _cleaningRoomRepository;
public FormCleaningRooms(IUnityContainer container, ICleaningRoomRepository cleaningRoomRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_cleaningRoomRepository = cleaningRoomRepository ??
throw new ArgumentNullException(nameof(cleaningRoomRepository));
}
private void FormCleaningRooms_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormCleaningRoom>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource = _cleaningRoomRepository.ReadCleaningRooms();
}

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,100 @@
namespace ProjectHotel.Forms
{
partial class FormDirectoryReport
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
checkBoxAthletes = new CheckBox();
checkBoxRooms = new CheckBox();
checkBoxHotels = new CheckBox();
buttonBuild = new Button();
SuspendLayout();
//
// checkBoxAthletes
//
checkBoxAthletes.AutoSize = true;
checkBoxAthletes.Location = new Point(12, 12);
checkBoxAthletes.Name = "checkBoxAthletes";
checkBoxAthletes.Size = new Size(97, 19);
checkBoxAthletes.TabIndex = 0;
checkBoxAthletes.Text = "Спортсмены";
checkBoxAthletes.UseVisualStyleBackColor = true;
//
// checkBoxRooms
//
checkBoxRooms.AutoSize = true;
checkBoxRooms.Location = new Point(12, 67);
checkBoxRooms.Name = "checkBoxRooms";
checkBoxRooms.Size = new Size(76, 19);
checkBoxRooms.TabIndex = 1;
checkBoxRooms.Text = "Комнаты";
checkBoxRooms.UseVisualStyleBackColor = true;
//
// checkBoxHotels
//
checkBoxHotels.AutoSize = true;
checkBoxHotels.Location = new Point(12, 123);
checkBoxHotels.Name = "checkBoxHotels";
checkBoxHotels.Size = new Size(87, 19);
checkBoxHotels.TabIndex = 2;
checkBoxHotels.Text = "Гостиницы";
checkBoxHotels.UseVisualStyleBackColor = true;
//
// buttonBuild
//
buttonBuild.Location = new Point(194, 67);
buttonBuild.Name = "buttonBuild";
buttonBuild.Size = new Size(97, 24);
buttonBuild.TabIndex = 3;
buttonBuild.Text = "сформировать";
buttonBuild.UseVisualStyleBackColor = true;
buttonBuild.Click += ButtonBuild_Click;
//
// FormDirectoryReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(357, 216);
Controls.Add(buttonBuild);
Controls.Add(checkBoxHotels);
Controls.Add(checkBoxRooms);
Controls.Add(checkBoxAthletes);
Name = "FormDirectoryReport";
StartPosition = FormStartPosition.CenterParent;
Text = "Выгрузка справочников";
ResumeLayout(false);
PerformLayout();
}
#endregion
private CheckBox checkBoxAthletes;
private CheckBox checkBoxRooms;
private CheckBox checkBoxHotels;
private Button buttonBuild;
}
}

View File

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

View File

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

View File

@ -0,0 +1,119 @@
namespace ProjectHotel.Forms
{
partial class FormHotel
{
/// <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()
{
label1 = new Label();
label2 = new Label();
textBoxHotelName = new TextBox();
textBoxHotelAddress = new TextBox();
buttonSave = new Button();
buttonCancel = new Button();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(15, 41);
label1.Name = "label1";
label1.Size = new Size(122, 15);
label1.TabIndex = 0;
label1.Text = "Название гостиницы";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(15, 93);
label2.Name = "label2";
label2.Size = new Size(46, 15);
label2.TabIndex = 1;
label2.Text = "Адресс";
//
// textBoxHotelName
//
textBoxHotelName.Location = new Point(168, 38);
textBoxHotelName.Name = "textBoxHotelName";
textBoxHotelName.Size = new Size(390, 23);
textBoxHotelName.TabIndex = 2;
//
// textBoxHotelAddress
//
textBoxHotelAddress.Location = new Point(168, 90);
textBoxHotelAddress.Name = "textBoxHotelAddress";
textBoxHotelAddress.Size = new Size(387, 23);
textBoxHotelAddress.TabIndex = 3;
//
// buttonSave
//
buttonSave.Location = new Point(105, 136);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// buttonCancel
//
buttonCancel.Location = new Point(385, 136);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// FormHotel
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(570, 167);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(textBoxHotelAddress);
Controls.Add(textBoxHotelName);
Controls.Add(label2);
Controls.Add(label1);
Name = "FormHotel";
StartPosition = FormStartPosition.CenterParent;
Text = "Гостиница";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private TextBox textBoxHotelName;
private TextBox textBoxHotelAddress;
private Button buttonSave;
private Button buttonCancel;
}
}

View File

@ -0,0 +1,84 @@
using ProjectHotel.Entities;
using ProjectHotel.Repositories;
using ProjectHotel.Repositories.Implementations;
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 ProjectHotel.Forms;
public partial class FormHotel : Form
{
private readonly IHotelRepository _hotelRepository;
private int? _hotelId;
public int Id
{
set
{
try
{
var hotel =
_hotelRepository.ReadHotelById(value);
if (hotel == null)
{
throw new
InvalidDataException(nameof(hotel));
}
textBoxHotelName.Text = hotel.Name;
textBoxHotelAddress.Text =
hotel.Address;
_hotelId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormHotel(IHotelRepository hotelRepository)
{
InitializeComponent();
_hotelRepository = hotelRepository ??
throw new
ArgumentNullException(nameof(hotelRepository));
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxHotelName.Text)
||
string.IsNullOrWhiteSpace(textBoxHotelAddress.Text))
{
throw new Exception("Имеются незаполненные поля");
}
if (_hotelId.HasValue)
{
_hotelRepository.UpdateHotel(CreateHotel(_hotelId.Value));
}
else
{
_hotelRepository.CreateHotel(CreateHotel(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Hotel CreateHotel(int id) => Hotel.CreateEntity(id, textBoxHotelName.Text, textBoxHotelAddress.Text);
}

View File

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

View File

@ -0,0 +1,166 @@
namespace ProjectHotel
{
partial class FormHotelForAthletes
{
/// <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()
{
menuStrip1 = new MenuStrip();
DirectoriesToolStripMenuItem = new ToolStripMenuItem();
RoomsToolStripMenuItem = new ToolStripMenuItem();
HotelsToolStripMenuItem = new ToolStripMenuItem();
AthletesToolStripMenuItem = new ToolStripMenuItem();
OperationsToolStripMenuItem = new ToolStripMenuItem();
PlacingAthleteToolStripMenuItem = new ToolStripMenuItem();
CleaningRoomToolStripMenuItem = new ToolStripMenuItem();
ReportsToolStripMenuItem = new ToolStripMenuItem();
DirectoryReportToolStripMenuItem = new ToolStripMenuItem();
HotelToolStripMenuItem = new ToolStripMenuItem();
DiagramToolStripMenuItem = new ToolStripMenuItem();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { DirectoriesToolStripMenuItem, OperationsToolStripMenuItem, ReportsToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(800, 24);
menuStrip1.TabIndex = 0;
menuStrip1.Text = "menuStrip1";
//
// DirectoriesToolStripMenuItem
//
DirectoriesToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { RoomsToolStripMenuItem, HotelsToolStripMenuItem, AthletesToolStripMenuItem });
DirectoriesToolStripMenuItem.Name = "DirectoriesToolStripMenuItem";
DirectoriesToolStripMenuItem.Size = new Size(94, 20);
DirectoriesToolStripMenuItem.Text = "Справочники";
//
// RoomsToolStripMenuItem
//
RoomsToolStripMenuItem.Name = "RoomsToolStripMenuItem";
RoomsToolStripMenuItem.Size = new Size(145, 22);
RoomsToolStripMenuItem.Text = "Комнаты";
RoomsToolStripMenuItem.Click += RoomsToolStripMenuItem_Click;
//
// HotelsToolStripMenuItem
//
HotelsToolStripMenuItem.Name = "HotelsToolStripMenuItem";
HotelsToolStripMenuItem.Size = new Size(145, 22);
HotelsToolStripMenuItem.Text = "Отелели";
HotelsToolStripMenuItem.Click += HotelsToolStripMenuItem_Click;
//
// AthletesToolStripMenuItem
//
AthletesToolStripMenuItem.Name = "AthletesToolStripMenuItem";
AthletesToolStripMenuItem.Size = new Size(145, 22);
AthletesToolStripMenuItem.Text = "Спортсмены";
AthletesToolStripMenuItem.Click += AthletesToolStripMenuItem_Click;
//
// OperationsToolStripMenuItem
//
OperationsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { PlacingAthleteToolStripMenuItem, CleaningRoomToolStripMenuItem });
OperationsToolStripMenuItem.Name = "OperationsToolStripMenuItem";
OperationsToolStripMenuItem.Size = new Size(75, 20);
OperationsToolStripMenuItem.Text = "Операции";
//
// PlacingAthleteToolStripMenuItem
//
PlacingAthleteToolStripMenuItem.Name = "PlacingAthleteToolStripMenuItem";
PlacingAthleteToolStripMenuItem.Size = new Size(201, 22);
PlacingAthleteToolStripMenuItem.Text = "Заселение спортсмена";
PlacingAthleteToolStripMenuItem.Click += PlacingAthleteToolStripMenuItem_Click;
//
// CleaningRoomToolStripMenuItem
//
CleaningRoomToolStripMenuItem.Name = "CleaningRoomToolStripMenuItem";
CleaningRoomToolStripMenuItem.Size = new Size(201, 22);
CleaningRoomToolStripMenuItem.Text = "Уборка комнаты";
CleaningRoomToolStripMenuItem.Click += CleaningRoomToolStripMenuItem_Click;
//
// ReportsToolStripMenuItem
//
ReportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { DirectoryReportToolStripMenuItem, HotelToolStripMenuItem, DiagramToolStripMenuItem });
ReportsToolStripMenuItem.Name = "ReportsToolStripMenuItem";
ReportsToolStripMenuItem.Size = new Size(60, 20);
ReportsToolStripMenuItem.Text = "Отчеты";
//
// DirectoryReportToolStripMenuItem
//
DirectoryReportToolStripMenuItem.Name = "DirectoryReportToolStripMenuItem";
DirectoryReportToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W;
DirectoryReportToolStripMenuItem.Size = new Size(280, 22);
DirectoryReportToolStripMenuItem.Text = "Документ со справочниками";
DirectoryReportToolStripMenuItem.Click += DirectoryReportToolStripMenuItem_Click;
//
// HotelToolStripMenuItem
//
HotelToolStripMenuItem.Name = "HotelToolStripMenuItem";
HotelToolStripMenuItem.Size = new Size(280, 22);
HotelToolStripMenuItem.Text = "Отчет о проживающих в отеле";
HotelToolStripMenuItem.Click += RoomToolStripMenuItem_Click;
//
// DiagramToolStripMenuItem
//
DiagramToolStripMenuItem.Name = "DiagramToolStripMenuItem";
DiagramToolStripMenuItem.Size = new Size(280, 22);
DiagramToolStripMenuItem.Text = "Диаграмма";
DiagramToolStripMenuItem.Click += DiagramToolStripMenuItem_Click;
//
// FormHotelForAthletes
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
BackgroundImage = Properties.Resources.hotel;
BackgroundImageLayout = ImageLayout.Stretch;
ClientSize = new Size(800, 450);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormHotelForAthletes";
StartPosition = FormStartPosition.CenterScreen;
Text = "Гостиница";
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
private MenuStrip menuStrip1;
private ToolStripMenuItem DirectoriesToolStripMenuItem;
private ToolStripMenuItem RoomsToolStripMenuItem;
private ToolStripMenuItem HotelsToolStripMenuItem;
private ToolStripMenuItem AthletesToolStripMenuItem;
private ToolStripMenuItem OperationsToolStripMenuItem;
private ToolStripMenuItem PlacingAthleteToolStripMenuItem;
private ToolStripMenuItem ReportsToolStripMenuItem;
private ToolStripMenuItem CleaningRoomToolStripMenuItem;
private ToolStripMenuItem DirectoryReportToolStripMenuItem;
private ToolStripMenuItem HotelToolStripMenuItem;
private ToolStripMenuItem DiagramToolStripMenuItem;
}
}

View File

@ -0,0 +1,122 @@
using ProjectHotel.Forms;
using System.ComponentModel;
using System.Xml.Linq;
using Unity;
namespace ProjectHotel;
public partial class FormHotelForAthletes : Form
{
private readonly IUnityContainer _container;
public FormHotelForAthletes(IUnityContainer container)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
}
private void RoomsToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormRooms>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void HotelsToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormHotels>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AthletesToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormAthletes>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void PlacingAthleteToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormPlacingAthletes>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void CleaningRoomToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormCleaningRooms>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DirectoryReportToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormDirectoryReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void RoomToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormHotelReport>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void DiagramToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormPlacingRoomDistribution>().ShowDialog();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà ïðè çàãðóçêå",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

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

View File

@ -0,0 +1,163 @@
namespace ProjectHotel.Forms
{
partial class FormHotelReport
{
/// <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()
{
dateTimePickerDateBegin = new DateTimePicker();
dateTimePickerDateEnd = new DateTimePicker();
comboBoxHotel = new ComboBox();
label1 = new Label();
label2 = new Label();
label3 = new Label();
label4 = new Label();
textBoxFilePath = new TextBox();
buttonSelectFilePath = new Button();
buttonMakeReport = new Button();
SuspendLayout();
//
// dateTimePickerDateBegin
//
dateTimePickerDateBegin.Location = new Point(107, 143);
dateTimePickerDateBegin.Name = "dateTimePickerDateBegin";
dateTimePickerDateBegin.Size = new Size(200, 23);
dateTimePickerDateBegin.TabIndex = 0;
//
// dateTimePickerDateEnd
//
dateTimePickerDateEnd.Location = new Point(107, 185);
dateTimePickerDateEnd.Name = "dateTimePickerDateEnd";
dateTimePickerDateEnd.Size = new Size(200, 23);
dateTimePickerDateEnd.TabIndex = 1;
//
// comboBoxHotel
//
comboBoxHotel.FormattingEnabled = true;
comboBoxHotel.Location = new Point(107, 108);
comboBoxHotel.Name = "comboBoxHotel";
comboBoxHotel.Size = new Size(200, 23);
comboBoxHotel.TabIndex = 2;
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(8, 68);
label1.Name = "label1";
label1.Size = new Size(87, 15);
label1.TabIndex = 3;
label1.Text = "Путь до файла";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(9, 111);
label2.Name = "label2";
label2.Size = new Size(40, 15);
label2.TabIndex = 4;
label2.Text = "Отель";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(8, 149);
label3.Name = "label3";
label3.Size = new Size(74, 15);
label3.TabIndex = 5;
label3.Text = "Дата начала";
//
// label4
//
label4.AutoSize = true;
label4.Location = new Point(8, 191);
label4.Name = "label4";
label4.Size = new Size(68, 15);
label4.TabIndex = 6;
label4.Text = "Дата конца";
//
// textBoxFilePath
//
textBoxFilePath.Location = new Point(107, 65);
textBoxFilePath.Name = "textBoxFilePath";
textBoxFilePath.Size = new Size(200, 23);
textBoxFilePath.TabIndex = 7;
//
// buttonSelectFilePath
//
buttonSelectFilePath.Location = new Point(323, 64);
buttonSelectFilePath.Name = "buttonSelectFilePath";
buttonSelectFilePath.Size = new Size(25, 23);
buttonSelectFilePath.TabIndex = 8;
buttonSelectFilePath.Text = ". .";
buttonSelectFilePath.UseVisualStyleBackColor = true;
buttonSelectFilePath.Click += buttonSelectFilePath_Click;
//
// buttonMakeReport
//
buttonMakeReport.Location = new Point(107, 292);
buttonMakeReport.Name = "buttonMakeReport";
buttonMakeReport.Size = new Size(128, 26);
buttonMakeReport.TabIndex = 9;
buttonMakeReport.Text = "сформировать";
buttonMakeReport.UseVisualStyleBackColor = true;
buttonMakeReport.Click += buttonMakeReport_Click;
//
// FormRoomReport
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(374, 330);
Controls.Add(buttonMakeReport);
Controls.Add(buttonSelectFilePath);
Controls.Add(textBoxFilePath);
Controls.Add(label4);
Controls.Add(label3);
Controls.Add(label2);
Controls.Add(label1);
Controls.Add(comboBoxHotel);
Controls.Add(dateTimePickerDateEnd);
Controls.Add(dateTimePickerDateBegin);
Name = "FormRoomReport";
StartPosition = FormStartPosition.CenterParent;
Text = "FormRoomReport";
ResumeLayout(false);
PerformLayout();
}
#endregion
private DateTimePicker dateTimePickerDateBegin;
private DateTimePicker dateTimePickerDateEnd;
private ComboBox comboBoxHotel;
private Label label1;
private Label label2;
private Label label3;
private Label label4;
private TextBox textBoxFilePath;
private Button buttonSelectFilePath;
private Button buttonMakeReport;
}
}

View File

@ -0,0 +1,80 @@
using ProjectHotel.Reports;
using ProjectHotel.Repositories;
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 Unity;
namespace ProjectHotel.Forms;
public partial class FormHotelReport : Form
{
private readonly IUnityContainer _container;
public FormHotelReport(IUnityContainer container, IHotelRepository hotelRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
comboBoxHotel.DataSource = hotelRepository.ReadHotels();
comboBoxHotel.DisplayMember = "Name";
comboBoxHotel.ValueMember = "Id";
}
private void buttonSelectFilePath_Click(object sender, EventArgs e)
{
var sfd = new SaveFileDialog()
{
Filter = "Excel Files | *.xlsx"
};
if (sfd.ShowDialog() != DialogResult.OK)
{
return;
}
textBoxFilePath.Text = sfd.FileName;
}
private void buttonMakeReport_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxFilePath.Text))
{
throw new Exception("Отсутствует имя файла для отчета");
}
if (comboBoxHotel.SelectedIndex < 0)
{
throw new Exception("Не выбран отель");
}
if (dateTimePickerDateEnd.Value <=
dateTimePickerDateBegin.Value)
{
throw new Exception("Дата начала должна быть раньше даты окончания");
}
if
(_container.Resolve<TableReport>().CreateTable(textBoxFilePath.Text,
(int)comboBoxHotel.SelectedValue!,
dateTimePickerDateBegin.Value, dateTimePickerDateEnd.Value))
{
MessageBox.Show("Документ сформирован",
"Формирование документа",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Возникли ошибки при формировании документа.Подробности в логах", "Формирование документа",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при создании очета",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

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

View File

@ -0,0 +1,126 @@
namespace ProjectHotel.Forms
{
partial class FormHotels
{
/// <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()
{
panel1 = new Panel();
buttonDelete = new Button();
buttonChange = new Button();
buttonAdd = new Button();
dataGridViewData = new DataGridView();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
SuspendLayout();
//
// panel1
//
panel1.Controls.Add(buttonDelete);
panel1.Controls.Add(buttonChange);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(632, 0);
panel1.Name = "panel1";
panel1.Size = new Size(168, 450);
panel1.TabIndex = 0;
//
// buttonDelete
//
buttonDelete.BackgroundImage = Properties.Resources.ImageDelete;
buttonDelete.BackgroundImageLayout = ImageLayout.Zoom;
buttonDelete.Location = new Point(24, 308);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(130, 130);
buttonDelete.TabIndex = 2;
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonChange
//
buttonChange.BackgroundImage = Properties.Resources.ImageChange;
buttonChange.BackgroundImageLayout = ImageLayout.Zoom;
buttonChange.Location = new Point(24, 158);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(130, 130);
buttonChange.TabIndex = 1;
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ButtonChange_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.AddImage;
buttonAdd.BackgroundImageLayout = ImageLayout.Zoom;
buttonAdd.Location = new Point(24, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(130, 130);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
dataGridViewData.AllowUserToDeleteRows = false;
dataGridViewData.AllowUserToResizeColumns = false;
dataGridViewData.AllowUserToResizeRows = false;
dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(632, 450);
dataGridViewData.TabIndex = 1;
//
// FormHotels
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
Name = "FormHotels";
StartPosition = FormStartPosition.CenterParent;
Text = "Гостиницы";
Load += FormHotels_Load;
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
ResumeLayout(false);
}
#endregion
private Panel panel1;
private Button buttonAdd;
private Button buttonDelete;
private Button buttonChange;
private DataGridView dataGridViewData;
}
}

View File

@ -0,0 +1,111 @@
using ProjectHotel.Repositories;
using ProjectHotel.Repositories.Implementations;
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 Unity;
namespace ProjectHotel.Forms;
public partial class FormHotels : Form
{
private readonly IUnityContainer _container;
private readonly IHotelRepository _hotelRepository;
public FormHotels(IUnityContainer container, IHotelRepository hotelRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_hotelRepository = hotelRepository ??
throw new ArgumentNullException(nameof(hotelRepository));
}
private void FormHotels_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormHotel>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonChange_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormHotel>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_hotelRepository.DeleteHotel(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource = _hotelRepository.ReadHotels();
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewData.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewData.SelectedRows[0].Cells["Id"].Value);
return true;
}
}

View File

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

View File

@ -0,0 +1,166 @@
namespace ProjectHotel.Forms
{
partial class FormPlacingAthlete
{
/// <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()
{
DataGridViewCellStyle dataGridViewCellStyle1 = new DataGridViewCellStyle();
label1 = new Label();
label2 = new Label();
buttonCancel = new Button();
buttonSave = new Button();
comboBoxRoom = new ComboBox();
groupBox1 = new GroupBox();
dataGridView = new DataGridView();
ColumnLengthOfStay = new DataGridViewTextBoxColumn();
ColumnAthlete = new DataGridViewComboBoxColumn();
groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit();
SuspendLayout();
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(58, 35);
label1.Name = "label1";
label1.Size = new Size(54, 15);
label1.TabIndex = 0;
label1.Text = "Комната";
//
// label2
//
label2.AutoSize = true;
label2.Location = new Point(58, 90);
label2.Name = "label2";
label2.Size = new Size(156, 15);
label2.TabIndex = 1;
label2.Text = "Длительность проживания";
//
// buttonCancel
//
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Location = new Point(304, 479);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 5;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
buttonSave.Location = new Point(111, 479);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 4;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// comboBoxRoom
//
comboBoxRoom.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxRoom.FormattingEnabled = true;
comboBoxRoom.Location = new Point(118, 32);
comboBoxRoom.Name = "comboBoxRoom";
comboBoxRoom.Size = new Size(382, 23);
comboBoxRoom.TabIndex = 6;
//
// groupBox1
//
groupBox1.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
groupBox1.Controls.Add(dataGridView);
groupBox1.Location = new Point(12, 130);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(491, 329);
groupBox1.TabIndex = 7;
groupBox1.TabStop = false;
groupBox1.Text = "Спортсмены";
//
// dataGridView
//
dataGridView.AllowUserToResizeColumns = false;
dataGridView.AllowUserToResizeRows = false;
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView.Columns.AddRange(new DataGridViewColumn[] { ColumnAthlete, ColumnLengthOfStay });
dataGridView.Dock = DockStyle.Fill;
dataGridView.Location = new Point(3, 19);
dataGridView.MultiSelect = false;
dataGridView.Name = "dataGridView";
dataGridView.RowHeadersVisible = false;
dataGridViewCellStyle1.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView.RowsDefaultCellStyle = dataGridViewCellStyle1;
dataGridView.Size = new Size(485, 307);
dataGridView.TabIndex = 0;
//
// ColumnLengthOfStay
//
ColumnLengthOfStay.HeaderText = "Длительность проживания";
ColumnLengthOfStay.Name = "ColumnLengthOfStay";
//
// ColumnAthlete
//
ColumnAthlete.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
ColumnAthlete.HeaderText = "Спортсмен";
ColumnAthlete.Name = "ColumnAthlete";
//
// FormPlacingAthlete
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(515, 534);
Controls.Add(groupBox1);
Controls.Add(comboBoxRoom);
Controls.Add(buttonCancel);
Controls.Add(buttonSave);
Controls.Add(label2);
Controls.Add(label1);
Name = "FormPlacingAthlete";
StartPosition = FormStartPosition.CenterParent;
Text = "Размещение спортсмена";
groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private Label label1;
private Label label2;
private Label label3;
private Button buttonCancel;
private Button buttonSave;
private ComboBox comboBoxRoom;
private GroupBox groupBox1;
private DataGridView dataGridView;
private DataGridViewComboBoxColumn ColumnAthlete;
private DataGridViewTextBoxColumn ColumnLengthOfStay;
}
}

View File

@ -0,0 +1,72 @@
using ProjectHotel.Entities;
using ProjectHotel.Repositories;
using ProjectHotel.Repositories.Implementations;
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 ProjectHotel.Forms;
public partial class FormPlacingAthlete : Form
{
private readonly IPlacingAthleteRepository _placingAthleteRepository;
public FormPlacingAthlete(IPlacingAthleteRepository placingAthleteRepository,
IRoomRepository roomRepository,
IAthleteRepository athleteRepository)
{
InitializeComponent();
_placingAthleteRepository = placingAthleteRepository ??
throw new ArgumentNullException(nameof(placingAthleteRepository));
comboBoxRoom.DataSource = roomRepository.ReadRooms();
comboBoxRoom.DisplayMember = "Name";
comboBoxRoom.ValueMember = "Id";
ColumnAthlete.DataSource = athleteRepository.ReadAthletes();
ColumnAthlete.DisplayMember = "FirstName";
ColumnAthlete.ValueMember = "Id";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (dataGridView.RowCount < 1 ||
comboBoxRoom.SelectedIndex < 0)
{
throw new Exception("Имеются незаполненные поля");
}
_placingAthleteRepository.CreatePlacingAthlete(PlacingAthlete.CreateOpeartion(0,(int)comboBoxRoom.SelectedValue!,
CreateListAthletePlacingAthleteFromDataGrid()));
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private List<AthletePlacingAthlete> CreateListAthletePlacingAthleteFromDataGrid()
{
var list = new List<AthletePlacingAthlete>();
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Cells["ColumnAthlete"].Value == null ||
row.Cells["ColumnLengthOfStay"].Value == null)
{
continue;
}
list.Add(AthletePlacingAthlete.CreateElement(0,
Convert.ToInt32(row.Cells["ColumnAthlete"].Value),
Convert.ToInt32(row.Cells["ColumnLengthOfStay"].Value)));
}
return list;
}
}

View File

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

View File

@ -0,0 +1,112 @@
namespace ProjectHotel.Forms
{
partial class FormPlacingAthletes
{
/// <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()
{
dataGridViewData = new DataGridView();
panel1 = new Panel();
buttonDelete = new Button();
buttonAdd = new Button();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
panel1.SuspendLayout();
SuspendLayout();
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
dataGridViewData.AllowUserToDeleteRows = false;
dataGridViewData.AllowUserToResizeColumns = false;
dataGridViewData.AllowUserToResizeRows = false;
dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(632, 450);
dataGridViewData.TabIndex = 3;
//
// panel1
//
panel1.Controls.Add(buttonDelete);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(632, 0);
panel1.Name = "panel1";
panel1.Size = new Size(168, 450);
panel1.TabIndex = 2;
//
// buttonDelete
//
buttonDelete.BackgroundImage = Properties.Resources.ImageDelete;
buttonDelete.BackgroundImageLayout = ImageLayout.Zoom;
buttonDelete.Location = new Point(26, 248);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(130, 130);
buttonDelete.TabIndex = 2;
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.AddImage;
buttonAdd.BackgroundImageLayout = ImageLayout.Zoom;
buttonAdd.Location = new Point(24, 51);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(130, 130);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// FormPlacingAthletes
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
Name = "FormPlacingAthletes";
StartPosition = FormStartPosition.CenterParent;
Text = "FormPlacingAthletes";
Load += FormPlacingAthletes_Load;
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
panel1.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private DataGridView dataGridViewData;
private Panel panel1;
private Button buttonDelete;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,89 @@
using ProjectHotel.Repositories;
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 Unity;
namespace ProjectHotel.Forms;
public partial class FormPlacingAthletes : Form
{
private readonly IUnityContainer _container;
private readonly IPlacingAthleteRepository _placingAthleteRepository;
public FormPlacingAthletes(IUnityContainer container, IPlacingAthleteRepository placingAthleteRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_placingAthleteRepository = placingAthleteRepository ??
throw new ArgumentNullException(nameof(placingAthleteRepository));
}
private void FormPlacingAthletes_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormPlacingAthlete>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление",
MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_placingAthleteRepository.DeletePlacingAthlete(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource =
_placingAthleteRepository.ReadPlacingAthlete();
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewData.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewData.SelectedRows[0].Cells["Id"].Value);
return true;
}
}

View File

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

View File

@ -0,0 +1,95 @@
namespace ProjectHotel.Forms
{
partial class FormPlacingRoomDistribution
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
buttonSelectFileName = new Button();
dateTimePicker = new DateTimePicker();
buttonCreate = new Button();
labelFileName = new Label();
SuspendLayout();
//
// buttonSelectFileName
//
buttonSelectFileName.Location = new Point(12, 31);
buttonSelectFileName.Name = "buttonSelectFileName";
buttonSelectFileName.Size = new Size(71, 23);
buttonSelectFileName.TabIndex = 0;
buttonSelectFileName.Text = "Выбрать ";
buttonSelectFileName.UseVisualStyleBackColor = true;
buttonSelectFileName.Click += buttonSelectFileName_Click;
//
// dateTimePicker
//
dateTimePicker.Location = new Point(75, 90);
dateTimePicker.Name = "dateTimePicker";
dateTimePicker.Size = new Size(200, 23);
dateTimePicker.TabIndex = 2;
//
// buttonCreate
//
buttonCreate.Location = new Point(75, 130);
buttonCreate.Name = "buttonCreate";
buttonCreate.Size = new Size(200, 62);
buttonCreate.TabIndex = 3;
buttonCreate.Text = "Сформировать";
buttonCreate.UseVisualStyleBackColor = true;
buttonCreate.Click += buttonCreate_Click;
//
// labelFileName
//
labelFileName.AutoSize = true;
labelFileName.Location = new Point(89, 35);
labelFileName.Name = "labelFileName";
labelFileName.Size = new Size(36, 15);
labelFileName.TabIndex = 4;
labelFileName.Text = "Файл";
//
// FormPlacingRoomDistribution
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(329, 217);
Controls.Add(labelFileName);
Controls.Add(buttonCreate);
Controls.Add(dateTimePicker);
Controls.Add(buttonSelectFileName);
Name = "FormPlacingRoomDistribution";
Text = "FormPlacingRoomDistribution";
ResumeLayout(false);
PerformLayout();
}
#endregion
private Button buttonSelectFileName;
private DateTimePicker dateTimePicker;
private Button buttonCreate;
private Label labelFileName;
}
}

View File

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

View File

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

View File

@ -0,0 +1,150 @@
namespace ProjectHotel.Forms
{
partial class FormRoom
{
/// <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();
hotelBindingSource = new BindingSource(components);
labelHotelName = new Label();
labelCapacity = new Label();
labelRoomName = new Label();
numericUpDownCapacity = new NumericUpDown();
textBoxRoomName = new TextBox();
buttonCancel = new Button();
buttonSave = new Button();
comboBoxHotel = new ComboBox();
((System.ComponentModel.ISupportInitialize)hotelBindingSource).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDownCapacity).BeginInit();
SuspendLayout();
//
// labelHotelName
//
labelHotelName.AutoSize = true;
labelHotelName.Location = new Point(31, 55);
labelHotelName.Name = "labelHotelName";
labelHotelName.Size = new Size(93, 15);
labelHotelName.TabIndex = 0;
labelHotelName.Text = "Название отеля";
//
// labelCapacity
//
labelCapacity.AutoSize = true;
labelCapacity.Location = new Point(31, 109);
labelCapacity.Name = "labelCapacity";
labelCapacity.Size = new Size(80, 15);
labelCapacity.TabIndex = 1;
labelCapacity.Text = "Вместимость";
//
// labelRoomName
//
labelRoomName.AutoSize = true;
labelRoomName.Location = new Point(31, 168);
labelRoomName.Name = "labelRoomName";
labelRoomName.Size = new Size(97, 15);
labelRoomName.TabIndex = 2;
labelRoomName.Text = "Номер комнаты";
//
// numericUpDownCapacity
//
numericUpDownCapacity.Location = new Point(153, 109);
numericUpDownCapacity.Minimum = new decimal(new int[] { 1, 0, 0, 0 });
numericUpDownCapacity.Name = "numericUpDownCapacity";
numericUpDownCapacity.Size = new Size(55, 23);
numericUpDownCapacity.TabIndex = 3;
numericUpDownCapacity.Value = new decimal(new int[] { 1, 0, 0, 0 });
//
// textBoxRoomName
//
textBoxRoomName.Location = new Point(153, 160);
textBoxRoomName.Name = "textBoxRoomName";
textBoxRoomName.Size = new Size(185, 23);
textBoxRoomName.TabIndex = 5;
//
// buttonCancel
//
buttonCancel.Location = new Point(263, 251);
buttonCancel.Name = "buttonCancel";
buttonCancel.Size = new Size(75, 23);
buttonCancel.TabIndex = 7;
buttonCancel.Text = "Отмена";
buttonCancel.UseVisualStyleBackColor = true;
buttonCancel.Click += ButtonCancel_Click;
//
// buttonSave
//
buttonSave.Location = new Point(73, 251);
buttonSave.Name = "buttonSave";
buttonSave.Size = new Size(75, 23);
buttonSave.TabIndex = 8;
buttonSave.Text = "Сохранить";
buttonSave.UseVisualStyleBackColor = true;
buttonSave.Click += ButtonSave_Click;
//
// comboBoxHotel
//
comboBoxHotel.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxHotel.FormattingEnabled = true;
comboBoxHotel.Location = new Point(153, 47);
comboBoxHotel.Name = "comboBoxHotel";
comboBoxHotel.Size = new Size(197, 23);
comboBoxHotel.TabIndex = 9;
//
// FormRoom
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(419, 309);
Controls.Add(comboBoxHotel);
Controls.Add(buttonSave);
Controls.Add(buttonCancel);
Controls.Add(textBoxRoomName);
Controls.Add(numericUpDownCapacity);
Controls.Add(labelRoomName);
Controls.Add(labelCapacity);
Controls.Add(labelHotelName);
Name = "FormRoom";
StartPosition = FormStartPosition.CenterParent;
Text = "Комната";
((System.ComponentModel.ISupportInitialize)hotelBindingSource).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDownCapacity).EndInit();
ResumeLayout(false);
PerformLayout();
}
#endregion
private BindingSource hotelBindingSource;
private Label labelHotelName;
private Label labelCapacity;
private Label labelRoomName;
private NumericUpDown numericUpDownCapacity;
private TextBox textBoxRoomName;
private Button buttonCancel;
private Button buttonSave;
private ComboBox comboBoxHotel;
}
}

View File

@ -0,0 +1,86 @@
using ProjectHotel.Entities;
using ProjectHotel.Repositories;
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 ProjectHotel.Forms
{
public partial class FormRoom : Form
{
private readonly IRoomRepository _roomRepository;
private int? _roomId;
public int Id
{
set
{
try
{
var room = _roomRepository.ReadRoomById(value);
if (room == null || comboBoxHotel.SelectedIndex < 0)
{
throw new
InvalidDataException(nameof(room));
}
textBoxRoomName.Text = room.Name;
numericUpDownCapacity.Value = room.Capacity;
_roomId = value;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при получении данных", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
public FormRoom(IRoomRepository roomRepository, IHotelRepository hotelRepository)
{
InitializeComponent();
_roomRepository = roomRepository ??
throw new ArgumentNullException(nameof(roomRepository));
comboBoxHotel.DataSource = hotelRepository.ReadHotels();
comboBoxHotel.DisplayMember = "Name";
comboBoxHotel.ValueMember = "Id";
}
private void ButtonSave_Click(object sender, EventArgs e)
{
try
{
if (string.IsNullOrWhiteSpace(textBoxRoomName.Text))
{
throw new Exception("Имеются незаполненные поля");
}
if (_roomId.HasValue)
{
_roomRepository.UpdateRoom(CreateRoom(_roomId.Value));
}
else
{
_roomRepository.CreateRoom(CreateRoom(0));
}
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonCancel_Click(object sender, EventArgs e) => Close();
private Room CreateRoom(int id) => Room.CreateEntity(id, (int)comboBoxHotel.SelectedValue!, textBoxRoomName.Text, Convert.ToInt32(numericUpDownCapacity.Value));
}
}

View File

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

View File

@ -0,0 +1,126 @@
namespace ProjectHotel.Forms
{
partial class FormRooms
{
/// <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()
{
dataGridViewData = new DataGridView();
panel1 = new Panel();
buttonDelete = new Button();
buttonChange = new Button();
buttonAdd = new Button();
((System.ComponentModel.ISupportInitialize)dataGridViewData).BeginInit();
panel1.SuspendLayout();
SuspendLayout();
//
// dataGridViewData
//
dataGridViewData.AllowUserToAddRows = false;
dataGridViewData.AllowUserToDeleteRows = false;
dataGridViewData.AllowUserToResizeColumns = false;
dataGridViewData.AllowUserToResizeRows = false;
dataGridViewData.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridViewData.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridViewData.Dock = DockStyle.Fill;
dataGridViewData.Location = new Point(0, 0);
dataGridViewData.MultiSelect = false;
dataGridViewData.Name = "dataGridViewData";
dataGridViewData.ReadOnly = true;
dataGridViewData.RowHeadersVisible = false;
dataGridViewData.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridViewData.Size = new Size(632, 450);
dataGridViewData.TabIndex = 3;
//
// panel1
//
panel1.Controls.Add(buttonDelete);
panel1.Controls.Add(buttonChange);
panel1.Controls.Add(buttonAdd);
panel1.Dock = DockStyle.Right;
panel1.Location = new Point(632, 0);
panel1.Name = "panel1";
panel1.Size = new Size(168, 450);
panel1.TabIndex = 2;
//
// buttonDelete
//
buttonDelete.BackgroundImage = Properties.Resources.ImageDelete;
buttonDelete.BackgroundImageLayout = ImageLayout.Zoom;
buttonDelete.Location = new Point(24, 308);
buttonDelete.Name = "buttonDelete";
buttonDelete.Size = new Size(130, 130);
buttonDelete.TabIndex = 2;
buttonDelete.UseVisualStyleBackColor = true;
buttonDelete.Click += ButtonDelete_Click;
//
// buttonChange
//
buttonChange.BackgroundImage = Properties.Resources.ImageChange;
buttonChange.BackgroundImageLayout = ImageLayout.Zoom;
buttonChange.Location = new Point(24, 158);
buttonChange.Name = "buttonChange";
buttonChange.Size = new Size(130, 130);
buttonChange.TabIndex = 1;
buttonChange.UseVisualStyleBackColor = true;
buttonChange.Click += ButtonChange_Click;
//
// buttonAdd
//
buttonAdd.BackgroundImage = Properties.Resources.AddImage;
buttonAdd.BackgroundImageLayout = ImageLayout.Zoom;
buttonAdd.Location = new Point(24, 12);
buttonAdd.Name = "buttonAdd";
buttonAdd.Size = new Size(130, 130);
buttonAdd.TabIndex = 0;
buttonAdd.UseVisualStyleBackColor = true;
buttonAdd.Click += ButtonAdd_Click;
//
// FormRooms
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(dataGridViewData);
Controls.Add(panel1);
Name = "FormRooms";
StartPosition = FormStartPosition.CenterParent;
Text = "FormRooms";
Load += FormRooms_Load;
((System.ComponentModel.ISupportInitialize)dataGridViewData).EndInit();
panel1.ResumeLayout(false);
ResumeLayout(false);
}
#endregion
private DataGridView dataGridViewData;
private Panel panel1;
private Button buttonDelete;
private Button buttonChange;
private Button buttonAdd;
}
}

View File

@ -0,0 +1,112 @@
using ProjectHotel.Repositories;
using ProjectHotel.Repositories.Implementations;
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 Unity;
namespace ProjectHotel.Forms;
public partial class FormRooms : Form
{
private readonly IUnityContainer _container;
private readonly IRoomRepository _roomRepository;
public FormRooms(IUnityContainer container, IRoomRepository roomRepository)
{
InitializeComponent();
_container = container ??
throw new ArgumentNullException(nameof(container));
_roomRepository = roomRepository ??
throw new ArgumentNullException(nameof(roomRepository));
}
private void FormRooms_Load(object sender, EventArgs e)
{
try
{
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при загрузке",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonAdd_Click(object sender, EventArgs e)
{
try
{
_container.Resolve<FormRoom>().ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при добавлении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonChange_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
try
{
var form = _container.Resolve<FormRoom>();
form.Id = findId;
form.ShowDialog();
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при изменении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonDelete_Click(object sender, EventArgs e)
{
if (!TryGetIdentifierFromSelectedRow(out var findId))
{
return;
}
if (MessageBox.Show("Удалить запись?", "Удаление", MessageBoxButtons.YesNo) != DialogResult.Yes)
{
return;
}
try
{
_roomRepository.DeleteRoom(findId);
LoadList();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка при удалении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void LoadList() => dataGridViewData.DataSource = _roomRepository.ReadRooms();
private bool TryGetIdentifierFromSelectedRow(out int id)
{
id = 0;
if (dataGridViewData.SelectedRows.Count < 1)
{
MessageBox.Show("Нет выбранной записи", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
id = Convert.ToInt32(dataGridViewData.SelectedRows[0].Cells["Id"].Value);
return true;
}
}

View File

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

View File

@ -1,3 +1,12 @@
using Unity.Lifetime;
using Unity;
using ProjectHotel.Repositories;
using ProjectHotel.Repositories.Implementations;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Serilog;
using Unity.Microsoft.Logging;
namespace ProjectHotel namespace ProjectHotel
{ {
internal static class Program internal static class Program
@ -11,7 +20,32 @@ namespace ProjectHotel
// To customize application configuration such as set high DPI settings or default font, // To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new Form1()); Application.Run(CreateContainer().Resolve<FormHotelForAthletes>());
}
private static IUnityContainer CreateContainer()
{
var container = new UnityContainer();
container.AddExtension(new LoggingExtension(CreateLoggerFactory()));
container.RegisterType <IConnectionString, ConnectionString> (new SingletonLifetimeManager());
container.RegisterType<IAthleteRepository, AthleteRepository>(new TransientLifetimeManager());
container.RegisterType<ICleaningRoomRepository, CleaningRoomRepository>(new TransientLifetimeManager());
container.RegisterType<IHotelRepository, HotelRepository>(new TransientLifetimeManager());
container.RegisterType<IPlacingAthleteRepository, PlacingAthleteRepository>(new TransientLifetimeManager());
container.RegisterType<IRoomRepository, RoomRepository>(new TransientLifetimeManager());
return container;
}
private static LoggerFactory CreateLoggerFactory()
{
var loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build())
.CreateLogger());
return loggerFactory;
} }
} }
} }

View File

@ -2,10 +2,49 @@
<PropertyGroup> <PropertyGroup>
<OutputType>WinExe</OutputType> <OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework> <TargetFramework>net8.0-windows</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms> <UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.35" />
<PackageReference Include="DocumentFormat.OpenXml" Version="3.2.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql" Version="9.0.1" />
<PackageReference Include="PDFsharp-MigraDoc-GDI" Version="6.1.1" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.9.0" />
<PackageReference Include="Unity" Version="5.11.10" />
<PackageReference Include="Unity.Microsoft.Logging" Version="5.11.1" />
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
This file is automatically generated by Visual Studio. It is
used to store generic object data source configuration information.
Renaming the file extension or editing the content of this file may
cause the file to be unrecognizable by the program.
-->
<GenericObjectDataSource DisplayName="Hotel" Version="1.0" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
<TypeInfo>ProjectHotel.Entities.Hotel, ProjectHotel, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null</TypeInfo>
</GenericObjectDataSource>

View File

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

View File

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

View File

@ -0,0 +1,52 @@
using Microsoft.Extensions.Logging;
using ProjectHotel.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Reports;
internal class ChartReport
{
private readonly IPlacingAthleteRepository _placingAthleteRepository;
private readonly ILogger<ChartReport> _logger;
public ChartReport(IPlacingAthleteRepository placingAthleteRepository,
ILogger<ChartReport> logger)
{
_placingAthleteRepository = placingAthleteRepository ??
throw new
ArgumentNullException(nameof(placingAthleteRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateChart(string filePath, DateTime dateTime)
{
try
{
new PdfBuilder(filePath)
.AddHeader("Расселение спортсменов")
.AddPieChart("Комнаты", GetData(dateTime))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<(string Caption, double Value)> GetData(DateTime dateTime)
{
return _placingAthleteRepository
.ReadPlacingAthlete()
.Where(x => x.PlacingDate.Date == dateTime.Date)
.GroupBy(x => x.RoomId, (key, group) => new {
Id = key,
Count = group.Sum(x => x.AthletePlacingAthletes.Count())
})
.Select(x => (x.Id.ToString(), (double)x.Count))
.ToList();
}
}

View File

@ -0,0 +1,83 @@
using Microsoft.Extensions.Logging;
using ProjectHotel.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Reports;
internal class DocReport
{
private readonly IAthleteRepository _athleteRepository;
private readonly IRoomRepository _roomRepository;
private readonly IHotelRepository _hotelRepository;
private readonly ILogger<DocReport> _logger;
public DocReport(IAthleteRepository athleteRepository, IRoomRepository roomRepository, IHotelRepository hotelRepository, ILogger<DocReport> logger)
{
_athleteRepository = athleteRepository ?? throw new ArgumentNullException(nameof(athleteRepository));
_roomRepository = roomRepository ?? throw new ArgumentNullException(nameof(roomRepository));
_hotelRepository = hotelRepository ?? throw new ArgumentNullException(nameof(hotelRepository));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public bool CreateDoc(string filePath, bool includeAthletes, bool includeRooms, bool includeHotels)
{
try
{
var builder = new WordBuilder(filePath)
.AddHeader("Документ со справочниками");
if (includeAthletes)
{
builder.AddParagraph("Спортсмены")
.AddTable([2400, 2400, 2400, 1200, 1200],
GetAthletes());
}
if (includeRooms)
{
builder.AddParagraph("Комнаты")
.AddTable([2400, 2400, 2400], GetRooms());
}
if (includeHotels)
{
builder.AddParagraph("Гостиницы")
.AddTable([2400, 2400], GetHotels());
}
builder.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetAthletes()
{
return [
["Имя", "Фамилия", "Отчество", "Вид/Виды спорта", "Разряд"],
.. _athleteRepository.ReadAthletes().Select(x => new string[] { x.FirstName,
x.LastName,x.FatherName, x.Sport.ToString(), x.AthleteClass.ToString() }),
];
}
private List<string[]> GetRooms()
{
return [
["Отель", "Номер", "Вместимость"],
.. _roomRepository
.ReadRooms()
.Select(x => new string[] { x.HotelId.ToString(), x.Name,
x.Capacity.ToString() }),
];
}
private List<string[]> GetHotels()
{
return [
["Название", "Адрес"],
.. _hotelRepository
.ReadHotels()
.Select(x => new string[] { x.Name,
x.Address}),
];
}
}

View File

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

View File

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

View File

@ -0,0 +1,108 @@
using Microsoft.Extensions.Logging;
using ProjectHotel.Repositories;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Reports;
internal class TableReport
{
private readonly IPlacingAthleteRepository _placingAthleteRepository;
private readonly IRoomRepository _roomRepository;
private readonly ILogger<TableReport> _logger;
internal static readonly string[] item = ["Комната", "Дата", "Заселено", "Выселено"];
public TableReport(IPlacingAthleteRepository placingAthleteRepository, IRoomRepository roomRepository, ILogger<TableReport> logger)
{
_placingAthleteRepository = placingAthleteRepository ?? throw new ArgumentNullException(nameof(placingAthleteRepository));
_roomRepository = roomRepository ?? throw new ArgumentNullException(nameof(roomRepository));
_logger = logger ??
throw new ArgumentNullException(nameof(logger));
}
public bool CreateTable(string filePath, int hotelId, DateTime startDate, DateTime endDate)
{
try
{
new ExcelBuilder(filePath)
.AddHeader("Сводка о количестве жильцов в отеле", 0, 4)
.AddParagraph("за период", 0)
.AddTable([10, 10, 15, 15], GetData(hotelId, startDate, endDate))
.Build();
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при формировании документа");
return false;
}
}
private List<string[]> GetData(int hotelId, DateTime startDate, DateTime endDate)
{
var rooms = _roomRepository.ReadRooms().Where(r => r.HotelId == hotelId).ToList();
var placingAthletes = _placingAthleteRepository.ReadPlacingAthlete().ToList();
var athletePlacements = placingAthletes
.SelectMany(pa => pa.AthletePlacingAthletes, (pa, apa) => new
{
PlacingAthleteId = pa.Id,
RoomId = pa.RoomId,
PlacingDate = pa.PlacingDate.Date,
LengthOfStay = apa.LengthOfStay,
CheckoutDate = pa.PlacingDate.AddDays(apa.LengthOfStay).Date
})
.Where(ap => rooms.Any(r => r.Id == ap.RoomId))
.ToList();
var placementSummary = athletePlacements
.Where(ap => ap.PlacingDate >= startDate.Date && ap.PlacingDate <= endDate.Date)
.GroupBy(ap => new { ap.RoomId, ap.PlacingDate })
.Select(g => new
{
RoomId = g.Key.RoomId,
Date = g.Key.PlacingDate,
CheckedIn = (int?)g.Count(),
CheckedOut = (int?)null
})
.Union(
athletePlacements
.Where(ap => ap.CheckoutDate >= startDate.Date && ap.CheckoutDate <= endDate.Date)
.GroupBy(ap => new { ap.RoomId, ap.CheckoutDate })
.Select(g => new
{
RoomId = g.Key.RoomId,
Date = g.Key.CheckoutDate,
CheckedIn = (int?)null,
CheckedOut = (int?)g.Count()
})
)
.ToList();
var result = placementSummary
.GroupBy(ps => new { ps.RoomId, ps.Date })
.Select(g => new
{
RoomId = g.Key.RoomId,
Date = g.Key.Date,
CheckedIn = g.Sum(ps => ps.CheckedIn),
CheckedOut = g.Sum(ps => ps.CheckedOut)
}).OrderBy(r => r.Date)
.ThenBy(r => r.RoomId)
.ToList();
return new List<string[]>()
.Union(result.Select(x => new string[] {
x.RoomId.ToString(),
x.Date.ToString("yyyy-MM-dd"),
x.CheckedIn?.ToString() ?? string.Empty,
x.CheckedOut?.ToString() ?? string.Empty
}))
.Union(new List<string[]> { new string[] { "Всего", "", result.Sum(x => x.CheckedIn).ToString() ?? "0", result.Sum(x => x.CheckedOut).ToString() ?? "0" } })
.ToList();
}
}

View File

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

View File

@ -0,0 +1,17 @@
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Repositories;
public interface IAthleteRepository
{
IEnumerable<Athlete> ReadAthletes();
Athlete ReadAthleteById(int id);
void CreateAthlete(Athlete athlete);
void UpdateAthlete(Athlete athlete);
void DeleteAthlete(int id);
}

View File

@ -0,0 +1,16 @@
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Repositories;
public interface ICleaningRoomRepository
{
IEnumerable<CleaningRoom> ReadCleaningRooms(int? id = null, int? roomId = null);
void CreateCleaningRoom(CleaningRoom cleaningRoom);
CleaningRoom ReadCleaningRoomById(int id);
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Repositories;
public interface IConnectionString
{
string ConnectionString { get; }
}

View File

@ -0,0 +1,17 @@
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Repositories;
public interface IHotelRepository
{
IEnumerable<Hotel> ReadHotels();
Hotel ReadHotelById(int id);
void CreateHotel(Hotel hotel);
void UpdateHotel(Hotel hotel);
void DeleteHotel(int id);
}

View File

@ -0,0 +1,15 @@
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Repositories;
public interface IPlacingAthleteRepository
{
IEnumerable<PlacingAthlete> ReadPlacingAthlete(int? roomId = null, DateTime ? placing = null);
void CreatePlacingAthlete(PlacingAthlete placingAthlete);
void DeletePlacingAthlete(int id);
}

View File

@ -0,0 +1,18 @@
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Repositories;
public interface IRoomRepository
{
IEnumerable<Room> ReadRooms();
Room ReadRoomById(int id);
void CreateRoom(Room room);
void UpdateRoom(Room room);
void DeleteRoom(int id);
}

View File

@ -0,0 +1,128 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace ProjectHotel.Repositories.Implementations;
public class AthleteRepository : IAthleteRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<AthleteRepository> _logger;
public AthleteRepository(IConnectionString connectionString, ILogger<AthleteRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreateAthlete(Athlete athlete)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(athlete));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryInsert = @"
INSERT INTO Athletes (FirstName, LastName, FatherName, Sport, AthleteClass)
VALUES (@FirstName, @LastName, @FatherName, @Sport, @AthleteClass)";
connection.Execute(queryInsert, athlete);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeleteAthlete(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM Athletes
WHERE Id = @id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public Athlete ReadAthleteById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Athletes WHERE Id = @Id;
";
var athlete = connection.QueryFirst<Athlete>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(athlete));
return athlete;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public IEnumerable<Athlete> ReadAthletes()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @"SELECT * FROM Athletes";
var athletes = connection.Query<Athlete>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(athletes));
return athletes;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении всех объектов");
throw;
}
}
public void UpdateAthlete(Athlete athlete)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(athlete));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Athletes
SET FirstName = @FirstName, LastName = @LastName, FatherName = @FatherName, @Sport = Sport, @AthleteClass = AthleteClass
WHERE Id = @Id;
";
connection.Execute(queryUpdate, athlete);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
}

View File

@ -0,0 +1,84 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Repositories.Implementations;
internal class CleaningRoomRepository : ICleaningRoomRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<CleaningRoomRepository> _logger;
public CleaningRoomRepository(IConnectionString connectionString, ILogger<CleaningRoomRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<CleaningRoom> ReadCleaningRooms(int? id = null, int? roomId = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @"SELECT * FROM CleaningRoom";
var cleaningRoom = connection.Query<CleaningRoom>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(cleaningRoom));
return cleaningRoom;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении всех объектов");
throw;
}
}
public void CreateCleaningRoom(CleaningRoom cleaningRoom)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(cleaningRoom));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryInsert = @"
INSERT INTO CleaningRoom (RoomId, CleaningDate)
VALUES (@RoomId, @CleaningDate);
";
connection.Execute(queryInsert, cleaningRoom);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public CleaningRoom ReadCleaningRoomById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM CleaningRoom WHERE Id = @Id;
";
var cleaningRoom = connection.QueryFirst<CleaningRoom>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(cleaningRoom));
return cleaningRoom;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Repositories.Implementations
{
public class ConnectionString : IConnectionString
{
string IConnectionString.ConnectionString => "Host=127.0.0.1;Port=5432;Username=postgres;Password=postgres;Database=otp";
}
}

View File

@ -0,0 +1,127 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Repositories.Implementations;
internal class HotelRepository : IHotelRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<HotelRepository> _logger;
public HotelRepository(IConnectionString connectionString, ILogger<HotelRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Hotel> ReadHotels()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @"SELECT * FROM Hotels";
var hotel = connection.Query<Hotel>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(hotel));
return hotel;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении всех объектов");
throw;
}
}
public Hotel ReadHotelById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Hotels WHERE Id = @Id;
";
var hotel = connection.QueryFirst<Hotel>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(hotel));
return hotel;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void CreateHotel(Hotel hotel)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(hotel));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryInsert = @"
INSERT INTO Hotels (Name, Address)
VALUES (@Name, @Address)";
connection.Execute(queryInsert, hotel);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateHotel(Hotel hotel)
{
_logger.LogInformation("Редактирование объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(hotel));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryUpdate = @"
UPDATE Hotels
SET Name = @Name, Address = @Address
WHERE Id = @Id;
";
connection.Execute(queryUpdate, hotel);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при редактировании объекта");
throw;
}
}
public void DeleteHotel(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM Hotels
WHERE Id = @id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
}

View File

@ -0,0 +1,108 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Repositories.Implementations;
internal class PlacingAthleteRepository : IPlacingAthleteRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<PlacingAthleteRepository> _logger;
public PlacingAthleteRepository(IConnectionString connectionString, ILogger<PlacingAthleteRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public void CreatePlacingAthlete(PlacingAthlete placingAthlete)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(placingAthlete));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
var queryInsert = @"
INSERT INTO PlacingAthlete (RoomId, PlacingDate)
VALUES (@RoomId, @PlacingDate);
SELECT MAX(Id) FROM PlacingAthlete;
";
var placingAthleteId = connection.QueryFirst<int>(queryInsert, placingAthlete, transaction);
var querySubInsert = @"
INSERT INTO AthletePlacingAthlete (AthleteId, PlacingAthleteId, LengthOfStay)
VALUES (@AthleteId, @PlacingAthleteId, @LengthOfStay);
";
foreach (var elem in placingAthlete.AthletePlacingAthletes)
{
connection.Execute(querySubInsert, new { elem.AthleteId, placingAthleteId , elem.LengthOfStay }, transaction);
}
transaction.Commit();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void DeletePlacingAthlete(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var queryDelete = @"
DELETE FROM PlacingAthlete
WHERE Id = @id
";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
public IEnumerable<PlacingAthlete> ReadPlacingAthlete(int? roomId = null, DateTime? placing = null)
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"SELECT pa.*,apa.*
FROM PlacingAthlete pa
INNER JOIN AthletePlacingAthlete apa ON apa.PlacingAthleteId = pa.Id
";
var placingAthletes = connection.Query<TempAthletePlacingAthlete>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(placingAthletes));
return placingAthletes.GroupBy(x => x.Id, y => y, (key, value) =>
PlacingAthlete.CreateOpeartion(value.First(), value.Select(z =>
AthletePlacingAthlete.CreateElement(0, z.AthleteId, z.LengthOfStay)))).ToList();
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
}

View File

@ -0,0 +1,110 @@
using Dapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Npgsql;
using ProjectHotel.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectHotel.Repositories.Implementations
{
internal class RoomRepository : IRoomRepository
{
private readonly IConnectionString _connectionString;
private readonly ILogger<RoomRepository> _logger;
public RoomRepository(IConnectionString connectionString, ILogger<RoomRepository> logger)
{
_connectionString = connectionString;
_logger = logger;
}
public IEnumerable<Room> ReadRooms()
{
_logger.LogInformation("Получение всех объектов");
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var querySelect = @"SELECT * FROM Rooms";
var rooms = connection.Query<Room>(querySelect);
_logger.LogDebug("Полученные объекты: {json}", JsonConvert.SerializeObject(rooms));
return rooms;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при получении всех объектов");
throw;
}
}
public Room ReadRoomById(int id)
{
_logger.LogInformation("Получение объекта по идентификатору");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
var querySelect = @"
SELECT * FROM Rooms WHERE Id = @Id;
";
var room = connection.QueryFirst<Room>(querySelect, new { id });
_logger.LogDebug("Найденный объект: {json}", JsonConvert.SerializeObject(room));
return room;
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при поиске объекта");
throw;
}
}
public void CreateRoom(Room rooms)
{
_logger.LogInformation("Добавление объекта");
_logger.LogDebug("Объект: {json}", JsonConvert.SerializeObject(rooms));
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryInsert = @"
INSERT INTO Rooms (HotelId, Name,Capacity)
VALUES (@HotelId, @Name, @Capacity)";
connection.Execute(queryInsert, rooms);
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при добавлении объекта");
throw;
}
}
public void UpdateRoom(Room rooms)
{
}
public void DeleteRoom(int id)
{
_logger.LogInformation("Удаление объекта");
_logger.LogDebug("Объект: {id}", id);
try
{
using var connection = new NpgsqlConnection(_connectionString.ConnectionString);
connection.Open();
var queryDelete = @"
DELETE FROM Rooms
WHERE Id = @id";
connection.Execute(queryDelete, new { id });
}
catch (Exception ex)
{
_logger.LogError(ex, "Ошибка при удалении объекта");
throw;
}
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

View File

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

BIN
lab2.vpp Normal file

Binary file not shown.

BIN
lab2.vpp.bak_000f Normal file

Binary file not shown.