diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs index 67fc9f7..98901e5 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/AbstractCompany.cs @@ -35,7 +35,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); /// /// Конструктор @@ -101,7 +101,7 @@ public abstract class AbstractCompany DrawningShip? obj = _collection?.Get(i); obj?.DrawTransport(graphics); } - catch (ObjectNotFoundException) { }; + catch (Exception) { } } return bitmap; diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs index 11b35d1..0d261d8 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -27,7 +27,7 @@ public interface ICollectionGenericObjects /// /// Добавляемый объект /// /// Позиция /// true - вставка прошла удачно, false - вставка не удалась - bool Insert (T obj, int position); + int Insert (T obj, int position); /// /// Удаление объекта из коллекции с конктретной позиции diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs index a076684..e60b1c6 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ListGenericObjects.cs @@ -50,44 +50,37 @@ public class ListGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position < 0 || position >= _collection.Count) - throw new PositionOutOfCollectionException(position); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) { - if (_collection.Count + 1 <= _maxCount) - { - _collection.Add(obj); - return _collection.Count - 1; - } - return -1; - throw new CollectionOverflowException(MaxCount); + if (Count == _maxCount) throw new CollectionOverflowException(Count); + _collection.Add(obj); + return Count; } - public bool Insert(T obj, int position) + public int Insert(T obj, int position) { - if (_collection.Count + 1 > _maxCount || position < 0 || position >= _collection.Count) - return false; - if (_collection.Count + 1 > MaxCount) - throw new CollectionOverflowException(MaxCount); - if (position < 0 || position >= MaxCount) + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + + if (Count == _maxCount) + throw new CollectionOverflowException(Count); _collection.Insert(position, obj); - return true; + return position; + } public T Remove(int position) { - if (position < 0 || position >= _collection.Count) - return null; - throw new PositionOutOfCollectionException(position); - T temp = _collection[position]; + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); - return temp; + return obj; } - public IEnumerable GetItems() + public IEnumerable GetItems() { for (int i = 0; i < _collection.Count; ++i) { diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs index 3e7854d..a1f5e9b 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/MassiveGenericObjects.cs @@ -50,16 +50,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position < 0 || position >= _collection.Length) - throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) - throw new ObjectNotFoundException(position); + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } public int Insert(T obj) { - for (int i = 0; i < _collection.Length; i++) + for (int i = 0; i < Count; i++) { if (_collection[i] == null) { @@ -67,47 +65,51 @@ public class MassiveGenericObjects : ICollectionGenericObjects return i; } } - return -1; - throw new CollectionOverflowException(_collection.Length); + throw new CollectionOverflowException(Count); } - public bool Insert(T obj, int position) + public int Insert(T obj, int position) { - if (position < 0 || position >= _collection.Length) // проверка позиции - throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) // Попытка вставить на указанную позицию + if (position < 0 || position >= Count) + { + throw new PositionOutOfCollectionException(position); + } + if (_collection[position] == null) { _collection[position] = obj; - return true; + return position; } - for (int i = position; i < _collection.Length; i++) // попытка вставить объект на позицию после указанной + + for (int i = position + 1; i < Count; i++) { if (_collection[i] == null) { _collection[i] = obj; - return true; + return i; } } - for (int i = 0; i < position; i++) // попытка вставить объект на позицию до указанной + for (int i = position - 1; i >= 0; i--) { if (_collection[i] == null) { _collection[i] = obj; - return true; + return i; } } - throw new CollectionOverflowException(_collection.Length); + + throw new CollectionOverflowException(Count); } public T Remove(int position) { - if (position < 0 || position >= _collection.Length) // проверка позиции + if (position < 0 || position >= Count) + { throw new PositionOutOfCollectionException(position); - if (_collection[position] == null) - throw new ObjectNotFoundException(position); - T temp = _collection[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/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipSharingService.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipSharingService.cs index 2c56570..f8c3ffd 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipSharingService.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/ShipSharingService.cs @@ -19,6 +19,11 @@ public class ShipSharingService : AbstractCompany protected override void DrawBackground(Graphics g) { + Color backgroundColor = Color.SkyBlue; + using (Brush brush = new SolidBrush(backgroundColor)) + { + g.FillRectangle(brush, new Rectangle(0, 0, _pictureWidth, _pictureHeight)); + } Pen pen = new Pen(Color.Brown, 3); int offsetX = 10, offsetY = -12; int x = 1 + offsetX, y = _pictureHeight - _placeSizeHeight + offsetY; @@ -30,7 +35,7 @@ public class ShipSharingService : AbstractCompany { numCols++; g.DrawLine(pen, x, y, x + _placeSizeWidth / 2, y); - g.DrawLine(pen, x, y, x, y + _placeSizeHeight + 8); + g.DrawLine(pen, x, y, x, y + _placeSizeHeight + 4); locCoord.Add(new Tuple(x, y)); x += _placeSizeWidth + 2; } @@ -49,8 +54,12 @@ public class ShipSharingService : AbstractCompany int row = numRows - 1, col = numCols; for (int i = 0; i < _collection?.Count; i++, col--) { - _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); - _collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9); + try + { + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(locCoord[row * numCols - col].Item1 + 5, locCoord[row * numCols - col].Item2 + 9); + } + catch (Exception) { } if (col == 1) { col = numCols + 1; diff --git a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs index 4d3928b..c8b9e7d 100644 --- a/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/CollectionGenericObjects/StorageCollection.cs @@ -110,11 +110,11 @@ public class StorageCollection /// /// Путь и имя файла /// 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)) @@ -150,14 +150,9 @@ public class StorageCollection sb.Clear(); } } - return true; + } - /// - /// Загрузка информации по автомобилям в хранилище из файла - /// - /// Путь и имя файла - /// true - загрузка прошла успешно, false - ошибка при загрузке данных /// /// Загрузка информации по кораблям в хранилище из файла /// @@ -166,15 +161,17 @@ public class StorageCollection { if (!File.Exists(filename)) { - throw new FileNotFoundException("Файл не существует"); + throw new Exception("Файл не существует"); } using (StreamReader sr = new StreamReader(filename)) { string? str; str = sr.ReadLine(); + if (str == null || str.Length == 0) + throw new Exception("В файле нет данных"); if (str != _collectionKey.ToString()) - throw new FormatException("В файле неверные данные"); + throw new Exception("В файле неверные данные"); _storages.Clear(); while ((str = sr.ReadLine()) != null) { @@ -187,7 +184,7 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]); + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); @@ -195,18 +192,16 @@ public class StorageCollection string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningShip() is T ship) + if (elem?.CreateDrawningShip() is T boat) { try { - if (collection.Insert(ship) == -1) - { - throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]); - } + if (collection.Insert(boat) == -1) + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); } catch (CollectionOverflowException ex) { - throw new CollectionOverflowException("Коллекция переполнена", ex); + throw new Exception("Коллекция переполнена", ex); } } } diff --git a/ProjectContainerShip/ProjectContainerShip/Exceptions/CollectionOverflowException.cs b/ProjectContainerShip/ProjectContainerShip/Exceptions/CollectionOverflowException.cs index 586d959..235c302 100644 --- a/ProjectContainerShip/ProjectContainerShip/Exceptions/CollectionOverflowException.cs +++ b/ProjectContainerShip/ProjectContainerShip/Exceptions/CollectionOverflowException.cs @@ -14,12 +14,8 @@ namespace ProjectContainerShip.Exceptions; 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/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectNotFoundException.cs b/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectNotFoundException.cs index 93f264f..cbc18b2 100644 --- a/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectNotFoundException.cs +++ b/ProjectContainerShip/ProjectContainerShip/Exceptions/ObjectNotFoundException.cs @@ -14,12 +14,8 @@ namespace ProjectContainerShip.Exceptions; 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) { } } diff --git a/ProjectContainerShip/ProjectContainerShip/Exceptions/PositionOutOfCollectionException.cs b/ProjectContainerShip/ProjectContainerShip/Exceptions/PositionOutOfCollectionException.cs index 6ea9fc5..58196bd 100644 --- a/ProjectContainerShip/ProjectContainerShip/Exceptions/PositionOutOfCollectionException.cs +++ b/ProjectContainerShip/ProjectContainerShip/Exceptions/PositionOutOfCollectionException.cs @@ -13,13 +13,9 @@ namespace ProjectContainerShip.Exceptions; [Serializable] internal class PositionOutOfCollectionException : ApplicationException { - public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } - + 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/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs index 5436814..2e9d1a4 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs +++ b/ProjectContainerShip/ProjectContainerShip/FormShipCollection.cs @@ -35,6 +35,7 @@ namespace ProjectContainerShip InitializeComponent(); _storageCollection = new(); _logger = logger; + _logger.LogInformation("Форма загрузилась"); } #region Работа с компанией @@ -66,30 +67,26 @@ namespace ProjectContainerShip /// Добавление лодки в коллекцию /// /// - /// - /// Метод установки корабля в компанию - /// private void SetShip(DrawningShip? ship) { - if (_company == null) - return; try { + if (_company == null || ship == null) + { + return; + } + if (_company + ship != -1) { MessageBox.Show("Объект добавлен"); pictureBox.Image = _company.Show(); - _logger.LogInformation("Добавление корабля {ship} в коллекцию", ship); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - _logger.LogInformation("Не удалось добавить корабль {ship} в коллекцию", ship); + _logger.LogInformation("Добавлен объект: " + ship.GetDataForSave()); } } + catch (ObjectNotFoundException) { } catch (CollectionOverflowException ex) { - MessageBox.Show("Ошибка переполнения коллекции"); + MessageBox.Show("В коллекции превышено допустимое количество элементов"); _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -101,43 +98,32 @@ namespace ProjectContainerShip /// private void ButtonDelShip_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) - { - return; - } - - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - { - return; - } + int pos = Convert.ToInt32(maskedTextBoxPosition.Text); try { - int pos = Convert.ToInt32(maskedTextBoxPosition.Text); + if (string.IsNullOrEmpty(maskedTextBoxPosition.Text) || _company == null) + { + throw new Exception("Входные данные отсутствуют"); + } + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + { + return; + } + + if (_company - pos != null) { MessageBox.Show("Объект удален"); pictureBox.Image = _company.Show(); - _logger.LogInformation("Удаление корабля по индексу {pos}", pos); - } - else - { - MessageBox.Show("Не удалось удалить объект"); - _logger.LogInformation("Не удалось удалить корабль из коллекции по индексу {pos}", pos); + _logger.LogInformation("Объект удален"); } } - catch (ObjectNotFoundException ex) + catch (Exception ex) { - - MessageBox.Show("Ошибка: отсутствует объект"); + MessageBox.Show("Не найден объект по позиции " + pos); _logger.LogError("Ошибка: {Message}", ex.Message); } - catch (PositionOutOfCollectionException ex) - { - - MessageBox.Show("Ошибка: неправильная позиция"); - _logger.LogError("Ошибка: {Message}", ex.Message); - } - } /// @@ -154,24 +140,32 @@ namespace ProjectContainerShip DrawningShip? ship = null; int counter = 100; - while (ship == null) + try { - ship = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (ship == null) { - break; + ship = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } - } - if (ship == null) + if (ship == null) + { + return; + } + + FormContainerShip form = new FormContainerShip(); + form.SetShip = ship; + form.ShowDialog(); + } + catch (Exception ex) { - return; + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - FormContainerShip form = new FormContainerShip(); - form.SetShip = ship; - form.ShowDialog(); } /// @@ -242,16 +236,27 @@ namespace ProjectContainerShip /// private void ButtonCollectionDel_Click(object sender, EventArgs e) { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null) { MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - return; - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - _logger.LogInformation("Удаление коллекции с названием {name}", listBoxCollection.SelectedItem.ToString()); - RefreshListBoxItems(); + + try + { + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RefreshListBoxItems(); + _logger.LogInformation("Удалена коллекция: ", listBoxCollection.SelectedItem.ToString()); + } + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } /// @@ -294,6 +299,7 @@ namespace ProjectContainerShip /// private void saveToolStripMenuItem_Click(object sender, EventArgs e) { + if (saveFileDialog.ShowDialog() == DialogResult.OK) { try { @@ -303,7 +309,7 @@ namespace ProjectContainerShip } catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } } diff --git a/ProjectContainerShip/ProjectContainerShip/FormShipConfig.cs b/ProjectContainerShip/ProjectContainerShip/FormShipConfig.cs index 5bd4f02..2a98d13 100644 --- a/ProjectContainerShip/ProjectContainerShip/FormShipConfig.cs +++ b/ProjectContainerShip/ProjectContainerShip/FormShipConfig.cs @@ -145,9 +145,9 @@ public partial class FormShipConfig : Form private void labelAdditionalColor_DragDrop(object sender, DragEventArgs e) { - if (_ship?.EntityShip is EntityContainerShip _catamaran) + if (_ship?.EntityShip is EntityContainerShip _containerShip) { - _catamaran.SetAdditionalColor((Color)e.Data.GetData(typeof(Color))); + _containerShip.SetAdditionalColor((Color)e.Data.GetData(typeof(Color))); } DrawObject(); diff --git a/ProjectContainerShip/ProjectContainerShip/Program.cs b/ProjectContainerShip/ProjectContainerShip/Program.cs index ccbabc9..c4c3877 100644 --- a/ProjectContainerShip/ProjectContainerShip/Program.cs +++ b/ProjectContainerShip/ProjectContainerShip/Program.cs @@ -23,20 +23,19 @@ namespace ProjectContainerShip } private static void ConfigureServices(ServiceCollection services) { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + services.AddSingleton() .AddLogging(option => { - var configuration = new ConfigurationBuilder() - .SetBasePath(Directory.GetCurrentDirectory()) - .AddJsonFile(path: "C:\\Users\\\\Desktop\\\\\\1 \\2\\OOP\\Lab\\ProjectContainerShip\\ProjectContainerShip\\appSetting.json", optional: false, reloadOnChange: true) - .Build(); - - var logger = new LoggerConfiguration() - .ReadFrom.Configuration(configuration) - .CreateLogger(); - option.SetMinimumLevel(LogLevel.Information); - option.AddSerilog(logger); + option.AddSerilog(new LoggerConfiguration().ReadFrom.Configuration(new ConfigurationBuilder(). + AddJsonFile($"{pathNeed}appSetting.json").Build()).CreateLogger()); }); } } diff --git a/ProjectContainerShip/ProjectContainerShip/appSetting.json b/ProjectContainerShip/ProjectContainerShip/appSetting.json index d39f3a5..b947cc8 100644 --- a/ProjectContainerShip/ProjectContainerShip/appSetting.json +++ b/ProjectContainerShip/ProjectContainerShip/appSetting.json @@ -1,20 +1,15 @@ { "Serilog": { "Using": [ "Serilog.Sinks.File" ], - "MinimumLevel": "Information", + "MinimumLevel": "Debug", "WriteTo": [ { "Name": "File", - "Args": { - "path": "Logs/log_.log", - "rollingInterval": "Day", - "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" - } + "Args": { "path": "log.log" } } ], - "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], "Properties": { - "Application": "ContainerShip" + "Applicatoin": "Sample" } } } \ No newline at end of file