This commit is contained in:
BoiledMilk123 2024-05-20 21:12:31 +04:00
parent f00e0c5a8c
commit 48eac5dc3a
16 changed files with 356 additions and 61 deletions

View File

@ -97,8 +97,15 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
DrawningLocomotive? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
try
{
DrawningLocomotive? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch(Exception)
{
continue;
}
}
return bitmap;
}

View File

@ -1,4 +1,5 @@
using System;
using ProjectElectricLocomotive.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -48,17 +49,21 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// проверка позиции
if (position >= Count || position < 0)
try
{
return null;
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
catch (IndexOutOfRangeException)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
public int Insert(T obj)
{
if (Count == _maxCount) return -1;
if (Count == _maxCount) throw new CollectionOwerflowException(Count);
_collection.Add(obj);
return Count;
}
@ -69,14 +74,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
// проверка позиции
// вставка по позиции
if (position >= Count || position < 0)
{
return -1;
}
if (Count == _maxCount)
{
return -1;
}
if (position > MaxCount) throw new CollectionOwerflowException(position);
if (obj == null) throw new ArgumentNullException(nameof(obj));
_collection.Insert(position, obj);
return position;
@ -86,10 +87,16 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
// проверка позиции
// удаление объекта из списка
if (position >= Count || position < 0) return null;
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
try
{
T obj = _collection[position];
_collection.RemoveAt(position);
return obj;
}
catch (IndexOutOfRangeException)
{
throw new PositionOutOfCollectionException(position);
}
}

View File

@ -47,17 +47,20 @@ public class LocomotiveDepot : AbstractCompany
{
for (int i = 0; i < (_collection?.Count); i++)
{
if (_collection.Get(i) != null)
try
{
_collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight);
_collection?.Get(i)?.SetPosition(_placeSizeWidth * positionWidth + 25, positionHeight * _placeSizeHeight + 10);
}
catch(Exception)
{
}
if (positionWidth < width - 1)
{
positionWidth++;
}
else
{
positionWidth = 0;

View File

@ -1,4 +1,5 @@
using System;
using ProjectElectricLocomotive.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -55,11 +56,15 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
// проверка позиции
if (position >= Count || position < 0)
try
{
return null;
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
catch (IndexOutOfRangeException)
{
throw new PositionOutOfCollectionException(position);
}
return _collection[position];
}
public int Insert(T obj)
{
@ -72,7 +77,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return i;
}
}
return -1;
throw new CollectionOwerflowException(Count);
}
@ -112,7 +117,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
}
return -1;
throw new CollectionOwerflowException(Count);
}
public T? Remove(int position)
@ -120,10 +125,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
//// проверка позиции
//// удаление объекта из массива, присвоив элементу массива значение null
if (position >= Count || position < 0 || _collection[position] == null) return null;
T removedObject = _collection[position];
_collection[position] = null;
return removedObject;
try
{
T removedObject = _collection[position];
if (removedObject == null) throw new ObjectNotFoundException(position);
_collection[position] = null;
return removedObject;
}
catch (IndexOutOfRangeException)
{
throw new PositionOutOfCollectionException(position);
}
}
public IEnumerable<T> GetItems()

View File

@ -1,4 +1,5 @@
using ProjectElectricLocomotive.Drawnings;
using ProjectElectricLocomotive.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
@ -100,15 +101,14 @@ public class StorageCollection<T>
/// Сохранение информации по автомобилям в хранилице в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
if (_storages.Count == 0) return false;
if (_storages.Count == 0) throw new NoCollectionExpection("В хранилище отсутствуют коллекции для сохранения");
using (StreamWriter writer = new StreamWriter(filename))
{
@ -129,25 +129,27 @@ public class StorageCollection<T>
writer.WriteLine();
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename)) return false;
if (!File.Exists(filename)) throw new FileNotFoundException("Файл не существует");
using (StreamReader reader = new StreamReader(filename))
{
string line = reader.ReadLine();
if (line == null || !line.Equals(_collectionKey))
if (line == null)
{
return false;
throw new FileIsEmptyException("В файле нет данных");
}
if (!line.Equals(_collectionKey))
{
throw new FileHasWrongDataExpextion("В файле неверные данные");
}
_storages.Clear();
@ -166,7 +168,7 @@ public class StorageCollection<T>
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null) return false;
if (collection == null) throw new NullCollectionExpection("Не удалось создать коллекцию"); ;
collection.MaxCount = Convert.ToInt32(record[2]);
@ -176,9 +178,13 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningLocomotive() is T locomotive)
{
if (collection.Insert(locomotive) == -1)
try
{
return false;
collection.Insert(locomotive);
}
catch(Exception ex)
{
throw new CollectionOwerflowException("Коллекция переполнена", ex);
}
}
}
@ -187,8 +193,6 @@ public class StorageCollection<T>
line = reader.ReadLine();
}
}
return true;
}
/// <summary>

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions;
/// <summary>
/// Класс, описывающий переполнение коллекции
/// </summary>
[Serializable]
internal class CollectionOwerflowException : ApplicationException
{
public CollectionOwerflowException(int count) : base("В коллекции превышено допустимое количество: count " + count) { }
public CollectionOwerflowException() : base() { }
public CollectionOwerflowException(string message) : base(message) { }
public CollectionOwerflowException(string message, Exception exception) : base(message, exception) { }
public CollectionOwerflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions;
/// <summary>
/// Класс, описывающий переполнение коллекции
/// </summary>
[Serializable]
internal class FileHasWrongDataExpextion : ApplicationException
{
public FileHasWrongDataExpextion() : base() { }
public FileHasWrongDataExpextion(string message) : base("Файл имеет неверные данные: " + message) { }
public FileHasWrongDataExpextion(string message, Exception exception) : base(message, exception) { }
public FileHasWrongDataExpextion(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class FileIsEmptyException : ApplicationException
{
public FileIsEmptyException() : base() { }
public FileIsEmptyException(string message) : base("Файл пустой: " + message) { }
public FileIsEmptyException(string message, Exception exception) : base(message, exception) { }
public FileIsEmptyException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions;
[Serializable]
internal class NoCollectionExpection : ApplicationException
{
public NoCollectionExpection() : base() { }
public NoCollectionExpection(string message) : base(message) { }
public NoCollectionExpection(string message, Exception exception) : base(message, exception) { }
public NoCollectionExpection(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions;
[Serializable]
internal class NullCollectionExpection : ApplicationException
{
public NullCollectionExpection() : base() { }
public NullCollectionExpection(string message) : base(message) { }
public NullCollectionExpection(string message, Exception exception) : base(message, exception) { }
public NullCollectionExpection(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что по указанной позиции нет элемента
/// </summary>
[Serializable]
internal class ObjectNotFoundException : ApplicationException
{
public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { }
public ObjectNotFoundException() : base() { }
public ObjectNotFoundException(string message) : base(message) { }
public ObjectNotFoundException(string message, Exception exception) : base(message, exception) { }
public ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectElectricLocomotive.Exceptions;
/// <summary>
/// Класс, описывающий ошибку выхода за границу коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{
public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { }
public PositionOutOfCollectionException() : base() { }
public PositionOutOfCollectionException(string message) : base(message) { }
public PositionOutOfCollectionException(string message, Exception exception) : base(message, exception) { }
public PositionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -1,4 +1,5 @@
using ProjectElectricLocomotive.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectElectricLocomotive.CollectionGenericObjects;
using ProjectElectricLocomotive.Drawnings;
using System;
using System.Collections.Generic;
@ -25,13 +26,19 @@ public partial class FormLocomotiveCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormLocomotiveCollection()
public FormLocomotiveCollection(ILogger<FormLocomotiveCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
}
/// <summary>
@ -67,15 +74,23 @@ public partial class FormLocomotiveCollection : Form
return;
}
if (_company + locomotive != -1)
if (_company == null) return;
try
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if((_company + locomotive) != -1)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект: {entity}", locomotive.GetDataForSave());
pictureBox.Image = _company.Show();
}
}
else
catch(Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show("Объект не был добавлен");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -95,14 +110,17 @@ public partial class FormLocomotiveCollection : Form
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
DrawningLocomotive locomotive = _company - pos;
_logger.LogInformation("Объект по позиции {pos} удаден", pos);
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -178,6 +196,8 @@ public partial class FormLocomotiveCollection : Form
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RefreshListBoxItems();
_logger.LogInformation("Добавлена коллекция: {CollectionName} типа: {Type}", textBoxCollectionName.Text, collectionType);
}
/// <summary>
@ -197,6 +217,7 @@ public partial class FormLocomotiveCollection : Form
return;
}
if (MessageBox.Show("Вы хотите удалить коллекцию?", "Коллекция удалена", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) return;
_logger.LogInformation("Коллекция успешно удалена: {collectionName}", listBoxCollection.SelectedIndex.ToString());
_storageCollection.DelCollection(listBoxCollection.SelectedItem?.ToString() ?? string.Empty);
RefreshListBoxItems();
}
@ -233,14 +254,17 @@ public partial class FormLocomotiveCollection : Form
if (collection == null)
{
MessageBox.Show("Коллекция не проиннициализирована");
_logger.LogInformation("Коллекция не проиннициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new LocomotiveDepot(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Создана компания типа депо, коллекция: {CollectionName}", listBoxCollection.SelectedItem);
break;
}
_logger.LogInformation("Создана компания на коллекции : {CollectionName}", listBoxCollection.SelectedItem);
panelCompanyTools.Enabled = true;
RefreshListBoxItems();
}
@ -254,13 +278,16 @@ public partial class FormLocomotiveCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
try
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл {filename}", saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка {Message}", ex.Message);
}
}
}
@ -274,15 +301,18 @@ public partial class FormLocomotiveCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RefreshListBoxItems();
_logger.LogInformation("Загрузка прошла успешно из файла, {filename}", openFileDialog.FileName);
}
else
catch(Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка {Message}", ex.Message);
}
RefreshListBoxItems();
}
}
}

View File

@ -1,3 +1,12 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using Serilog.Sinks.File;
using Serilog.Configuration;
using Microsoft.Extensions.Configuration;
namespace ProjectElectricLocomotive
{
internal static class Program
@ -11,7 +20,27 @@ namespace ProjectElectricLocomotive
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormLocomotiveCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormLocomotiveCollection>());
}
private static void ConfigureServices(ServiceCollection services)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("Settings.json")
.Build();
services.AddSingleton<FormLocomotiveCollection>()
.AddLogging(builder =>
{
builder.AddSerilog(new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger());
});
}
}
}

View File

@ -8,6 +8,24 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Новая папка1\**" />
<EmbeddedResource Remove="Новая папка1\**" />
<None Remove="Новая папка1\**" />
</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.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
<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>
@ -23,4 +41,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="Settings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/locomotiveLog.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
]
}
}