первая часть

This commit is contained in:
ikswi 2024-05-02 09:16:58 +04:00
parent c3e7442abe
commit ea4be41558
10 changed files with 241 additions and 81 deletions

View File

@ -1,4 +1,7 @@
namespace ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Exceptions;
using ProjectSportCar.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@ -43,28 +46,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= Count || position < 0) return null;
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
return _collection[position];
}
public int Insert(T obj)
{
if (Count + 1 > _maxCount) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
{
if (Count + 1 > _maxCount) return -1;
if (position < 0 || position > Count) return -1;
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
return 1;
return position;
}
public T? Remove(int position)
{
if (position < 0 || position > Count) return null;
if (position < 0 || position > Count) throw new PositionOutOfCollectionException(position);
T? pos = _collection[position];
_collection.RemoveAt(position);
return pos;

View File

@ -1,4 +1,7 @@
namespace ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Exceptions;
using ProjectSportCar.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@ -48,8 +51,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position >= _collection.Length || position < 0)
{ return null; }
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
return _collection[position];
}
@ -66,13 +69,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
index++;
}
return -1;
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
{
if (position >= _collection.Length || position < 0)
{ return -1; }
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
@ -98,15 +100,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return position;
}
}
return -1;
throw new CollectionOverflowException(Count);
}
public T? Remove(int position)
{
if (position >= _collection.Length || position < 0)
{
return null;
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
T obj = _collection[position];
_collection[position] = null;
return obj;

View File

@ -1,4 +1,5 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
using System.Text;
namespace ProjectAirFighter.CollectionGenericObjects;
@ -93,13 +94,11 @@ public class StorageCollection<T>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранении данных</returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
@ -139,10 +138,7 @@ public class StorageCollection<T>
}
writer.Write(sb);
}
}
return true;
}
/// <summary>
@ -152,11 +148,11 @@ public class StorageCollection<T>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
//
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не существует");
}
using (StreamReader fs = File.OpenText(filename))
{
@ -164,12 +160,12 @@ public class StorageCollection<T>
if (str == null || str.Length == 0)
{
return false;
throw new Exception("В файле нет данных");
}
if (!str.StartsWith(_collectionKey))
{
return false;
throw new Exception("В файле неверные данные");
}
_storages.Clear();
@ -190,7 +186,7 @@ public class StorageCollection<T>
if (collection == null)
{
return false;
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
@ -201,15 +197,21 @@ public class StorageCollection<T>
{
if (elem?.CreateDrawningMilitaryAircraft() is T militaryAircraft)
{
if (collection.Insert(militaryAircraft) == -1)
try
{
return false;
if (collection.Insert(militaryAircraft) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new Exception("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
}
return true;
}
}

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectAirFighter.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class CollectionOverflowException : ApplicationException
{
public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество: " + count) { }
public CollectionOverflowException() : base() { }
public CollectionOverflowException(string message) : base(message) { }
public CollectionOverflowException(string message, Exception exception) : base(message, exception) { }
protected CollectionOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectAirFighter.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) { }
protected ObjectNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectSportCar.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) { }
protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -1,5 +1,8 @@
using ProjectAirFighter.CollectionGenericObjects;
using Microsoft.Extensions.Logging;
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar;
namespace ProjectAirFighter;
@ -15,13 +18,19 @@ public partial class FormMilitaryAircraftCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логгер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMilitaryAircraftCollection()
public FormMilitaryAircraftCollection(ILogger<FormMilitaryAircraftCollection> logger)
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@ -53,19 +62,25 @@ public partial class FormMilitaryAircraftCollection : Form
/// <param name="militaryAircraft"></param>
private void SetMilitaryAircraft(DrawningMilitaryAircraft? militaryAircraft)
{
if (_company == null || militaryAircraft == null)
try
{
return;
}
if (_company == null || militaryAircraft == null)
{
return;
}
if (_company + militaryAircraft != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
if (_company + militaryAircraft != -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _company.Show();
_logger.LogInformation("Добавлен объект: " + militaryAircraft.GetDataForSave());
}
}
else
catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -88,14 +103,19 @@ public partial class FormMilitaryAircraftCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_company - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
if (_company - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _company.Show();
_logger.LogInformation("Удален объект по позиции " + pos);
}
}
else
catch (Exception ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -113,26 +133,28 @@ public partial class FormMilitaryAircraftCollection : Form
DrawningMilitaryAircraft? militaryAircraft = null;
int counter = 100;
while (militaryAircraft == null)
try
{
militaryAircraft = _company.GetRandomObject();
counter--;
if (counter <= 0)
while (militaryAircraft == null)
{
break;
militaryAircraft = _company.GetRandomObject();
counter--;
if (counter <= 0)
{
break;
}
}
FormAirFighter Form = new()
{
SetAir = militaryAircraft
};
Form.ShowDialog();
}
catch (Exception ex)
if (militaryAircraft == null)
{
return;
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
FormAirFighter form = new()
{
SetAir = militaryAircraft
};
form.ShowDialog();
}
/// <summary>
@ -158,33 +180,50 @@ public partial class FormMilitaryAircraftCollection : Form
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
try
{
collectionType = CollectionType.Massive;
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
_logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text);
}
else if (radioButtonList.Checked)
catch (Exception ex)
{
collectionType = CollectionType.List;
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedItem == null)
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
try
{
return;
if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
private void RerfreshListBoxItems()
@ -236,13 +275,16 @@ public partial class FormMilitaryAircraftCollection : 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);
}
}
}
@ -256,14 +298,18 @@ public partial class FormMilitaryAircraftCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
try
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}

View File

@ -1,3 +1,8 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
namespace ProjectAirFighter
{
internal static class Program
@ -11,7 +16,25 @@ namespace ProjectAirFighter
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMilitaryAircraftCollection());
ServiceCollection services = new();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService<FormMilitaryAircraftCollection>());
}
/// <summary>
/// Êîíôèãóðàöèÿ ñåðâèñà DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMilitaryAircraftCollection>()
.AddLogging(option =>
{
option.SetMinimumLevel(LogLevel.Information);
option.AddNLog("nlog.config");
});
}
}
}

View File

@ -8,6 +8,11 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.10" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +28,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true" internalLogLevel="Info">
<targets>
<target xsi:type="File" name="tofile" fileName="carlog-${shortdate}.log" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="tofile" />
</rules>
</nlog>
</configuration>