думаю это самая завершенная лаба 7
This commit is contained in:
parent
3264a8ed5d
commit
90437759da
@ -8,6 +8,16 @@
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" 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.7" />
|
||||
<PackageReference Include="Serilog" Version="3.1.1" />
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Update="Properties\Resources.Designer.cs">
|
||||
<DesignTime>True</DesignTime>
|
||||
|
22
AircraftCarrier/AircraftCarrier/AircraftNotFoundException.cs
Normal file
22
AircraftCarrier/AircraftCarrier/AircraftNotFoundException.cs
Normal file
@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Runtime.Serialization;
|
||||
|
||||
namespace AircraftCarrier.Exceptions
|
||||
{
|
||||
[Serializable]
|
||||
internal class AircraftNotFoundException : ApplicationException
|
||||
{
|
||||
public AircraftNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
|
||||
public AircraftNotFoundException() : base() { }
|
||||
public AircraftNotFoundException(string message) : base(message) { }
|
||||
public AircraftNotFoundException(string message, Exception exception) :
|
||||
base(message, exception)
|
||||
{ }
|
||||
protected AircraftNotFoundException(SerializationInfo info,
|
||||
StreamingContext contex) : base(info, contex) { }
|
||||
}
|
||||
}
|
@ -64,7 +64,7 @@ namespace AircraftCarrier.Generics
|
||||
}
|
||||
}
|
||||
/// Сохранение информации по автомобилям в хранилище в файл
|
||||
public bool SaveData(string filename)
|
||||
public void SaveData(string filename)
|
||||
{
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
@ -83,56 +83,69 @@ namespace AircraftCarrier.Generics
|
||||
}
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return false;
|
||||
throw new Exception("Невалиданя операция, нет данных для сохранения");
|
||||
}
|
||||
using StreamWriter sw = new(filename);
|
||||
sw.Write($"AircraftStorage{Environment.NewLine}{data}");
|
||||
return true;
|
||||
using FileStream fs = new(filename, FileMode.Create);
|
||||
byte[] info = new
|
||||
UTF8Encoding(true).GetBytes($"CarStorage{Environment.NewLine}{data}");
|
||||
fs.Write(info, 0, info.Length);
|
||||
return;
|
||||
}
|
||||
/// Загрузка информации по автомобилям в хранилище из файла
|
||||
public bool LoadData(string filename)
|
||||
public void LoadData(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
return false;
|
||||
throw new FileNotFoundException("Файл не найден");
|
||||
}
|
||||
using (StreamReader sr = new(filename))
|
||||
string bufferTextFromFile = "";
|
||||
using (FileStream fs = new(filename, FileMode.Open))
|
||||
{
|
||||
string str = sr.ReadLine();
|
||||
if (str == null || str.Length == 0)
|
||||
byte[] b = new byte[fs.Length];
|
||||
UTF8Encoding temp = new(true);
|
||||
while (fs.Read(b, 0, b.Length) > 0)
|
||||
{
|
||||
return false;
|
||||
bufferTextFromFile += temp.GetString(b);
|
||||
}
|
||||
if (!str.StartsWith("AircraftStorage"))
|
||||
}
|
||||
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
if (strs == null || strs.Length == 0)
|
||||
{
|
||||
throw new FileNotFoundException("Нет данных для загрузки");
|
||||
}
|
||||
if (!strs[0].StartsWith("CarStorage"))
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
throw new FileNotFoundException("Неверный формат данных");
|
||||
}
|
||||
_AircraftStorages.Clear();
|
||||
foreach (string data in strs)
|
||||
{
|
||||
string[] record = data.Split(_separatorForKeyValue,
|
||||
StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 2)
|
||||
{
|
||||
//если нет такой записи, то это не те данные
|
||||
return false;
|
||||
continue;
|
||||
}
|
||||
_AircraftStorages.Clear();
|
||||
while ((str = sr.ReadLine()) != null)
|
||||
AircraftsGenericCollection<DrawningAircraft, DrawningObjectAircraft>
|
||||
collection = new(_pictureWidth, _pictureHeight);
|
||||
string[] set = record[1].Split(_separatorRecords,StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set)
|
||||
{
|
||||
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
|
||||
if (record.Length != 2)
|
||||
DrawningAircraft? aircraft =
|
||||
elem?.CreateDrawningAircraft(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (aircraft != null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
AircraftsGenericCollection<DrawningAircraft, DrawningObjectAircraft> collection = new(_pictureWidth, _pictureHeight);
|
||||
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
|
||||
foreach (string elem in set.Reverse())
|
||||
{
|
||||
DrawningAircraft? aircraft = elem?.CreateDrawningAircraft(_separatorForObject, _pictureWidth, _pictureHeight);
|
||||
if (aircraft != null)
|
||||
if (collection + aircraft == -1)
|
||||
{
|
||||
if (collection + aircraft == -1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
throw new ApplicationException("Ошибка добавления в коллекцию");
|
||||
}
|
||||
}
|
||||
_AircraftStorages.Add(record[0], collection);
|
||||
}
|
||||
_AircraftStorages.Add(record[0], collection);
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
20
AircraftCarrier/AircraftCarrier/AppSettings.json
Normal file
20
AircraftCarrier/AircraftCarrier/AppSettings.json
Normal file
@ -0,0 +1,20 @@
|
||||
{
|
||||
"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": "Aircraft"
|
||||
}
|
||||
}
|
||||
}
|
@ -10,15 +10,21 @@ using System.Windows.Forms;
|
||||
using AircraftCarrier.DrawningObjects;
|
||||
using AircraftCarrier.Generics;
|
||||
using AircraftCarrier.MovementStrategy;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using AircraftCarrier.Exceptions;
|
||||
|
||||
namespace AircraftCarrier
|
||||
{
|
||||
public partial class FormAircraftCollection : Form
|
||||
{
|
||||
private readonly AircraftsGenericStorage _storage;
|
||||
public FormAircraftCollection()
|
||||
private readonly ILogger _logger;
|
||||
public FormAircraftCollection(ILogger<FormAircraftCollection> logger)
|
||||
{
|
||||
InitializeComponent();
|
||||
_storage = new AircraftsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
|
||||
_storage = new AircraftsGenericStorage(pictureBoxCollection.Width,
|
||||
pictureBoxCollection.Height);
|
||||
_logger = logger;
|
||||
}
|
||||
/// Заполнение listBoxObjects
|
||||
private void ReloadObjects()
|
||||
@ -43,10 +49,12 @@ namespace AircraftCarrier
|
||||
if (string.IsNullOrEmpty(textBoxStorageName.Text))
|
||||
{
|
||||
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning("Неудачная попытка добавить набор: заполнены не все данные");
|
||||
return;
|
||||
}
|
||||
_storage.AddSet(textBoxStorageName.Text);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Набор добавлен: {textBoxStorageName.Text}");
|
||||
}
|
||||
private void listBoxStorage_SelectedIndexChanged(object sender, EventArgs e)
|
||||
{
|
||||
@ -56,20 +64,23 @@ namespace AircraftCarrier
|
||||
{
|
||||
if (listBoxStorage.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Неудачная попытка удалить набор: набор не выбран");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show($"Удалить объект{listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo,
|
||||
MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
|
||||
|
||||
if (MessageBox.Show($"Удалить набор {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
|
||||
{
|
||||
_storage.DelSet(listBoxStorage.SelectedItem.ToString()
|
||||
?? string.Empty);
|
||||
_storage.DelSet(name);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Удаленный набор: {name}");
|
||||
}
|
||||
}
|
||||
private void ButtonAddAircraft_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorage.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Неудачная попытка добавить объект: набор не выбран");
|
||||
return;
|
||||
}
|
||||
var formMonorailConfig = new FormAircraftConfig();
|
||||
@ -87,44 +98,64 @@ namespace AircraftCarrier
|
||||
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning($"Неудачная попытка добавить объект: значение set равно null");
|
||||
return;
|
||||
}
|
||||
if (obj + aircraft != -1)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект добавлен");
|
||||
pictureBoxCollection.Image = obj.ShowAircrafts();
|
||||
if (obj + aircraft != -1)
|
||||
{
|
||||
MessageBox.Show("Добавленный объект");
|
||||
pictureBoxCollection.Image = obj.ShowAircrafts();
|
||||
_logger.LogInformation($"Добавленный объект {aircraft}");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Неудачная попытка добавить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch(ApplicationException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось добавить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"Неудачная попытка добавить объект: {ex.Message}");
|
||||
}
|
||||
}
|
||||
private void ButtonRemoveAircraft_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (listBoxStorage.SelectedIndex == -1)
|
||||
{
|
||||
_logger.LogWarning($"Неудачная попытка удалить объект: набор не выбран");
|
||||
return;
|
||||
}
|
||||
var obj = _storage[listBoxStorage.SelectedItem.ToString() ??
|
||||
string.Empty];
|
||||
if (obj == null)
|
||||
{
|
||||
_logger.LogWarning($"Неудачная попытка удалить объект: значение set равно null");
|
||||
return;
|
||||
}
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление",
|
||||
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
|
||||
{
|
||||
return;
|
||||
}
|
||||
int pos = Convert.ToInt32(MaskedTextBoxNumber.Text);
|
||||
if (obj - pos != null)
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowAircrafts();
|
||||
if (obj - pos)
|
||||
{
|
||||
MessageBox.Show("Объект удален");
|
||||
pictureBoxCollection.Image = obj.ShowAircrafts();
|
||||
_logger.LogInformation($"Удаленный объект на месте: {pos}");
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show("Неудачная попытка удалить объект");
|
||||
}
|
||||
}
|
||||
else
|
||||
catch (AircraftNotFoundException ex)
|
||||
{
|
||||
MessageBox.Show("Не удалось удалить объект");
|
||||
MessageBox.Show(ex.Message);
|
||||
_logger.LogWarning($"Неудачная попытка удалить объект: {ex.Message}");
|
||||
}
|
||||
}
|
||||
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
|
||||
@ -146,36 +177,41 @@ namespace AircraftCarrier
|
||||
{
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.SaveData(saveFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
_storage.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
_logger.LogInformation($"Файл успешно сохранен {saveFileDialog.FileName}");
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не сохранилось", "Результат",
|
||||
MessageBox.Show($"Сохранить не удалось: {ex.Message}", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не удалось сохранить файл: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
/// Обработка нажатия "Загрузка"
|
||||
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (openFileDialog.ShowDialog() == DialogResult.OK)
|
||||
if (saveFileDialog.ShowDialog() == DialogResult.OK)
|
||||
{
|
||||
if (_storage.LoadData(openFileDialog.FileName))
|
||||
try
|
||||
{
|
||||
MessageBox.Show("Загрузка прошла успешно",
|
||||
_storage.SaveData(saveFileDialog.FileName);
|
||||
MessageBox.Show("Сохранение прошло успешно",
|
||||
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
ReloadObjects();
|
||||
_logger.LogInformation($"Файл успешно сохранен: {saveFileDialog.FileName}");
|
||||
}
|
||||
else
|
||||
catch (Exception ex)
|
||||
{
|
||||
MessageBox.Show("Не загрузилось", "Результат",
|
||||
MessageBox.Show($"Сбой загрузки: {ex.Message}", "Результат",
|
||||
MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
_logger.LogWarning($"Не удалось загрузить файл: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Serilog;
|
||||
|
||||
namespace AircraftCarrier
|
||||
{
|
||||
internal static class Program
|
||||
@ -6,10 +11,32 @@ namespace AircraftCarrier
|
||||
[STAThread]
|
||||
static void Main()
|
||||
{
|
||||
// To customize application configuration such as set high DPI settings or default font,
|
||||
// see https://aka.ms/applicationconfiguration.
|
||||
ApplicationConfiguration.Initialize();
|
||||
Application.Run(new FormAircraftCollection());
|
||||
var services = new ServiceCollection();
|
||||
ConfigureServices(services);
|
||||
using (ServiceProvider serviceProvider =
|
||||
services.BuildServiceProvider())
|
||||
{
|
||||
|
||||
Application.Run(serviceProvider.GetRequiredService<FormAircraftCollection>());
|
||||
}
|
||||
}
|
||||
private static void ConfigureServices(ServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<FormAircraftCollection>().AddLogging(option =>
|
||||
{
|
||||
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}appsettings.json", optional: false, reloadOnChange: true).Build();
|
||||
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
|
||||
option.SetMinimumLevel(LogLevel.Information);
|
||||
option.AddSerilog(logger);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using AircraftCarrier.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@ -28,8 +29,10 @@ namespace AircraftCarrier.Generics
|
||||
/// Добавление объекта в набор на конкретную позицию
|
||||
public int Insert(T Aircraft, int position)
|
||||
{
|
||||
if (position < 0 || position > Count || Count >= _maxCount)
|
||||
return -1;
|
||||
if (position < 0 || position > Count)
|
||||
throw new AircraftNotFoundException("Impossible to insert");
|
||||
if (Count >= _maxCount)
|
||||
throw new StorageOverflowException(_maxCount);
|
||||
|
||||
_places.Insert(position, Aircraft);
|
||||
return position;
|
||||
@ -38,7 +41,7 @@ namespace AircraftCarrier.Generics
|
||||
public bool Remove(int position)
|
||||
{
|
||||
if (position < 0 || position >= Count)
|
||||
return false;
|
||||
throw new AircraftNotFoundException(position);
|
||||
_places.RemoveAt(position);
|
||||
return true;
|
||||
}
|
||||
|
21
AircraftCarrier/AircraftCarrier/StorageOverflowException.cs
Normal file
21
AircraftCarrier/AircraftCarrier/StorageOverflowException.cs
Normal 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;
|
||||
|
||||
namespace AircraftCarrier
|
||||
{
|
||||
[Serializable]
|
||||
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) { }
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user