1 Commits

Author SHA1 Message Date
79ea49873b удалены лишние 2024-05-12 02:46:45 +04:00
12 changed files with 91 additions and 273 deletions

View File

@@ -1,5 +1,4 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
@@ -96,18 +95,9 @@ public abstract class AbstractCompany
SetObjectsPosition();
for (int i = 0; i < (_collection?.Count ?? 0); ++i)
{
try
{
{
DrawningMilitaryAircraft? obj = _collection?.Get(i);
obj?.DrawTransport(graphics);
}
catch (ObjectNotFoundException e)
{ }
catch (PositionOutOfCollectionException e)
{ }
catch (CollectionOverflowException e)
{ }
}
return bitmap;

View File

@@ -1,5 +1,4 @@
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
@@ -43,13 +42,11 @@ public class Angar : AbstractCompany
for (int i = 0; i < (_collection?.Count ?? 0); i++)
{
try
if (_collection.Get(i) != null)
{
_collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight);
_collection.Get(i).SetPosition(_placeSizeWidth * curWidth + 10, curHeight * _placeSizeHeight + 10);
}
catch (ObjectNotFoundException) { }
catch (PositionOutOfCollectionException e) { }
if (curWidth > 0)
curWidth--;
@@ -58,7 +55,7 @@ public class Angar : AbstractCompany
curWidth = width - 1;
curHeight--;
}
if (curHeight >= height)
if (curHeight > height)
{
return;
}

View File

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

View File

@@ -1,6 +1,4 @@
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter.CollectionGenericObjects;
namespace ProjectAirFighter.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
@@ -50,69 +48,65 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public T? Get(int position)
{
if (position < 0 || position >= Count - 3) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
if (position >= _collection.Length || position < 0)
{ return null; }
return _collection[position];
}
public int Insert(T obj)
{
for (int i = 0; i < Count - 3; i++)
int index = 0;
while (index < _collection.Length)
{
if (_collection[i] == null)
if (_collection[index] == null)
{
_collection[i] = obj;
return i;
_collection[index] = obj;
return index;
}
index++;
}
throw new CollectionOverflowException(Count);
return -1;
}
public int Insert(T obj, int position)
{
if (position < 0 || position >= Count - 3) throw new PositionOutOfCollectionException(position);
if (position >= _collection.Length || position < 0)
{ return -1; }
if (_collection[position] != null)
if (_collection[position] == null)
{
bool pushed = false;
for (int index = position + 1; index < Count; index++)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
_collection[position] = obj;
return position;
}
int index;
if (!pushed)
for (index = position + 1; index < _collection.Length; ++index)
{
if (_collection[index] == null)
{
for (int index = position - 1; index >= 0; index--)
{
if (_collection[index] == null)
{
position = index;
pushed = true;
break;
}
}
}
if (!pushed)
{
throw new CollectionOverflowException(Count);
_collection[position] = obj;
return position;
}
}
// вставка
_collection[position] = obj;
return position;
for (index = position - 1; index >= 0; --index)
{
if (_collection[index] == null)
{
_collection[position] = obj;
return position;
}
}
return -1;
}
public T? Remove(int position)
{
if (position >= Count - 3 || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) throw new ObjectNotFoundException(position);
if (position >= _collection.Length || position < 0)
{
return null;
}
T obj = _collection[position];
_collection[position] = null;
return obj;

View File

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

View File

@@ -1,20 +0,0 @@
using System.Runtime.Serialization;
namespace ProjectAirFighter.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
public 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

@@ -1,20 +0,0 @@
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

@@ -1,20 +0,0 @@
using System.Runtime.Serialization;
namespace ProjectAirFighter.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,7 +1,5 @@
using Microsoft.Extensions.Logging;
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.CollectionGenericObjects;
using ProjectAirFighter.Drawnings;
using ProjectAirFighter.Exceptions;
namespace ProjectAirFighter;
@@ -17,20 +15,13 @@ public partial class FormMilitaryAircraftCollection : Form
/// </summary>
private AbstractCompany? _company = null;
/// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormMilitaryAircraftCollection(ILogger<FormMilitaryAircraftCollection> logger)
public FormMilitaryAircraftCollection()
{
InitializeComponent();
_storageCollection = new();
_logger = logger;
_logger.LogInformation("Форма загрузилась");
}
/// <summary>
@@ -67,18 +58,14 @@ public partial class FormMilitaryAircraftCollection : Form
return;
}
try
if (_company + militaryAircraft != -1)
{
var res = _company + militaryAircraft;
MessageBox.Show("Объект добавлен");
_logger.LogInformation($"Объект добавлен под индексом {res}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
else
{
MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
MessageBox.Show("Не удалось добавить объект");
}
}
@@ -101,18 +88,14 @@ public partial class FormMilitaryAircraftCollection : Form
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
try
if (_company - pos != null)
{
var res = _company - pos;
MessageBox.Show("Объект удален");
_logger.LogInformation($"Объект удален под индексом {pos}");
pictureBox.Image = _company.Show();
}
catch (Exception ex)
else
{
MessageBox.Show(ex.Message, "Не удалось удалить объект",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
MessageBox.Show("Не удалось удалить объект");
}
}
@@ -185,17 +168,8 @@ public partial class FormMilitaryAircraftCollection : Form
collectionType = CollectionType.List;
}
try
{
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
_logger.LogInformation("Добавление коллекции");
RerfreshListBoxItems();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError($"Ошибка: {ex.Message}", ex.Message);
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
private void buttonCollectionDel_Click(object sender, EventArgs e)
@@ -210,7 +184,6 @@ public partial class FormMilitaryAircraftCollection : Form
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
_logger.LogInformation("Коллекция удалена");
RerfreshListBoxItems();
}
@@ -247,7 +220,6 @@ public partial class FormMilitaryAircraftCollection : Form
{
case "Хранилище":
_company = new Angar(pictureBox.Width, pictureBox.Height, collection);
_logger.LogInformation("Компания создана");
break;
}
@@ -259,16 +231,13 @@ public partial class FormMilitaryAircraftCollection : Form
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
_storageCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName);
}
catch (Exception ex)
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
@@ -277,17 +246,14 @@ public partial class FormMilitaryAircraftCollection : Form
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
if (_storageCollection.LoadData(openFileDialog.FileName))
{
_storageCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch (Exception ex)
else
{
MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

View File

@@ -1,50 +1,17 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace ProjectAirFighter;
internal static class Program
namespace ProjectAirFighter
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
internal static class Program
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
var services = new ServiceCollection();
ConfigureServices(services);
using ServiceProvider serviceProvider = services.BuildServiceProvider();
Application.Run(serviceProvider.GetRequiredService <FormMilitaryAircraftCollection>());
}
/// <summary>
/// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> DI
/// </summary>
/// <param name="services"></param>
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMilitaryAircraftCollection>().AddLogging(option =>
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
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}serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMilitaryAircraftCollection());
}
}
}

View File

@@ -8,16 +8,6 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.AspNetCore" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

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