ИСЭбд-22 Семеленова Юлия лаб_7 простая #9

Closed
Whoisthatjulia wants to merge 1 commits from lab_7 into lab_6
13 changed files with 268 additions and 131 deletions

View File

@ -8,4 +8,14 @@
<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>
</Project>

View File

@ -1,11 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AirFighter.DrawningObjects;
namespace AirFighter
{
public delegate void AirFighterDelegate(DrawningAirFighter fighter);
}

View File

@ -37,14 +37,14 @@ namespace AirFighter.Generics
}
return collect?._collection.Insert(obj);
}
public static bool operator -(AirFighterGenericCollection<T, U> collect, int pos)
public static T operator -(AirFighterGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj != null)
{
return collect._collection.Remove(pos);
collect?._collection.Remove(pos);
}
return false;
return obj;
}
public U? GetU(int pos)
{
@ -78,19 +78,20 @@ namespace AirFighter.Generics
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
foreach (var fighter in _collection.GetAirFighter())
{
if (fighter != null)
for (int i = 0; i < _collection.Count; i++)
foreach (var airfighter in _collection.GetAirFighter())
{
int index = _collection.GetAirFighter().ToList().IndexOf(fighter);
int row = height - 1 - (index / width);
int col = width - 1 - (index % width);
fighter.SetPosition(col * _placeSizeWidth + 10, row * _placeSizeHeight + 5);
if (airfighter != null)
{
T? fighter = _collection[i];
if (fighter == null)
continue;
int row = height - 1 - (i / width);
int col = width - 1 - (i % width);
fighter.SetPosition(col * _placeSizeWidth + 10, row * _placeSizeHeight + 5);
fighter.DrawTransport(g);
}
}
fighter.DrawTransport(g);
}
}
}
}

View File

@ -7,6 +7,8 @@ using AirFighter.DrawningObjects;
using AirFighter.MovementStrategy;
using AirFighter.Generics;
using System.IO;
using AirFighter.Exceptions;
namespace AirFighter.Generics
{
@ -51,7 +53,7 @@ namespace AirFighter.Generics
private readonly char _separatorRecords = ';';
private static readonly char _separatorForObject = ':';
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -69,71 +71,66 @@ namespace AirFighter.Generics
}
if (data.Length == 0)
{
return false;
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using StreamWriter fs = new StreamWriter(filename);
using (StreamWriter writer = new StreamWriter(filename))
{
fs.WriteLine($"AirFighterStorages{Environment.NewLine}");
fs.WriteLine(data);
writer.Write($"fighterStorage{Environment.NewLine}{data}");
}
return true;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не найден");
Review

Требовалось заменить класс Exception на его более подходящих наследников

Требовалось заменить класс Exception на его более подходящих наследников
}
using (StreamReader fs = File.OpenText(filename))
using (StreamReader reader = new StreamReader(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
string cheker = reader.ReadLine();
if (cheker == null)
{
return false;
throw new Exception("Нет данных для загрузки");
}
if (!str.StartsWith("AirFighterStorages"))
if (!cheker.StartsWith("fighterStorage"))
{
//если нет такой записи, то это не те данные
return false;
throw new Exception("Неверный формат ввода");
}
_fighterStorages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
string strs;
bool firstinit = true;
while ((strs = reader.ReadLine()) != null)
{
if (strs == null && firstinit)
{
throw new Exception("Нет данных для загрузки");
}
if (strs == null)
{
return false;
}
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
continue;
break;
}
firstinit = false;
string name = strs.Split(_separatorForKeyValue)[0];
AirFighterGenericCollection<DrawningAirFighter, DrawningObjectAirFighter> collection = new(_pictureWidth, _pictureHeight);
string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
foreach (string data in strs.Split(_separatorForKeyValue)[1].Split(_separatorRecords))
{
DrawningAirFighter? fighter = elem?.CreateDrawningAirFighter(_separatorForObject, _pictureWidth, _pictureHeight);
DrawningAirFighter? fighter =
data?.CreateDrawningAirFighter(_separatorForObject, _pictureWidth, _pictureHeight);
if (fighter != null)
{
if ((collection + fighter) == -1)
try { _ = collection + fighter; }
catch (AirFighterNotFoundException e)
{
return false;
throw e;
}
catch (StorageOverflowException e)
{
throw e;
}
}
}
_fighterStorages.Add(record[0], collection);
_fighterStorages.Add(name, collection);
}
return true;
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter
{
[Serializable] internal class AirFighterNotFoundException : ApplicationException
{
public AirFighterNotFoundException(int i) : base($"Не найден объект по позиции {i}") { }
public AirFighterNotFoundException() : base() { }
public AirFighterNotFoundException(string message) : base(message) { }
public AirFighterNotFoundException(string message, Exception exception) : base(message, exception) { }
protected AirFighterNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -17,9 +17,9 @@ namespace AirFighter.DrawningObjects
{
public EntityAirFighter? EntityAirFighter { get; protected set; }
public int _pictureWidth;
private int _pictureWidth;
public int _pictureHeight;
private int _pictureHeight;
protected int _startPosX;
@ -55,22 +55,12 @@ namespace AirFighter.DrawningObjects
}
public void SetPosition(int x, int y)
{
if (x < 0)
{
x = 0;
}
else if (x > _pictureWidth - _fighterWidth)
{
x = _pictureWidth - _fighterWidth;
}
if (y < 0)
{
y = 0;
}
else if (y > _pictureHeight - _fighterHeight)
{
y = _pictureHeight - _fighterHeight;
}
if ((x > 0) && (x < _pictureWidth))
_startPosX = x;
else _startPosX = 0;
if ((y > 0) && (y < _pictureHeight))
_startPosY = y;
else _startPosY = 0;
_startPosX = x;
_startPosY = y;
}
@ -79,7 +69,7 @@ namespace AirFighter.DrawningObjects
public int GetPosY => _startPosY;
public int GetWidth => _fighterWidth;
public int GetHeight => _fighterHeight;
public virtual bool CanMove(DirectionAirFighter direction)
public bool CanMove(DirectionAirFighter direction)
{
if (EntityAirFighter == null)
{
@ -97,7 +87,7 @@ namespace AirFighter.DrawningObjects
_ => false,
};
}
public virtual void MoveTransport(DirectionAirFighter direction)
public void MoveTransport(DirectionAirFighter direction)
{
if (!CanMove(direction) || EntityAirFighter == null)
{

View File

@ -17,7 +17,7 @@ namespace AirFighter.DrawningObjects
return new DrawningAirFighter(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]), width, height);
}
if (strs.Length == 6)
else if (strs.Length == 6)
{
return new DrawningAirFighterMilitary(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]),

View File

@ -3,6 +3,7 @@ using AirFighter.DrawningObjects;
using AirFighter.Drawnings;
using AirFighter.Generics;
using AirFighter.MovementStrategy;
using Microsoft.Extensions.Logging;
@ -17,14 +18,16 @@ namespace AirFighter
/// Набор объектов
/// </summary>
private readonly AirFighterGenericStorage _storage;
private readonly ILogger _logger;
/// <summary>
/// Конструктор
/// </summary>
public FormAirFighterCollection()
public FormAirFighterCollection(ILogger<FormAirFighterCollection> logger)
{
InitializeComponent();
_storage = new AirFighterGenericStorage(pictureBoxCollection.Width,
pictureBoxCollection.Height);
_logger = logger;
}
/// <summary>
/// Заполнение listBoxObjects
@ -59,10 +62,12 @@ namespace AirFighter
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Пустое название набора");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}");
}
/// <summary>
/// Выбор набора
@ -84,14 +89,17 @@ namespace AirFighter
{
if (listBoxStorage.SelectedIndex == -1)
{
_logger.LogWarning("Удаление невыбранного набора");
return;
}
string name = listBoxStorage.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"Удалить объект {listBoxStorage.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorage.SelectedItem.ToString()
?? string.Empty);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
/// <summary>
@ -99,35 +107,36 @@ namespace AirFighter
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void addAirFighter(DrawningAirFighter fighter)
private void ButtonAddAirFighter_Click(object sender, EventArgs e)
{
fighter._pictureHeight = pictureBoxCollection.Height;
fighter._pictureWidth = pictureBoxCollection.Width;
if (listBoxStorage.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (obj + fighter != -1)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowAirFighter();
}
else
{
MessageBox.Show("Не удалось добавить объект");
}
}
private void ButtonAddAirFighter_Click(object sender, EventArgs e)
{
var formAirFighterConfig = new FormAirFighterConfig();
formAirFighterConfig.AddEvent(addAirFighter);
formAirFighterConfig.AddEvent(fighter =>
{
var obj = _storage[listBoxStorage.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
_logger.LogWarning("Добавление пустого объекта");
return;
}
try
{
_ = obj + fighter;
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowAirFighter();
_logger.LogInformation($"Добавлен объект в набор {listBoxStorage.SelectedItem.ToString()}");
}
catch (Exception ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"{ex.Message} в наборе {listBoxStorage.SelectedItem.ToString()}");
}
});
formAirFighterConfig.Show();
}
@ -141,6 +150,7 @@ namespace AirFighter
{
if (listBoxStorage.SelectedIndex == -1)
{
_logger.LogWarning("Удаление объекта из несуществующего набора");
return;
}
var obj = _storage[listBoxStorage.SelectedItem.ToString() ??
@ -159,10 +169,12 @@ namespace AirFighter
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = obj.ShowAirFighter();
_logger.LogInformation($"Удален объект из набора {listBoxStorage.SelectedItem.ToString()}");
}
else
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Не удалось удалить объект из набора {listBoxStorage.SelectedItem.ToString()}");
}
}
/// <summary>
@ -190,15 +202,16 @@ namespace AirFighter
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog1.FileName))
try
{
MessageBox.Show("Сохранение прошло успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_storage.SaveData(saveFileDialog1.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Сохранение наборов в файл {saveFileDialog1.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось сохранить наборы с ошибкой: {ex.Message}");
}
}
}
@ -207,16 +220,17 @@ namespace AirFighter
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog1.FileName))
try
{
_storage.LoadData(openFileDialog1.FileName);
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно",
"Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Загрузились наборы из файла {openFileDialog1.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось загрузить наборы с ошибкой: {ex.Message}");
}
}
}

View File

@ -33,5 +33,19 @@ namespace AirFighter.MovementStrategy
_drawningAirFighter?.CanMove(direction) ?? false;
public void MoveObject(DirectionAirFighter direction) =>
_drawningAirFighter?.MoveTransport(direction);
public void SetPosition(int x, int y)
{
if (_drawningAirFighter != null)
{
_drawningAirFighter.SetPosition(x, y);
}
}
public void Draw(Graphics g)
{
if (_drawningAirFighter != null)
{
_drawningAirFighter.DrawTransport(g);
}
}
}
}

View File

@ -1,3 +1,12 @@
using AirFighter;
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using Serilog;
using AirFighter;
namespace AirFighter
{
internal static class Program
@ -11,7 +20,31 @@ namespace AirFighter
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormAirFighterCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormAirFighterCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormAirFighterCollection>().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);
});
}
}
}
}

View File

@ -1,4 +1,5 @@
using System.Numerics;
using AirFighter.Exceptions;
namespace AirFighter.Generics
{
@ -15,19 +16,50 @@ namespace AirFighter.Generics
}
public int Insert(T fighter)
{
return Insert(fighter, 0);
if (_places.Count == 0)
{
_places.Add(fighter);
return 0;
}
else
{
if (_places.Count < _maxCount)
{
_places.Add(fighter);
for (int i = 0; i < _places.Count; i++)
{
T temp = _places[i];
_places[i] = _places[_places.Count - 1];
_places[_places.Count - 1] = temp;
}
return 0;
}
else
{
throw new StorageOverflowException(_places.Count);
}
}
}
public int Insert(T fighter, int position)
public bool Insert(T fighter, int position)
{
if (position < 0 || position >= _maxCount) return -1;
_places.Insert(position, fighter);
return position;
if (position < 0 || position >= _maxCount)
throw new AirFighterNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(position);
_places.Insert(0, fighter);
return true;
}
public bool Remove(int position)
{
if ((position < 0) || (position > _maxCount)) return false;
_places.RemoveAt(position);
if (position < 0 || position > _maxCount || position >= Count)
throw new AirFighterNotFoundException();
if (_places[position] == null)
{
throw new AirFighterNotFoundException();
}
_places[position] = null;
return true;
}
public T? this[int position]

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace AirFighter.Exceptions
{
[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) { }
}
}

View 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", "WithShipName", "WithThreadId" ],
"Properties": {
"Application": "AirFighter"
}
}
}