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)
{
T? obj = collect._collection[pos];
if (obj != null)
{
collect._collection.Remove(pos);
}
return obj;
}

View File

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

View File

@ -8,6 +8,25 @@
<ImplicitUsings>enable</ImplicitUsings>
</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>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -13,6 +13,10 @@ using System.Windows.Forms;
using DumpTruck.MovementStrategy;
using DumpTruck.DrawningObjects;
using DumpTruck.Generics;
using Microsoft.Extensions.Logging;
using DumpTruck.Exceptions;
using System.Xml.Linq;
using Serilog;
namespace DumpTruck
@ -70,22 +74,19 @@ pictureBoxCollection.Height);
form.Show();
Action<DrawningCar>? carDelegate = new((m) =>
{
int q = obj + m;
if (q != -1)
try
{
int q = obj + m;
MessageBox.Show("Объект добавлен");
Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}");
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);
@ -108,15 +109,23 @@ pictureBoxCollection.Height);
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
try
{
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
var q = obj - pos;
MessageBox.Show("Объект удален");
Log.Information($"Удален объект из коллекции {listBoxStorages.SelectedItem.ToString() ?? string.Empty} по номеру {pos}");
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);
ReloadObjects();
Log.Information($"Добавлен набор: {textBoxStorageName.Text}");
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
@ -170,9 +180,11 @@ pictureBoxCollection.Height);
if (MessageBox.Show($"Удалить объект { listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString()
?? string.Empty);
string name = listBoxStorages.SelectedItem.ToString()
?? string.Empty;
_storage.DelSet(name);
ReloadObjects();
Log.Information($"Удален набор: {name}");
}
}
@ -186,15 +198,18 @@ MessageBoxIcon.Question) == DialogResult.Yes)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning("Не удалось сохранить");
MessageBox.Show($"Не сохранилось: {ex.Message}",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@ -204,19 +219,22 @@ MessageBoxIcon.Question) == DialogResult.Yes)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
_storage.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
Log.Information($"Файл {openFileDialog.FileName} успешно загружен");
foreach (var collection in _storage.Keys)
{
listBoxStorages.Items.Add(collection);
}
ReloadObjects();
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Log.Warning("Не удалось загрузить");
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
{
internal static class Program
@ -8,9 +17,22 @@ namespace DumpTruck
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
ApplicationConfiguration.Initialize(); string[] path = Directory.GetCurrentDirectory().Split('\\');
string pathNeed = "";
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());
}
}

View File

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