diff --git a/ProjectFighterJet/CollectionGenericObjects/ListGenericObjects.cs b/ProjectFighterJet/CollectionGenericObjects/ListGenericObjects.cs index 3cb313e..4e0b97c 100644 --- a/ProjectFighterJet/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectFighterJet/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ using ProjectFighterJet.CollectionGenericObjects; +using ProjectFighterJet.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -57,33 +58,28 @@ where T : class } public int Insert(T obj) { - if (Count <= _maxCount) - { - _collection.Add(obj); - return Count; - } - return -1; + // TODO выброс ошибки если переполнение + if (Count == _maxCount) throw new CollectionOverflowException(Count); + _collection.Add(obj); + return Count; } public int Insert(T obj, int position) { - if (Count < _maxCount && position >= 0 && position < _maxCount) - { - _collection.Insert(position, obj); - return position; - } - return -1; + // TODO выброс ошибки если переполнение + // TODO выброс ошибки если за границу + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + _collection.Insert(position, obj); + return position; } public T Remove(int position) { - T temp = _collection[position]; - if (position >= 0 && position < _maxCount) - { - _collection.RemoveAt(position); - return temp; - } - return null; + // TODO если выброс за границу + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; + _collection.RemoveAt(position); + return obj; } - public IEnumerable GetItems() { for (int i = 0; i < Count; ++i) diff --git a/ProjectFighterJet/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectFighterJet/CollectionGenericObjects/MassiveGenericObjects.cs index 19be99a..7f5129d 100644 --- a/ProjectFighterJet/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectFighterJet/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ using ProjectFighterJet.Drawnings; +using ProjectFighterJet.Exceptions; namespace ProjectFighterJet.CollectionGenericObjects; @@ -65,12 +66,14 @@ where T : class } index++; } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) - { - if (position >= _collection.Length || position < 0) return -1; + { + // TODO выброс ошибки если переполнение + // TODO выброс ошибки если выход за границу + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { _collection[position] = obj; @@ -84,7 +87,7 @@ where T : class _collection[index] = obj; return index; } - index++; + ++index; } index = position - 1; while (index >= 0) @@ -94,17 +97,20 @@ where T : class _collection[index] = obj; return index; } - index--; + --index; } - return -1; + throw new CollectionOverflowException(Count); } public T? Remove(int position) { - if (position >= _collection.Length || position < 0) return null; - T temp = _collection[position]; + // TODO выброс ошибки если выход за границу + // TODO выброс ошибки если объект пустой + 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 temp; + return obj; } public IEnumerable GetItems() diff --git a/ProjectFighterJet/CollectionGenericObjects/StorageCollection.cs b/ProjectFighterJet/CollectionGenericObjects/StorageCollection.cs index ecf0b7e..8d2b42c 100644 --- a/ProjectFighterJet/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectFighterJet/CollectionGenericObjects/StorageCollection.cs @@ -6,6 +6,7 @@ using System.Text; using System.Threading.Tasks; using System.Text; using static System.Runtime.InteropServices.JavaScript.JSType; +using ProjectFighterJet.Exceptions; namespace ProjectFighterJet.CollectionGenericObjects; @@ -90,12 +91,12 @@ where T : DrawningJet /// Сохранение информации по автомобилям в хранилище в файл /// /// Путь и имя файла - /// true - сохранение прошло успешно, false - ошибка при сохранении данных - public bool SaveData(string filename) + + public void SaveData(string filename) { if (_storages.Count == 0) { - return false; + throw new Exception("В хранилище отсутствуют коллекции для сохранения"); } if (File.Exists(filename)) { @@ -106,19 +107,18 @@ where T : DrawningJet writer.Write(_collectionKey); foreach (KeyValuePair> value in _storages) { - StringBuilder sb = new(); - sb.Append(Environment.NewLine); + writer.Write(Environment.NewLine); // не сохраняем пустые коллекции if (value.Value.Count == 0) { continue; } - sb.Append(value.Key); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.GetCollectionType); - sb.Append(_separatorForKeyValue); - sb.Append(value.Value.MaxCount); - sb.Append(_separatorForKeyValue); + writer.Write(value.Key); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.GetCollectionType); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.MaxCount); + writer.Write(_separatorForKeyValue); foreach (T? item in value.Value.GetItems()) { string data = item?.GetDataForSave() ?? string.Empty; @@ -126,85 +126,40 @@ where T : DrawningJet { continue; } - sb.Append(data); - sb.Append(_separatorItems); + writer.Write(data); + writer.Write(_separatorItems); } - writer.Write(sb); } } - //if (_storages.Count == 0) - //{ - // return false; - //} - //if (File.Exists(filename)) - //{ - // File.Delete(filename); - //} - //StringBuilder sb = new(); - //sb.Append(_collectionKey); - //foreach (KeyValuePair> value in _storages) - //{ - // sb.Append(Environment.NewLine); - // // не сохраняем пустые коллекции - // if (value.Value.Count == 0) - // { - // continue; - // } - // sb.Append(value.Key); - // sb.Append(_separatorForKeyValue); - // sb.Append(value.Value.GetCollectionType); - // sb.Append(_separatorForKeyValue); - // sb.Append(value.Value.MaxCount); - // sb.Append(_separatorForKeyValue); - // foreach (T? item in value.Value.GetItems()) - // { - // string data = item?.GetDataForSave() ?? string.Empty; - // if (string.IsNullOrEmpty(data)) - // { - // continue; - // } - // sb.Append(data); - // sb.Append(_separatorItems); - // } - //} - //using FileStream fs = new(filename, FileMode.Create); - //byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); - //fs.Write(info, 0, info.Length); - - return true; + } /// /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных - 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)) { string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); string strs = ""; while ((strs = fs.ReadLine()) != null) { - //по идее этого произойти не должно - //if (strs == null) - //{ - // return false; - //} + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 4) { @@ -214,7 +169,7 @@ where T : DrawningJet ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); @@ -222,65 +177,21 @@ where T : DrawningJet { if (elem?.CreateDrawningJet() is T jet) { - if (collection.Insert(jet) == -1) + try { - return false; + if (collection.Insert(jet) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } - return true; - //string bufferTextFromFile = ""; - //using (FileStream fs = new(filename, FileMode.Open)) - //{ - // byte[] b = new byte[fs.Length]; - // UTF8Encoding temp = new(true); - // while (fs.Read(b, 0, b.Length) > 0) - // { - // bufferTextFromFile += temp.GetString(b); - // } - //} - //string[] strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - //if (strs == null || strs.Length == 0) - //{ - // return false; - //} - //if (!strs[0].Equals(_collectionKey)) - //{ - // //если нет такой записи, то это не те данные - // return false; - //} - //_storages.Clear(); - //foreach (string data in strs) - //{ - // string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - // if (record.Length != 4) - // { - // continue; - // } - // CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); - // ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); - // if (collection == null) - // { - // return false; - // } - // collection.MaxCount = Convert.ToInt32(record[2]); - // string[] set = record[3].Split(_separatorItems, - // StringSplitOptions.RemoveEmptyEntries); - // foreach (string elem in set) - // { - // if (elem?.CreateDrawningShip() is T ship) - // { - // if (collection.Insert(ship) == -1) - // { - // return false; - // } - // } - // } - // _storages.Add(record[0], collection); - //} - //return true; } } /// diff --git a/ProjectFighterJet/Exceptions/CollectionOverflowException.cs b/ProjectFighterJet/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..f8575a7 --- /dev/null +++ b/ProjectFighterJet/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,16 @@ +using System.Runtime.Serialization; + +namespace ProjectFighterJet.Exceptions; + +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[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) { } +} diff --git a/ProjectFighterJet/Exceptions/ObjectNotFoundException.cs b/ProjectFighterJet/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..be76eb7 --- /dev/null +++ b/ProjectFighterJet/Exceptions/ObjectNotFoundException.cs @@ -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 ProjectFighterJet.Exceptions; + +/// +/// Класс, описывающий ошибку, что по указанной позиции нет элемента +/// +[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) { } +} \ No newline at end of file diff --git a/ProjectFighterJet/Exceptions/PositionOutOfCollectionException.cs b/ProjectFighterJet/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..564d29b --- /dev/null +++ b/ProjectFighterJet/Exceptions/PositionOutOfCollectionException.cs @@ -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 ProjectFighterJet.Exceptions; + +/// +/// Класс, описывающий ошибку выхода за границы коллекции +/// +[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) { } +} diff --git a/ProjectFighterJet/FormJetCollection.cs b/ProjectFighterJet/FormJetCollection.cs index 17baf7a..c7814c7 100644 --- a/ProjectFighterJet/FormJetCollection.cs +++ b/ProjectFighterJet/FormJetCollection.cs @@ -1,5 +1,7 @@ -using ProjectFighterJet.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectFighterJet.CollectionGenericObjects; using ProjectFighterJet.Drawnings; +using ProjectFighterJet.Exceptions; using System; using System.Collections.Generic; using System.ComponentModel; @@ -26,10 +28,15 @@ public partial class FormJetCollection : Form /// /// Конструктор /// - public FormJetCollection() + + private readonly ILogger _logger; + + public FormJetCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// /// Выбор компании @@ -48,14 +55,24 @@ public partial class FormJetCollection : Form private void SetJet(DrawningJet jet) { - if (_company + jet != -1) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company == null || jet == null) + { + return; + } + if (_company + jet != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + jet.GetDataForSave()); + } } - else + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } /// @@ -99,15 +116,19 @@ public partial class FormJetCollection : Form } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - int tempSize = FighterJetSharingService.getAmountOfObjects(); - 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); } } /// @@ -123,24 +144,28 @@ public partial class FormJetCollection : Form } DrawningJet? jet = null; int counter = 100; - while (jet == null) + try { - jet = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (jet == null) { - break; + jet = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } + + FormFighterJet form = new() + { + Setjet = jet + }; + form.ShowDialog(); } - if (jet == null) + catch (Exception ex) { - return; + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - FormFighterJet form = new() - { - Setjet = jet - }; - form.ShowDialog(); } /// /// Перерисовка коллекции @@ -164,17 +189,25 @@ public partial class FormJetCollection : Form MessageBoxButtons.OK, MessageBoxIcon.Error); 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) @@ -239,15 +272,16 @@ public partial class FormJetCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _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); } } } @@ -262,16 +296,17 @@ public partial class FormJetCollection : Form if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storageCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); 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); } } } diff --git a/ProjectFighterJet/Program.cs b/ProjectFighterJet/Program.cs index 31ba146..7059418 100644 --- a/ProjectFighterJet/Program.cs +++ b/ProjectFighterJet/Program.cs @@ -1,3 +1,8 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using NLog.Extensions.Logging; + namespace ProjectFighterJet { internal static class Program @@ -11,7 +16,21 @@ namespace ProjectFighterJet // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); - Application.Run(new FormJetCollection()); + + ServiceCollection services = new(); + ConfigureServices(services); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + Application.Run(serviceProvider.GetRequiredService()); + + } + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); } } } \ No newline at end of file diff --git a/ProjectFighterJet/ProjectFighterJet.csproj b/ProjectFighterJet/ProjectFighterJet.csproj index e23ec39..ebbf751 100644 --- a/ProjectFighterJet/ProjectFighterJet.csproj +++ b/ProjectFighterJet/ProjectFighterJet.csproj @@ -11,6 +11,9 @@ + + + diff --git a/ProjectFighterJet/nlog.config b/ProjectFighterJet/nlog.config new file mode 100644 index 0000000..49cc43e --- /dev/null +++ b/ProjectFighterJet/nlog.config @@ -0,0 +1,3 @@ + + + \ No newline at end of file