ISE_22.Aparyan.Bulldozer.Base Lab07 #7

Closed
LuizaAparyan wants to merge 3 commits from Laba07 into Laba06
11 changed files with 225 additions and 57 deletions

View File

@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace ProjectBulldozer.Exceptions
{
[Serializable]
internal class BulldozerNotFoundException : ApplicationException
{
public BulldozerNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public BulldozerNotFoundException() : base() { }
public BulldozerNotFoundException(string message) : base(message) { }
public BulldozerNotFoundException(string message, Exception exception) : base(message, exception) { }
protected BulldozerNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -0,0 +1,17 @@
using System.Runtime.Serialization;
namespace ProjectBulldozer.Exceptions
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception Exception) : base(message, Exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
}

View File

@ -1,4 +1,6 @@
namespace ProjectBulldozer using System.ComponentModel;
namespace ProjectBulldozer
{ {
partial class FormTractorCollections partial class FormTractorCollections
{ {
@ -23,7 +25,7 @@
сохранитьToolStripMenuItem = new ToolStripMenuItem(); сохранитьToolStripMenuItem = new ToolStripMenuItem();
загрузитьToolStripMenuItem = new ToolStripMenuItem(); загрузитьToolStripMenuItem = new ToolStripMenuItem();
toolStripMenuItem1 = new ToolStripMenuItem(); toolStripMenuItem1 = new ToolStripMenuItem();
((System.ComponentModel.ISupportInitialize)pictureBoxCollections).BeginInit(); ((ISupportInitialize)pictureBoxCollections).BeginInit();
groupBox1.SuspendLayout(); groupBox1.SuspendLayout();
Instruments.SuspendLayout(); Instruments.SuspendLayout();
menuStrip1.SuspendLayout(); menuStrip1.SuspendLayout();
@ -34,7 +36,7 @@
maskedTextBoxNumber.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; maskedTextBoxNumber.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBoxNumber.Location = new Point(33, 356); maskedTextBoxNumber.Location = new Point(33, 356);
maskedTextBoxNumber.Margin = new Padding(3, 2, 3, 2); maskedTextBoxNumber.Margin = new Padding(3, 2, 3, 2);
maskedTextBoxNumber.Mask = "0"; maskedTextBoxNumber.Mask = "00";
maskedTextBoxNumber.Name = "maskedTextBoxNumber"; maskedTextBoxNumber.Name = "maskedTextBoxNumber";
maskedTextBoxNumber.Size = new Size(131, 23); maskedTextBoxNumber.Size = new Size(131, 23);
maskedTextBoxNumber.TabIndex = 4; maskedTextBoxNumber.TabIndex = 4;
@ -217,7 +219,7 @@
Margin = new Padding(3, 2, 3, 2); Margin = new Padding(3, 2, 3, 2);
Name = "FormTractorCollections"; Name = "FormTractorCollections";
Text = "Набор объектов"; Text = "Набор объектов";
((System.ComponentModel.ISupportInitialize)pictureBoxCollections).EndInit(); ((ISupportInitialize)pictureBoxCollections).EndInit();
groupBox1.ResumeLayout(false); groupBox1.ResumeLayout(false);
groupBox1.PerformLayout(); groupBox1.PerformLayout();
Instruments.ResumeLayout(false); Instruments.ResumeLayout(false);
@ -227,6 +229,22 @@
ResumeLayout(false); ResumeLayout(false);
PerformLayout(); PerformLayout();
} }
private void файлToolStripMenuItem_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
private void saveFileDialog_FileOk(object sender, CancelEventArgs e)
{
throw new NotImplementedException();
}
private void openFileDialog_FileOk(object sender, CancelEventArgs e)
{
throw new NotImplementedException();
}
private void pictureBoxCollections_Click(object sender, EventArgs e) private void pictureBoxCollections_Click(object sender, EventArgs e)
{ {
throw new NotImplementedException(); throw new NotImplementedException();

View File

@ -1,6 +1,10 @@
using Bulldozer; using Bulldozer;
using ProjectBulldozer.Generics; using ProjectBulldozer.Generics;
using ProjectBulldozer.Drawning; using ProjectBulldozer.Drawning;
using ProjectBulldozer.Exceptions;
using Microsoft.Extensions.Logging;
using System.ComponentModel;
using System.Xml.Linq;
namespace ProjectBulldozer namespace ProjectBulldozer
{ {
public partial class FormTractorCollections : Form public partial class FormTractorCollections : Form
@ -8,11 +12,20 @@ namespace ProjectBulldozer
private readonly TractorGenericStorage _storage; private readonly TractorGenericStorage _storage;
private readonly TractorGenericCollection<DrawingTractor, DrawingObjectTractor> _tractors; private readonly TractorGenericCollection<DrawingTractor, DrawingObjectTractor> _tractors;
readonly int countPlace = 10; readonly int countPlace = 10;
private readonly ILogger _logger;
public FormTractorCollections() public FormTractorCollections()
{ {
InitializeComponent(); InitializeComponent();
_storage = new TractorGenericStorage(pictureBoxCollections.Width, pictureBoxCollections.Height); _storage = new TractorGenericStorage(pictureBoxCollections.Width, pictureBoxCollections.Height);
} }
public FormTractorCollections(ILogger<FormTractorCollections> logger)
{
InitializeComponent();
_storage = new TractorGenericStorage(pictureBoxCollections.Width, pictureBoxCollections.Height);
_logger = logger;
}
private void ReloadObjects() private void ReloadObjects()
{ {
int index = listBoxStorage.SelectedIndex; int index = listBoxStorage.SelectedIndex;
@ -36,10 +49,12 @@ namespace ProjectBulldozer
if (string.IsNullOrEmpty(textBoxStorageName.Text)) if (string.IsNullOrEmpty(textBoxStorageName.Text))
{ {
MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Не всё заполнено", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"!!Ошибка!! Не все данные заполнены");
return; return;
} }
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
} }
private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e) private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e)
{ {
@ -49,13 +64,16 @@ namespace ProjectBulldozer
{ {
if (listBoxStorage.SelectedIndex == -1) if (listBoxStorage.SelectedIndex == -1)
{ {
_logger.LogWarning($"Удаление не выбранного набора");
return; return;
} }
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorage.SelectedItem.ToString() ?? string.Empty); _storage.DelSet(listBoxStorage.SelectedItem.ToString() ?? string.Empty);
ReloadObjects(); ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
} }
} }
private void ButtonAddTractor_Click(object sender, EventArgs e) private void ButtonAddTractor_Click(object sender, EventArgs e)
@ -81,22 +99,30 @@ namespace ProjectBulldozer
tractor._pictureHeight = pictureBoxCollections.Height; tractor._pictureHeight = pictureBoxCollections.Height;
if (listBoxStorage.SelectedIndex == -1) return; if (listBoxStorage.SelectedIndex == -1) return;
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty]; var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
if (obj == null) if (obj == null)
{ {
return; return;
} }
int addedIndex = obj + tractor; try
if (addedIndex != -1 && addedIndex < countPlace) {
if (obj + tractor)
{ {
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
pictureBoxCollections.Image = obj.ShowTractors(); pictureBoxCollections.Image = obj.ShowTractors();
_logger.LogInformation($"В набор {name} добавлен объект");
} }
else else
{ {
MessageBox.Show("Не удалось добавить объект"); MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message}. Не удалось добавить объект");
} }
} }
private void ButtonRemoveTractor_Click(object sender, EventArgs e) private void ButtonRemoveTractor_Click(object sender, EventArgs e)
@ -111,17 +137,30 @@ namespace ProjectBulldozer
{ {
return; return;
} }
if (maskedTextBoxNumber.Text == "") { return; }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
try
{
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
if (obj - pos != null) if (obj - pos != null)
{ {
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
pictureBoxCollections.Image = obj.ShowTractors(); pictureBoxCollections.Image = obj.ShowTractors();
_logger.LogInformation($"Из набора {name} удален объект");
} }
else else
{ {
MessageBox.Show("Не удалось удалить объект"); MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Не удалось удалить объект");
} }
} }
catch (BulldozerNotFoundException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message}. Не удалось удалить объект");
}
}
private void ButtonRefreshCollection_Click(object sender, EventArgs e) private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{ {
if (listBoxStorage.SelectedIndex == -1) return; if (listBoxStorage.SelectedIndex == -1) return;
@ -136,15 +175,16 @@ namespace ProjectBulldozer
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
MessageBox.Show("Сохранение прошло успешно", _storage.SaveData(saveFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogWarning("Ошибка сохранения");
} }
} }
} }
@ -152,21 +192,21 @@ namespace ProjectBulldozer
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
MessageBox.Show("Загрузка прошло успешно", _storage.LoadData(openFileDialog.FileName);
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
ReloadObjects(); ReloadObjects();
MessageBox.Show("Загрузка произошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка загрузки");
}
} }
} }
} }
} }

View File

@ -18,9 +18,7 @@
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, 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="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name=" <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value> <value>[base64 mime encoded serialized .NET Framework object]</value>
</data> </data>
@ -119,4 +117,13 @@
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>153, 17</value>
</metadata>
<metadata name="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>286, 17</value>
</metadata>
</root> </root>

View File

@ -19,12 +19,9 @@ namespace ProjectBulldozer.Generics
_pictureHeight = picHeight; _pictureHeight = picHeight;
_collection = new SetGeneric<T>(width * height); _collection = new SetGeneric<T>(width * height);
} }
public static int operator +(TractorGenericCollection<T, U> collect, T? tract) public static bool operator +(TractorGenericCollection<T, U> collect, T? tract)
{ {
if (tract == null) if (tract == null) return false;
{
return -1;
}
return collect._collection.Insert(tract); return collect._collection.Insert(tract);
} }
public static T? operator -(TractorGenericCollection<T, U> collect, int pos) public static T? operator -(TractorGenericCollection<T, U> collect, int pos)

View File

@ -1,4 +1,5 @@
namespace ProjectBulldozer.Generics using ProjectBulldozer.Exceptions;
namespace ProjectBulldozer.Generics
{ {
internal class SetGeneric<T> where T : class internal class SetGeneric<T> where T : class
{ {
@ -12,24 +13,35 @@
_places = new List<T?>(count); _places = new List<T?>(count);
} }
/// Добавление объекта в набор /// Добавление объекта в набор
public int Insert(T tract) public bool Insert(T tract)
{ {
return Insert(tract, 0); return Insert(tract, 0);
} }
public int Insert(T tract, int position) public bool Insert(T tract, int position)
{ {
if (position < 0 || position >= _maxCount) return -1; if (position < 0 || position >= _maxCount)
_places.Insert(position, tract); {
return position; throw new BulldozerNotFoundException(position);
} }
public T? Remove(int position) if (Count >= _maxCount)
{ {
if (position >= Count || position < 0) throw new StorageOverflowException(_maxCount);
return null; }
_places.Insert(position, tract);
T? tmp = _places[position]; return true;
}
public bool Remove(int position)
{
if (position < 0 || position >= _maxCount)
{
return false;
}
if (_places[position] == null)
{
throw new BulldozerNotFoundException(position);
}
_places[position] = null; _places[position] = null;
return tmp; return true;
} }
public T? this[int position] public T? this[int position]
{ {

View File

@ -64,7 +64,7 @@ namespace ProjectBulldozer.Generics
} }
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new InvalidOperationException("Невалиданя операция, нет данных для сохранения");
} }
using StreamWriter sw = new(filename); using StreamWriter sw = new(filename);
sw.Write($"TractorsStorage{Environment.NewLine}{data}"); sw.Write($"TractorsStorage{Environment.NewLine}{data}");
@ -74,7 +74,7 @@ namespace ProjectBulldozer.Generics
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new FileNotFoundException("Файл не найден");
} }
using (StreamReader sr = File.OpenText(filename)) using (StreamReader sr = File.OpenText(filename))
{ {
@ -85,7 +85,7 @@ namespace ProjectBulldozer.Generics
} }
if (!str.StartsWith("TractorsStorage")) if (!str.StartsWith("TractorsStorage"))
{ {
return false; throw new FormatException("Неверный формат данных");
} }
_TractorsStorage.Clear(); _TractorsStorage.Clear();
@ -112,9 +112,9 @@ namespace ProjectBulldozer.Generics
_pictureWidth, _pictureHeight); _pictureWidth, _pictureHeight);
if (tractor != null) if (tractor != null)
{ {
if ((collection + tractor) == -1) if ((collection + tractor))
{ {
return false; throw new ApplicationException("Ошибка добавления в коллекцию");
} }
} }
} }

View File

@ -1,14 +1,40 @@
using ProjectBulldozer; using ProjectBulldozer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace Bulldozer namespace Bulldozer
{ {
internal static class Program internal static class Program
{ {
private static Serilog.ILogger? logger;
[STAThread] [STAThread]
static void Main() static void Main()
{ {
https://aka.ms/applicationconfiguration. // see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize(); ApplicationConfiguration.Initialize();
Application.Run(new FormTractorCollections()); var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormTractorCollections>());
}
}
private static void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<FormTractorCollections>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split('\\');
string appPath = "";
for (int i = 0; i < path.Length - 3; i++)
{
appPath += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().AddJsonFile($"{appPath}appsettings.json").Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
} }
} }
} }

View File

@ -8,6 +8,20 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.2.7" />
<PackageReference Include="NLog.Config" Version="4.7.15" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="NLog.Schema" Version="5.2.7" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.3.7" />
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<Compile Update="Properties\Resources.Designer.cs"> <Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime> <DesignTime>True</DesignTime>

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "logs/bulldozerlog-.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Bulldozer"
}
}
}