diff --git a/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj b/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj index 70b4ca1..ebc4659 100644 --- a/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj +++ b/AntiAircraftGun/AntiAircraftGun/AntiAircraftGun.csproj @@ -11,6 +11,8 @@ + + \ No newline at end of file diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs index 0c30f55..b115d09 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/AbstractCompany.cs @@ -51,7 +51,7 @@ public abstract class AbstractCompany /// public static bool operator +(AbstractCompany company, DrawningGun gun) { - return company._collection?.Insert(gun) ?? false; + return company._collection.Insert(gun); } /// @@ -62,7 +62,7 @@ public abstract class AbstractCompany /// public static bool operator -(AbstractCompany company, int position) { - return company._collection?.Remove(position) ?? false; + return company._collection.Remove(position); } /// diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs index ccabac6..d8b97cb 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using AntiAircraftGun.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -32,15 +33,21 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { // TODO проверка позиции + // TODO выброс ошибки, если выход за границу + // +- if (!_collection.Any()) { return null; } - if (_collection.Count <= position || position < 0 || position >= _maxCount) { return null; } + if (_collection.Count <= position || position < 0 || position >= _maxCount) { + throw new PostiionOutOfCollectionException(Count); + } return _collection[position]; } public bool Insert(T obj) { // TODO проверка, что не превышено максимальное количество элементов // TODO вставка в конец набора - if (_collection.Count>=_maxCount) return false; + // TODO выброс ошибки, если переполнение + // +- + if (_collection.Count>=_maxCount) throw new CollectionOverflowExecption(_maxCount); _collection.Add(obj); return true; } @@ -49,7 +56,11 @@ public class ListGenericObjects : ICollectionGenericObjects // TODO проверка, что не превышено максимальное количество элементов // TODO проверка позиции // TODO вставка по позиции - if (_collection.Count >= _maxCount || _collection[position] == null || position < 0) { return false; } + // TODO выброс ошибки, если выход за границу + // TODO выброс ошибки, если переполнение + // +- + if (Count>=_maxCount) throw new CollectionOverflowExecption(_maxCount); + if (position >= Count || position < 0) { throw new PostiionOutOfCollectionException(position); } _collection.Insert(position, obj); return true; } @@ -57,6 +68,9 @@ public class ListGenericObjects : ICollectionGenericObjects { // TODO проверка позиции // TODO удаление объекта из списка + // TODO выброс ошибки, если выход за границу массива + // +- + if(position < 0 || position >= _maxCount) throw new PostiionOutOfCollectionException(position); if (_collection[position] == null) { return false; diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs index a4dc4bb..a701d5d 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,6 @@ -using System.Diagnostics; +using AntiAircraftGun.Exceptions; +using System.Data.Entity.Core; +using System.Diagnostics; namespace AntiAircraftGun.CollectionGenericObjects; /// @@ -44,19 +46,29 @@ internal class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { // TODO проверка позиции + // TODO выброс ошибки, если переполнение + // TODO выброс ошибки, если пустой + // +- if (_collection[position] == null) - return null; + { + throw new Exceptions.ObjectNotFoundException(position); + } + if (position >= _collection.Length || position<0) + { + throw new PostiionOutOfCollectionException(position); + } return _collection[position]; } public bool Insert(T obj) { // TODO вставка в свободное место набора + // TODO выброс ошибки, если переполнение for (int i = 0; i < Count; i++) { if (InsertingElementCollection(i, obj)) return true; } - return false; + throw new CollectionOverflowExecption(Count); } public bool Insert(T obj, int position) { @@ -65,6 +77,13 @@ internal class MassiveGenericObjects : ICollectionGenericObjects // ищется свободное место после этой позиции и идет вставка туда // если нет после, ищем до // TODO вставка + // TODO выброс ошибки, если переполнение + // TODO выброс ошибки, если выход за границу массива + // +- + if(position>=_collection.Length||position<0) + { + throw new PostiionOutOfCollectionException(position); + } if (InsertingElementCollection(position, obj)) return true; for (int i = position + 1; i < Count; i++) @@ -77,13 +96,17 @@ internal class MassiveGenericObjects : ICollectionGenericObjects if (InsertingElementCollection(i, obj)) return true; } - return false; + throw new CollectionOverflowExecption(Count); } public bool Remove(int position) { // TODO проверка позиции // TODO удаление объекта из массива, присвоив элементу массива значение null - if (_collection[position] == null) return false; + // TODO выброс ошибки, если выход за границу + // TODO выброс ошибки, если пустой + // +- + if(position >= _collection.Length || position < 0) throw new PostiionOutOfCollectionException(position); + if (_collection[position] == null) throw new Exceptions.ObjectNotFoundException(position); _collection[position] = null; return true; } diff --git a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs index 1097ec3..e7c29a2 100644 --- a/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs +++ b/AntiAircraftGun/AntiAircraftGun/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using AntiAircraftGun.Drawnings; +using AntiAircraftGun.Exceptions; using System.Text; namespace AntiAircraftGun.CollectionGenericObjects; @@ -82,15 +83,14 @@ where T : DrawningGun /// Запись информации в файл /// /// - /// - public bool SaveData(string filename) + public void SaveData(string filename) { if(File.Exists(filename)) { File.Delete(filename); } - if(_storages.Count==0) return false; + if(_storages.Count==0) throw new Exception("В хранилище отсутсвуют коллекции для сохранения"); StringBuilder sb = new(); sb.Append(_collectionKey); @@ -117,30 +117,28 @@ where T : DrawningGun using FileStream fs=new(filename, FileMode.Create); byte[] info=new UTF8Encoding(true).GetBytes(sb.ToString()); fs.Write(info, 0, info.Length); - return true; } /// /// Загрузка информации по установкам в хранилище из файла /// /// - /// - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } using (StreamReader reader = File.OpenText(filename)) { string str = reader.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 = ""; @@ -155,7 +153,7 @@ where T : DrawningGun 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); @@ -163,15 +161,21 @@ where T : DrawningGun { if (elem?.CreateDrawningCun() is T gun) { - if (!collection.Insert(gun)) + try { - return false; + if (!collection.Insert(gun)) + { + throw new Exception("Объект не удалось добавить в коллекию: " + record[3]); + } + } + catch (CollectionOverflowExecption ex) + { + throw new Exception("Коллекция переполнена",ex); } } } _storages.Add(record[0], collection); } - return true; } } diff --git a/AntiAircraftGun/AntiAircraftGun/Drawnings/ExtentionDrawningGun.cs b/AntiAircraftGun/AntiAircraftGun/Drawnings/ExtentionDrawningGun.cs index d7f685f..3e5e870 100644 --- a/AntiAircraftGun/AntiAircraftGun/Drawnings/ExtentionDrawningGun.cs +++ b/AntiAircraftGun/AntiAircraftGun/Drawnings/ExtentionDrawningGun.cs @@ -25,6 +25,7 @@ public static class ExtentionDrawningGun } gun = EntityGun.CreateEntityCar(strs); if (gun != null) + { return new DrawningGun(gun); } diff --git a/AntiAircraftGun/AntiAircraftGun/Exceptions/CollectionOverflowExecption.cs b/AntiAircraftGun/AntiAircraftGun/Exceptions/CollectionOverflowExecption.cs new file mode 100644 index 0000000..18a539a --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/Exceptions/CollectionOverflowExecption.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Data.Entity.Core.Mapping; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Exceptions; +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +public class CollectionOverflowExecption : ApplicationException +{ + public CollectionOverflowExecption(int count) : base("В коллекции превышено допустимое кол-во: count " + count) { } + public CollectionOverflowExecption() : base() { } + public CollectionOverflowExecption(string message) : base(message) { } + public CollectionOverflowExecption(string message, Exception innerException) : base(message, innerException) { } + protected CollectionOverflowExecption(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/AntiAircraftGun/AntiAircraftGun/Exceptions/ObjectNotFoundException.cs b/AntiAircraftGun/AntiAircraftGun/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..c0e345b --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Exceptions; +[Serializable] +public class ObjectNotFoundException: ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + public ObjectNotFoundException() : base() { } + public ObjectNotFoundException(string message) : base(message) { } + public ObjectNotFoundException(string message, Exception innerException) : base(message, innerException) { } + protected ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/AntiAircraftGun/AntiAircraftGun/Exceptions/PostiionOutOfCollectionException.cs b/AntiAircraftGun/AntiAircraftGun/Exceptions/PostiionOutOfCollectionException.cs new file mode 100644 index 0000000..e40c04c --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/Exceptions/PostiionOutOfCollectionException.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace AntiAircraftGun.Exceptions; + +public class PostiionOutOfCollectionException:ApplicationException +{ + public PostiionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } + public PostiionOutOfCollectionException() : base() { } + public PostiionOutOfCollectionException(string message) : base(message) { } + public PostiionOutOfCollectionException(string message, Exception innerException) : base(message, innerException) { } + protected PostiionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} diff --git a/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs b/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs index 60bd96b..2b7884e 100644 --- a/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs +++ b/AntiAircraftGun/AntiAircraftGun/FormGunCollections.cs @@ -1,11 +1,17 @@ using AntiAircraftGun.CollectionGenericObjects; using AntiAircraftGun.Drawnings; +using AntiAircraftGun.Exceptions; +using Microsoft.Extensions.Logging; +using System.Data.Entity.Core; namespace AntiAircraftGun; public partial class FormGunCollections : Form { - + /// + /// Логер + /// + private readonly ILogger _logger; private readonly StorageCollection _storageCollection; /// /// Компания @@ -14,10 +20,12 @@ public partial class FormGunCollections : Form /// /// Конструктор /// - public FormGunCollections() + public FormGunCollections(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } /// /// @@ -48,15 +56,21 @@ public partial class FormGunCollections : Form /// private void SetGun(DrawningGun gun) { - if (_company == null || gun == null) { return; } - if (_company + gun) + try { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); + if (_company == null || gun == null) { return; } + if (_company + gun) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + gun.GetDataForSave()); + } } - else + catch (Exceptions.ObjectNotFoundException) { } + catch (CollectionOverflowExecption ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -77,14 +91,19 @@ public partial class FormGunCollections : Form } if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + if (_company - pos) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удален объект по позиции " + pos); + } } - else + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -102,25 +121,32 @@ public partial class FormGunCollections : Form DrawningGun? gun = null; int counter = 100; - while (gun == null) + try { - gun = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (gun == null) { - break; + gun = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + if (gun == null) + { + return; } - } - if (gun == null) - { - return; - } - FormAntiAircraftGun form = new() + FormAntiAircraftGun form = new() + { + SetGun = gun, + }; + form.ShowDialog(); + } + catch (Exception ex) { - SetGun = gun, - }; - form.ShowDialog(); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } /// @@ -150,18 +176,26 @@ public partial class FormGunCollections : 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(); } /// /// Удаление коллекции @@ -175,8 +209,20 @@ public partial class FormGunCollections : Form MessageBox.Show("Коллекция для удаления не выбрана"); return; } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); + try + { + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); + } } /// /// Создание компании @@ -232,8 +278,17 @@ listBoxCollection.SelectedItem == null) { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - else MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + try + { + _storageCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); + } } } /// @@ -244,18 +299,20 @@ listBoxCollection.SelectedItem == null) private void DownloadToolStripMenuItem_Click(object sender, EventArgs e) { //TODO продумать логику + // TODO Логирование 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/AntiAircraftGun/AntiAircraftGun/Program.cs b/AntiAircraftGun/AntiAircraftGun/Program.cs index 948a487..3b9ba36 100644 --- a/AntiAircraftGun/AntiAircraftGun/Program.cs +++ b/AntiAircraftGun/AntiAircraftGun/Program.cs @@ -1,3 +1,6 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + namespace AntiAircraftGun { internal static class Program @@ -10,8 +13,39 @@ namespace AntiAircraftGun { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. + ServiceCollection services = new(); + ConfigureServices(services); ApplicationConfiguration.Initialize(); - Application.Run(new FormGunCollections()); + 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"); + //}); + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddSerilog(new LoggerConfiguration() + .ReadFrom.Configuration(new ConfigurationBuilder() + .AddJsonFile($"{pathNeed}serilog.json") + .Build()) + .CreateLogger()); + }); } } } \ No newline at end of file diff --git a/AntiAircraftGun/AntiAircraftGun/serilog.json b/AntiAircraftGun/AntiAircraftGun/serilog.json new file mode 100644 index 0000000..21a6582 --- /dev/null +++ b/AntiAircraftGun/AntiAircraftGun/serilog.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file