This commit is contained in:
ValAnn 2023-12-16 14:39:38 +04:00
parent c2126b3c7e
commit 9244b7ecf0
9 changed files with 172 additions and 62 deletions

View File

@ -73,10 +73,7 @@ namespace DumpTruck.Generics
pos) pos)
{ {
T? obj = collect._collection[pos]; T? obj = collect._collection[pos];
if (obj != null) collect._collection.Remove(pos);
{
collect._collection.Remove(pos);
}
return obj; return obj;
} }

View File

@ -64,7 +64,7 @@ namespace DumpTruck.Generics
/// Удаление набора /// Удаление набора
/// </summary> /// </summary>
/// <param name="name">Название набора</param> /// <param name="name">Название набора</param>
public void DelSet(string name) public void DelSet(string name)
{ {
if (!_carStorages.ContainsKey(name)) if (!_carStorages.ContainsKey(name))
{ {
@ -90,7 +90,7 @@ namespace DumpTruck.Generics
} }
} }
public bool SaveData(string filename) public void SaveData(string filename)
{ {
if (File.Exists(filename)) if (File.Exists(filename))
{ {
@ -110,7 +110,7 @@ CarsGenericCollection<DrawningCar, DrawningObjectCar>> record in _carStorages)
if (data.Length == 0) if (data.Length == 0)
{ {
return false; throw new Exception("Невалиданя операция, нет данных для сохранения");
} }
string toWrite = $"CarStorage{Environment.NewLine}{data}"; string toWrite = $"CarStorage{Environment.NewLine}{data}";
var strs = toWrite.Split(new char[] { '\n', '\r' }, var strs = toWrite.Split(new char[] { '\n', '\r' },
@ -123,7 +123,7 @@ StringSplitOptions.RemoveEmptyEntries);
sw.WriteLine(str); sw.WriteLine(str);
} }
} }
return true; return;
} }
public bool LoadData(string filename) public bool LoadData(string filename)
@ -131,7 +131,7 @@ StringSplitOptions.RemoveEmptyEntries);
{ {
if (!File.Exists(filename)) if (!File.Exists(filename))
{ {
return false; throw new IOException("Файл не найден");
} }
using (StreamReader sr = new(filename)) using (StreamReader sr = new(filename))
{ {
@ -140,11 +140,11 @@ StringSplitOptions.RemoveEmptyEntries);
StringSplitOptions.RemoveEmptyEntries); StringSplitOptions.RemoveEmptyEntries);
if (strs == null || strs.Length == 0) if (strs == null || strs.Length == 0)
{ {
return false; throw new IOException("Нет данных для загрузки");
} }
if (!strs[0].StartsWith("CarStorage")) if (!strs[0].StartsWith("CarStorage"))
{ {
return false; throw new IOException("Неверный формат данных");
} }
_carStorages.Clear(); _carStorages.Clear();
do do
@ -177,6 +177,8 @@ StringSplitOptions.RemoveEmptyEntries);
} while (str != null); } while (str != null);
} }
return true; return true;
} }
} }

View File

@ -8,6 +8,25 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.5" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<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

@ -13,6 +13,10 @@ using System.Windows.Forms;
using DumpTruck.MovementStrategy; using DumpTruck.MovementStrategy;
using DumpTruck.DrawningObjects; using DumpTruck.DrawningObjects;
using DumpTruck.Generics; using DumpTruck.Generics;
using Microsoft.Extensions.Logging;
using DumpTruck.Exceptions;
using System.Xml.Linq;
using Serilog;
namespace DumpTruck namespace DumpTruck
@ -70,28 +74,25 @@ pictureBoxCollection.Height);
form.Show(); form.Show();
Action<DrawningCar>? carDelegate = new((m) => Action<DrawningCar>? carDelegate = new((m) =>
{ {
int q = obj + m; try
if (q != -1)
{ {
int q = obj + m;
MessageBox.Show("Объект добавлен"); MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
pictureBoxCollection.Image = obj.ShowCars(); pictureBoxCollection.Image = obj.ShowCars();
} }
else catch (StorageOverflowException ex)
{ {
MessageBox.Show("Не удалось добавить объект"); Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена");
MessageBox.Show(ex.Message);
} }
});
Action<Color>? ColorDelegate = new((m) =>
{
MessageBox.Show(m.ToString());
}); });
form.AddEvent(carDelegate); form.AddEvent(carDelegate);
} }
private void ButtonRemoveCar_Click(object sender, EventArgs e) private void ButtonRemoveCar_Click(object sender, EventArgs e)
{ {
if (listBoxStorages.SelectedIndex == -1) if (listBoxStorages.SelectedIndex == -1)
{ {
@ -108,15 +109,23 @@ pictureBoxCollection.Height);
{ {
return; return;
} }
int pos = Convert.ToInt32(maskedTextBoxNumber.Text); try
if (obj - pos != null)
{ {
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var q = obj - pos;
MessageBox.Show("Объект удален"); MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
pictureBoxCollection.Image = obj.ShowCars(); pictureBoxCollection.Image = obj.ShowCars();
} }
else catch (TruckNotFoundException ex)
{ {
MessageBox.Show("Не удалось удалить объект"); Log.Warning($"Не получилось удалить объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
MessageBox.Show(ex.Message);
}
catch (FormatException ex)
{
Log.Warning($"Было введено не число");
MessageBox.Show("Введите число");
} }
} }
@ -152,6 +161,7 @@ pictureBoxCollection.Height);
_storage.AddSet(textBoxStorageName.Text); _storage.AddSet(textBoxStorageName.Text);
ReloadObjects(); ReloadObjects();
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
} }
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e) private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
@ -170,9 +180,11 @@ pictureBoxCollection.Height);
if (MessageBox.Show($"Удалить объект { listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, if (MessageBox.Show($"Удалить объект { listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes) MessageBoxIcon.Question) == DialogResult.Yes)
{ {
_storage.DelSet(listBoxStorages.SelectedItem.ToString() string name = listBoxStorages.SelectedItem.ToString()
?? string.Empty); ?? string.Empty;
_storage.DelSet(name);
ReloadObjects(); ReloadObjects();
Log.Information($"Удален набор: {name}");
} }
} }
@ -186,15 +198,18 @@ MessageBoxIcon.Question) == DialogResult.Yes)
{ {
if (saveFileDialog.ShowDialog() == DialogResult.OK) if (saveFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.SaveData(saveFileDialog.FileName)) try
{ {
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не сохранилось", "Результат", Log.Warning("Не удалось сохранить");
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }
@ -204,19 +219,22 @@ MessageBoxIcon.Question) == DialogResult.Yes)
{ {
if (openFileDialog.ShowDialog() == DialogResult.OK) if (openFileDialog.ShowDialog() == DialogResult.OK)
{ {
if (_storage.LoadData(openFileDialog.FileName)) try
{ {
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys) foreach (var collection in _storage.Keys)
{ {
listBoxStorages.Items.Add(collection); listBoxStorages.Items.Add(collection);
} }
ReloadObjects();
} }
else catch (Exception ex)
{ {
MessageBox.Show("Не загрузилось", "Результат", Log.Warning("Не удалось загрузить");
MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
} }
} }

View File

@ -1,3 +1,12 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Json;
using Serilog.Configuration;
namespace DumpTruck namespace DumpTruck
{ {
internal static class Program internal static class Program
@ -8,9 +17,22 @@ namespace DumpTruck
[STAThread] [STAThread]
static void Main() static void Main()
{ {
// To customize application configuration such as set high DPI settings or default font, ApplicationConfiguration.Initialize(); string[] path = Directory.GetCurrentDirectory().Split('\\');
// see https://aka.ms/applicationconfiguration. string pathNeed = "";
ApplicationConfiguration.Initialize(); for (int i = 0; i < path.Length - 3; i++)
{
pathNeed += path[i] + "\\";
}
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: $"{pathNeed}debug.json", optional: false, reloadOnChange: true)
.Build();
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormCarCollection()); Application.Run(new FormCarCollection());
} }
} }

View File

@ -4,6 +4,8 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles; using System.Windows.Forms.VisualStyles;
using DumpTruck.Exceptions;
using System;
namespace DumpTruck.Generics namespace DumpTruck.Generics
{ {
@ -40,9 +42,10 @@ namespace DumpTruck.Generics
public int Insert(T car) public int Insert(T car)
{ {
if (_places.Count == countMax) { return -1; } if (_places.Count == countMax) { throw new StorageOverflowException(countMax); }
return Insert(car, 0); Insert(car, 0);
return 1;
} }
/// <summary> /// <summary>
/// Добавление объекта в набор на конкретную позицию /// Добавление объекта в набор на конкретную позицию
@ -53,21 +56,13 @@ namespace DumpTruck.Generics
public int Insert(T car, int position) public int Insert(T car, int position)
{ {
if (!(position >= 0 && position <= Count && _places.Count < countMax)) if (_places.Count == countMax)
{ throw new StorageOverflowException(countMax);
return -1; if (!(position >= 0 && position <= Count)) return -1;
}
_places.Insert(position, car); _places.Insert(position, car);
return position; return position;
} }
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// проверка, что после вставляемого элемента в массиве есть пустой элемент
// сдвиг всех объектов, находящихся справа от позиции до первого пустого элемента
// TODO вставка по позиции
/// <summary> /// <summary>
/// Удаление объекта из набора с конкретной позиции /// Удаление объекта из набора с конкретной позиции
/// </summary> /// </summary>
@ -75,14 +70,10 @@ namespace DumpTruck.Generics
/// <returns></returns> /// <returns></returns>
public bool Remove(int position) public bool Remove(int position)
{ {
if (position < Count && position >= 0) if (!(position >= 0 && position < Count))
{ throw new TruckNotFoundException(position);
_places[position] = null; _places.RemoveAt(position);
return true; return true;
}
return false;
} }
/// <summary> /// <summary>
@ -92,16 +83,18 @@ namespace DumpTruck.Generics
/// <returns></returns> /// <returns></returns>
public T? this[int position] public T? this[int position]
{ {
get { get
if (!(position >= 0 && position <= Count)) {
if (!(position >= 0 && position < Count))
return null; return null;
return _places[position]; return _places[position];
} }
set set
{ {
if (!(position >= 0 && position <= Count)) if (!(position >= 0 && position < Count && _places.Count < countMax))
return; return;
_places.Insert(position, value); _places.Insert(position, value);
return;
} }
} }
/// <summary> /// <summary>

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace DumpTruck.Exceptions
{
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 contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace DumpTruck.Exceptions
{
internal class TruckNotFoundException : ApplicationException
{
public TruckNotFoundException(int i) : base($"Не найден объект попозиции {i}") { }
public TruckNotFoundException() : base() { }
public TruckNotFoundException(string message) : base(message) { }
public TruckNotFoundException(string message, Exception exception) :
base(message, exception)
{ }
protected TruckNotFoundException(SerializationInfo info,
StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,15 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "log.txt" }
}
],
"Properties": {
"Application": "Sample"
}
}
}