From c156ce7b1f206ce226bd3424cd982489d1433c92 Mon Sep 17 00:00:00 2001 From: Whoisthatjulia Date: Fri, 29 Dec 2023 19:55:03 +0400 Subject: [PATCH] lab_7 --- AirFighter/AirFighter/AirFighter.csproj | 10 +++ AirFighter/AirFighter/AirFighterDelegate.cs | 11 --- .../AirFighter/AirFighterGenericCollection.cs | 29 +++--- .../AirFighter/AirFighterGenericStorage.cs | 75 ++++++++-------- .../AirFighter/AirFighterNotFoundException.cs | 19 ++++ AirFighter/AirFighter/DrawningAirFighter.cs | 30 +++---- AirFighter/AirFighter/ExtentionAirFighter.cs | 2 +- .../AirFighter/FormAirFighterCollection.cs | 88 +++++++++++-------- .../AirFighter/IMoveableObject_Realise.cs | 14 +++ AirFighter/AirFighter/Program.cs | 37 +++++++- AirFighter/AirFighter/SetGeneric.cs | 46 ++++++++-- .../AirFighter/StorageOverflowException.cs | 18 ++++ AirFighter/AirFighter/appsettings.json | 20 +++++ 13 files changed, 268 insertions(+), 131 deletions(-) delete mode 100644 AirFighter/AirFighter/AirFighterDelegate.cs create mode 100644 AirFighter/AirFighter/AirFighterNotFoundException.cs create mode 100644 AirFighter/AirFighter/StorageOverflowException.cs create mode 100644 AirFighter/AirFighter/appsettings.json diff --git a/AirFighter/AirFighter/AirFighter.csproj b/AirFighter/AirFighter/AirFighter.csproj index b57c89e..9619a2e 100644 --- a/AirFighter/AirFighter/AirFighter.csproj +++ b/AirFighter/AirFighter/AirFighter.csproj @@ -8,4 +8,14 @@ enable + + + + + + + + + + \ No newline at end of file diff --git a/AirFighter/AirFighter/AirFighterDelegate.cs b/AirFighter/AirFighter/AirFighterDelegate.cs deleted file mode 100644 index 83a021e..0000000 --- a/AirFighter/AirFighter/AirFighterDelegate.cs +++ /dev/null @@ -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); -} diff --git a/AirFighter/AirFighter/AirFighterGenericCollection.cs b/AirFighter/AirFighter/AirFighterGenericCollection.cs index e91db23..95afa39 100644 --- a/AirFighter/AirFighter/AirFighterGenericCollection.cs +++ b/AirFighter/AirFighter/AirFighterGenericCollection.cs @@ -37,14 +37,14 @@ namespace AirFighter.Generics } return collect?._collection.Insert(obj); } - public static bool operator -(AirFighterGenericCollection collect, int pos) + public static T operator -(AirFighterGenericCollection 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); - } } } } diff --git a/AirFighter/AirFighter/AirFighterGenericStorage.cs b/AirFighter/AirFighter/AirFighterGenericStorage.cs index f005ab9..5e2295e 100644 --- a/AirFighter/AirFighter/AirFighterGenericStorage.cs +++ b/AirFighter/AirFighter/AirFighterGenericStorage.cs @@ -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("Файл не найден"); } - - 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 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; } } } diff --git a/AirFighter/AirFighter/AirFighterNotFoundException.cs b/AirFighter/AirFighter/AirFighterNotFoundException.cs new file mode 100644 index 0000000..bd62293 --- /dev/null +++ b/AirFighter/AirFighter/AirFighterNotFoundException.cs @@ -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) { } + } +} + diff --git a/AirFighter/AirFighter/DrawningAirFighter.cs b/AirFighter/AirFighter/DrawningAirFighter.cs index eb96955..f09a34b 100644 --- a/AirFighter/AirFighter/DrawningAirFighter.cs +++ b/AirFighter/AirFighter/DrawningAirFighter.cs @@ -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) { diff --git a/AirFighter/AirFighter/ExtentionAirFighter.cs b/AirFighter/AirFighter/ExtentionAirFighter.cs index f831a1e..3d06670 100644 --- a/AirFighter/AirFighter/ExtentionAirFighter.cs +++ b/AirFighter/AirFighter/ExtentionAirFighter.cs @@ -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]), diff --git a/AirFighter/AirFighter/FormAirFighterCollection.cs b/AirFighter/AirFighter/FormAirFighterCollection.cs index 27006b7..c11023f 100644 --- a/AirFighter/AirFighter/FormAirFighterCollection.cs +++ b/AirFighter/AirFighter/FormAirFighterCollection.cs @@ -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 /// Набор объектов /// private readonly AirFighterGenericStorage _storage; + private readonly ILogger _logger; /// /// Конструктор /// - public FormAirFighterCollection() + public FormAirFighterCollection(ILogger logger) { InitializeComponent(); _storage = new AirFighterGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } /// /// Заполнение 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}"); } /// /// Выбор набора @@ -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}"); } } /// @@ -99,35 +107,36 @@ namespace AirFighter /// /// /// - 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()}"); } } /// @@ -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}"); } } } diff --git a/AirFighter/AirFighter/IMoveableObject_Realise.cs b/AirFighter/AirFighter/IMoveableObject_Realise.cs index d2e1ede..3f5238c 100644 --- a/AirFighter/AirFighter/IMoveableObject_Realise.cs +++ b/AirFighter/AirFighter/IMoveableObject_Realise.cs @@ -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); + } + } } } diff --git a/AirFighter/AirFighter/Program.cs b/AirFighter/AirFighter/Program.cs index 1dd7fab..7e8dc16 100644 --- a/AirFighter/AirFighter/Program.cs +++ b/AirFighter/AirFighter/Program.cs @@ -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()); + } + } + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton().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); + }); } } -} \ No newline at end of file +} + + + diff --git a/AirFighter/AirFighter/SetGeneric.cs b/AirFighter/AirFighter/SetGeneric.cs index 9910b40..291e24c 100644 --- a/AirFighter/AirFighter/SetGeneric.cs +++ b/AirFighter/AirFighter/SetGeneric.cs @@ -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] diff --git a/AirFighter/AirFighter/StorageOverflowException.cs b/AirFighter/AirFighter/StorageOverflowException.cs new file mode 100644 index 0000000..e8a0120 --- /dev/null +++ b/AirFighter/AirFighter/StorageOverflowException.cs @@ -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) { } + } +} diff --git a/AirFighter/AirFighter/appsettings.json b/AirFighter/AirFighter/appsettings.json new file mode 100644 index 0000000..66e218d --- /dev/null +++ b/AirFighter/AirFighter/appsettings.json @@ -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" + } + } +} \ No newline at end of file