From c24f435746be853808bff8bec1a8e3b27e055bf5 Mon Sep 17 00:00:00 2001 From: "Valitov.Damir" Date: Fri, 21 Apr 2023 23:04:27 +0400 Subject: [PATCH] lab7 done --- Sailboat/Boat.cs | 1 - Sailboat/BoatNotFoundException.cs | 19 +++++ Sailboat/DrawingObjectBoat.cs | 4 + Sailboat/ExtentionBoat.cs | 42 +++++++++ Sailboat/FormMapWithSetBoats.Designer.cs | 76 +++++++++++++++-- Sailboat/FormMapWithSetBoats.cs | 104 +++++++++++++++++++---- Sailboat/FormMapWithSetBoats.resx | 9 ++ Sailboat/IDrawingObject.cs | 5 ++ Sailboat/MapWithSetBoatsGeneric.cs | 17 ++++ Sailboat/MapsCollection.cs | 71 +++++++++++++++- Sailboat/Program.cs | 35 ++++++-- Sailboat/Sailboat.csproj | 26 ++++++ Sailboat/SetBoatsGeneric.cs | 8 ++ Sailboat/StorageOverflowException.cs | 19 +++++ Sailboat/serilog.json | 16 ++++ 15 files changed, 418 insertions(+), 34 deletions(-) create mode 100644 Sailboat/BoatNotFoundException.cs create mode 100644 Sailboat/ExtentionBoat.cs create mode 100644 Sailboat/StorageOverflowException.cs create mode 100644 Sailboat/serilog.json diff --git a/Sailboat/Boat.cs b/Sailboat/Boat.cs index 44b059d..421db56 100644 --- a/Sailboat/Boat.cs +++ b/Sailboat/Boat.cs @@ -40,7 +40,6 @@ namespace Sailboat { BodyColor = newBaseColor; } - } } diff --git a/Sailboat/BoatNotFoundException.cs b/Sailboat/BoatNotFoundException.cs new file mode 100644 index 0000000..f4568da --- /dev/null +++ b/Sailboat/BoatNotFoundException.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 Sailboat +{ + [Serializable] + internal class BoatNotFoundException : ApplicationException + { + public BoatNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } + public BoatNotFoundException() : base() { } + public BoatNotFoundException(string message) : base(message) { } + public BoatNotFoundException(string message, Exception exception) : base(message, exception) { } + protected BoatNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } + } +} diff --git a/Sailboat/DrawingObjectBoat.cs b/Sailboat/DrawingObjectBoat.cs index ba6dfc1..d03c75e 100644 --- a/Sailboat/DrawingObjectBoat.cs +++ b/Sailboat/DrawingObjectBoat.cs @@ -36,5 +36,9 @@ namespace Sailboat { _boat.SetPosition(x, y, width, height); } + + public string GetInfo() => _boat?.GetDataForSave(); + + public static IDrawingObject Create(string data) => new DrawingObjectBoat(data.CreateDrawningBoat()); } } diff --git a/Sailboat/ExtentionBoat.cs b/Sailboat/ExtentionBoat.cs new file mode 100644 index 0000000..fc43455 --- /dev/null +++ b/Sailboat/ExtentionBoat.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Sailboat +{ + internal static class ExtentionBoat + { + private static readonly char _separatorForObject = ':'; + public static DrawingBoat CreateDrawningBoat(this string info) + { + string[] strs = info.Split(_separatorForObject); + if (strs.Length == 3) + { + return new DrawingBoat(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2])); + } + if (strs.Length == 6) + { + return new DrawingSailboat(Convert.ToInt32(strs[0]), + Convert.ToInt32(strs[1]), Color.FromName(strs[2]), + Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), + Convert.ToBoolean(strs[5])); + } + return null; + } + public static string GetDataForSave(this DrawingBoat drawingBoat) + { + var boat = drawingBoat.Boat; + var str = $"{boat.Speed}{_separatorForObject}{boat.Weight}{_separatorForObject}{boat.BodyColor.Name}"; + if (boat is not Sailboat sailboat) + { + return str; + } + return $"{str}{_separatorForObject}{sailboat.EdgeColor.Name}{_separatorForObject}{sailboat.Sail}{_separatorForObject}{sailboat.ExtendedBody}"; + } + } +} + diff --git a/Sailboat/FormMapWithSetBoats.Designer.cs b/Sailboat/FormMapWithSetBoats.Designer.cs index d05dcce..90150aa 100644 --- a/Sailboat/FormMapWithSetBoats.Designer.cs +++ b/Sailboat/FormMapWithSetBoats.Designer.cs @@ -46,9 +46,16 @@ namespace Sailboat this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox(); this.btn_add_boat = new System.Windows.Forms.Button(); this.pictureBox = new System.Windows.Forms.PictureBox(); + this.menuStrip = new System.Windows.Forms.MenuStrip(); + this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); + this.saveFileDialog = new System.Windows.Forms.SaveFileDialog(); this.groupBoxTools.SuspendLayout(); this.groupBoxMaps.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); + this.menuStrip.SuspendLayout(); this.SuspendLayout(); // // groupBoxTools @@ -64,9 +71,9 @@ namespace Sailboat this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition); this.groupBoxTools.Controls.Add(this.btn_add_boat); this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right; - this.groupBoxTools.Location = new System.Drawing.Point(707, 0); + this.groupBoxTools.Location = new System.Drawing.Point(707, 28); this.groupBoxTools.Name = "groupBoxTools"; - this.groupBoxTools.Size = new System.Drawing.Size(250, 609); + this.groupBoxTools.Size = new System.Drawing.Size(250, 581); this.groupBoxTools.TabIndex = 0; this.groupBoxTools.TabStop = false; this.groupBoxTools.Text = "Инструменты"; @@ -138,7 +145,7 @@ namespace Sailboat this.btn_left.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btn_left.BackgroundImage = global::Sailboat.Properties.Resources.left; this.btn_left.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; - this.btn_left.Location = new System.Drawing.Point(19, 552); + this.btn_left.Location = new System.Drawing.Point(19, 524); this.btn_left.Name = "btn_left"; this.btn_left.Size = new System.Drawing.Size(70, 40); this.btn_left.TabIndex = 11; @@ -150,7 +157,7 @@ namespace Sailboat this.btn_up.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btn_up.BackgroundImage = global::Sailboat.Properties.Resources.up; this.btn_up.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; - this.btn_up.Location = new System.Drawing.Point(95, 506); + this.btn_up.Location = new System.Drawing.Point(95, 478); this.btn_up.Name = "btn_up"; this.btn_up.Size = new System.Drawing.Size(75, 40); this.btn_up.TabIndex = 10; @@ -162,7 +169,7 @@ namespace Sailboat this.btn_down.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btn_down.BackgroundImage = global::Sailboat.Properties.Resources.down; this.btn_down.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; - this.btn_down.Location = new System.Drawing.Point(95, 552); + this.btn_down.Location = new System.Drawing.Point(95, 524); this.btn_down.Name = "btn_down"; this.btn_down.Size = new System.Drawing.Size(75, 40); this.btn_down.TabIndex = 9; @@ -174,7 +181,7 @@ namespace Sailboat this.btn_right.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btn_right.BackgroundImage = global::Sailboat.Properties.Resources.right; this.btn_right.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom; - this.btn_right.Location = new System.Drawing.Point(174, 552); + this.btn_right.Location = new System.Drawing.Point(174, 524); this.btn_right.Name = "btn_right"; this.btn_right.Size = new System.Drawing.Size(70, 40); this.btn_right.TabIndex = 8; @@ -232,12 +239,54 @@ namespace Sailboat // pictureBox // this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill; - this.pictureBox.Location = new System.Drawing.Point(0, 0); + this.pictureBox.Location = new System.Drawing.Point(0, 28); this.pictureBox.Name = "pictureBox"; - this.pictureBox.Size = new System.Drawing.Size(707, 609); + this.pictureBox.Size = new System.Drawing.Size(707, 581); this.pictureBox.TabIndex = 0; this.pictureBox.TabStop = false; // + // menuStrip + // + this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20); + this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.файлToolStripMenuItem}); + this.menuStrip.Location = new System.Drawing.Point(0, 0); + this.menuStrip.Name = "menuStrip"; + this.menuStrip.Size = new System.Drawing.Size(957, 28); + this.menuStrip.TabIndex = 1; + this.menuStrip.Text = "menuStrip"; + // + // файлToolStripMenuItem + // + this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.SaveToolStripMenuItem, + this.LoadToolStripMenuItem}); + this.файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + this.файлToolStripMenuItem.Size = new System.Drawing.Size(59, 24); + this.файлToolStripMenuItem.Text = "Файл"; + // + // SaveToolStripMenuItem + // + this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + this.SaveToolStripMenuItem.Text = "Сохранение"; + this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); + // + // LoadToolStripMenuItem + // + this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; + this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26); + this.LoadToolStripMenuItem.Text = "Загрузка"; + this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click); + // + // openFileDialog + // + this.openFileDialog.Filter = "txt file | *.txt"; + // + // saveFileDialog + // + this.saveFileDialog.Filter = "txt file | *.txt"; + // // FormMapWithSetBoats // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); @@ -245,6 +294,8 @@ namespace Sailboat this.ClientSize = new System.Drawing.Size(957, 609); this.Controls.Add(this.pictureBox); this.Controls.Add(this.groupBoxTools); + this.Controls.Add(this.menuStrip); + this.MainMenuStrip = this.menuStrip; this.Name = "FormMapWithSetBoats"; this.Text = "FormMapWithSetBoats"; this.groupBoxTools.ResumeLayout(false); @@ -252,7 +303,10 @@ namespace Sailboat this.groupBoxMaps.ResumeLayout(false); this.groupBoxMaps.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); + this.menuStrip.ResumeLayout(false); + this.menuStrip.PerformLayout(); this.ResumeLayout(false); + this.PerformLayout(); } @@ -275,5 +329,11 @@ namespace Sailboat private System.Windows.Forms.Button btn_delete_map; private System.Windows.Forms.ListBox listBoxMaps; private System.Windows.Forms.Button btn_add_map; + private System.Windows.Forms.MenuStrip menuStrip; + private System.Windows.Forms.ToolStripMenuItem файлToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem SaveToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem LoadToolStripMenuItem; + private System.Windows.Forms.OpenFileDialog openFileDialog; + private System.Windows.Forms.SaveFileDialog saveFileDialog; } } \ No newline at end of file diff --git a/Sailboat/FormMapWithSetBoats.cs b/Sailboat/FormMapWithSetBoats.cs index 5e85d58..735b389 100644 --- a/Sailboat/FormMapWithSetBoats.cs +++ b/Sailboat/FormMapWithSetBoats.cs @@ -1,5 +1,6 @@ -using System; + using System; using System.Collections.Generic; +using Microsoft.Extensions.Logging; using System.ComponentModel; using System.Data; using System.Drawing; @@ -12,16 +13,19 @@ namespace Sailboat { public partial class FormMapWithSetBoats : Form { - private readonly Dictionary _mapsDict = new Dictionary() { + private readonly Dictionary _mapsDict = new Dictionary() + { { "Простая карта", new SimpleMap() }, { "Водная карта", new WaterMap() } }; private readonly MapsCollection _mapsCollection; + private ILogger _logger; - public FormMapWithSetBoats() + public FormMapWithSetBoats(ILogger logger) { InitializeComponent(); + _logger = logger; _mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height); comboBoxMapSelector.Items.Clear(); foreach (var item in _mapsDict) @@ -66,14 +70,30 @@ namespace Sailboat return; } int pos = Convert.ToInt32(maskedTextBoxPosition.Text); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + var deletedBoat = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos; + if (deletedBoat != null) + { + MessageBox.Show("Объект удален"); + _logger.LogInformation("Из текущей карты удалён объект {@Tanker}", deletedBoat); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + _logger.LogWarning("Не удалось удалить объект по позиции {0}. Объект равен null", pos); + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (BoatNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + _logger.LogWarning("Ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Ошибка удаления: {ex.Message}"); + } + catch (Exception ex) + { + _logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message); + MessageBox.Show($"Неизвестная ошибка: {ex.Message}"); } } @@ -127,20 +147,24 @@ namespace Sailboat if (comboBoxMapSelector.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("При добавлении карты {0}", comboBoxMapSelector.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта"); return; } if (!_mapsDict.ContainsKey(comboBoxMapSelector.Text)) { MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Отсутствует карта с типом {0}", comboBoxMapSelector.Text); return; } _mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxMapSelector.Text]); ReloadMaps(); + _logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}"); } private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e) { pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); } private void btn_delete_map_Click(object sender, EventArgs e) @@ -152,25 +176,73 @@ namespace Sailboat if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { + _logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty); _mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty); ReloadMaps(); } } private void InsertBoatCheck(DrawingBoat _boat) { - if (listBoxMaps.SelectedIndex == -1) + try { - return; + if (listBoxMaps.SelectedIndex == -1) + { + return; + } + DrawingObjectBoat boat = new(_boat); + if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0) + { + MessageBox.Show("Объект добавлен"); + _logger.LogInformation("Добавлен объект {@Tanker}", _boat); + pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + } + else + { + MessageBox.Show("Не удалось добавить объект"); + _logger.LogWarning("Не удалось добавить объект"); + } } - DrawingObjectBoat boat = new(_boat); - if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0) + catch (StorageOverflowException ex) { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet(); + _logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message); + MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - else + } + + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) { - MessageBox.Show("Не удалось добавить объект"); + try + { + _mapsCollection.SaveData(saveFileDialog.FileName); + _logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + MessageBox.Show($"Не сохранилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message); + } + } + } + + private void LoadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _mapsCollection.LoadData(openFileDialog.FileName); + _logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName); + ReloadMaps(); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + catch (Exception ex) + { + _logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message); + MessageBox.Show($"Не загрузилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } } } diff --git a/Sailboat/FormMapWithSetBoats.resx b/Sailboat/FormMapWithSetBoats.resx index f298a7b..985a3e4 100644 --- a/Sailboat/FormMapWithSetBoats.resx +++ b/Sailboat/FormMapWithSetBoats.resx @@ -57,4 +57,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 144, 17 + + + 311, 17 + \ No newline at end of file diff --git a/Sailboat/IDrawingObject.cs b/Sailboat/IDrawingObject.cs index ea74317..699cb05 100644 --- a/Sailboat/IDrawingObject.cs +++ b/Sailboat/IDrawingObject.cs @@ -37,5 +37,10 @@ namespace Sailboat /// /// (float Left, float Right, float Top, float Bottom) GetCurrentPosition(); + + /// + /// Получение информации по объекту + /// + string GetInfo(); } } diff --git a/Sailboat/MapWithSetBoatsGeneric.cs b/Sailboat/MapWithSetBoatsGeneric.cs index 9abe3dd..9a9ba2d 100644 --- a/Sailboat/MapWithSetBoatsGeneric.cs +++ b/Sailboat/MapWithSetBoatsGeneric.cs @@ -132,5 +132,22 @@ namespace Sailboat if (currentHeight > height) return; } } + + public string GetData(char separatorType, char separatorData) + { + string data = $"{_map.GetType().Name}{separatorType}"; + foreach (var boat in _setBoats.GetBoats()) + { + data += $"{boat.GetInfo()}{separatorData}"; + } + return data; + } + public void LoadData(string[] records) + { + foreach (var rec in records) + { + _setBoats.Insert(DrawingObjectBoat.Create(rec) as T); + } + } } } diff --git a/Sailboat/MapsCollection.cs b/Sailboat/MapsCollection.cs index 84f5969..d1f13c6 100644 --- a/Sailboat/MapsCollection.cs +++ b/Sailboat/MapsCollection.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; @@ -8,7 +9,7 @@ namespace Sailboat { internal class MapsCollection { - readonly Dictionary> _mapStorages; + readonly Dictionary> _mapStorages; public List Keys => _mapStorages.Keys.ToList(); @@ -16,9 +17,12 @@ namespace Sailboat private readonly int _pictureHeight; + private readonly char separatorDict = '|'; + private readonly char separatorData = ';'; + public MapsCollection(int pictureWidth, int pictureHeight) { - _mapStorages = new Dictionary>(); + _mapStorages = new Dictionary>(); _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } @@ -26,7 +30,7 @@ namespace Sailboat public void AddMap(string name, AbstractMap map) { if (Keys.Contains(name)) return; - _mapStorages.Add(name, new MapWithSetBoatsGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages.Add(name, new MapWithSetBoatsGeneric(_pictureWidth, _pictureHeight, map)); } public void DelMap(string name) @@ -34,7 +38,7 @@ namespace Sailboat _mapStorages.Remove(name); } - public MapWithSetBoatsGeneric this[string ind] + public MapWithSetBoatsGeneric this[string ind] { get { @@ -42,5 +46,64 @@ namespace Sailboat return result; } } + + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// + public void SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + using (StreamWriter sw = new(filename)) + { + sw.Write($"MapsCollection{Environment.NewLine}"); + foreach (var storage in _mapStorages) + { + sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}"); + } + } + } + + /// + /// Загрузка нформации по автомобилям на парковках из файла + /// + /// + /// + public void LoadData(string filename) + { + if (!File.Exists(filename)) + { + throw new FileNotFoundException("Файл не найден"); + } + using (StreamReader sr = new(filename)) + { + string str = ""; + if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection")) + { + throw new FileFormatException("Формат данных в файле не правильный"); + } + _mapStorages.Clear(); + while ((str = sr.ReadLine()) != null) + { + var tempElem = str.Split(separatorDict); + AbstractMap map = null; + switch (tempElem[1]) + { + case "SimpleMap": + map = new SimpleMap(); + break; + case "WaterMap": + map = new WaterMap(); + break; + } + _mapStorages.Add(tempElem[0], new MapWithSetBoatsGeneric(_pictureWidth, _pictureHeight, map)); + _mapStorages[tempElem[0]].LoadData(tempElem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries)); + } + } + } } } diff --git a/Sailboat/Program.cs b/Sailboat/Program.cs index be522c6..71eefd0 100644 --- a/Sailboat/Program.cs +++ b/Sailboat/Program.cs @@ -1,7 +1,9 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Serilog; using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; +using System.IO; using System.Windows.Forms; namespace Sailboat @@ -17,7 +19,30 @@ namespace Sailboat Application.SetHighDpiMode(HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new FormMapWithSetBoats()); + 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 => + { + var configuration = new ConfigurationBuilder() + .SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: "serilog.json") + .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/Sailboat/Sailboat.csproj b/Sailboat/Sailboat.csproj index 1e26462..1da5513 100644 --- a/Sailboat/Sailboat.csproj +++ b/Sailboat/Sailboat.csproj @@ -6,4 +6,30 @@ true + + + + + + + Always + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Sailboat/SetBoatsGeneric.cs b/Sailboat/SetBoatsGeneric.cs index 08ba651..5f39a19 100644 --- a/Sailboat/SetBoatsGeneric.cs +++ b/Sailboat/SetBoatsGeneric.cs @@ -28,6 +28,10 @@ namespace Sailboat public int Insert(T boat, int position) { + if (Count == _maxCount) + { + throw new StorageOverflowException(_maxCount); + } if (position < 0 || position >= _maxCount || BusyPlaces == _maxCount) { return -1; @@ -39,6 +43,10 @@ namespace Sailboat public T Remove(int position) { + if (position >= Count || position < 0) + { + throw new BoatNotFoundException(position); + } if (position < 0 || position >= _maxCount) { return null; diff --git a/Sailboat/StorageOverflowException.cs b/Sailboat/StorageOverflowException.cs new file mode 100644 index 0000000..900ce19 --- /dev/null +++ b/Sailboat/StorageOverflowException.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 Sailboat +{ + [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 context) : base(info, context) { } + } +} diff --git a/Sailboat/serilog.json b/Sailboat/serilog.json new file mode 100644 index 0000000..5697fff --- /dev/null +++ b/Sailboat/serilog.json @@ -0,0 +1,16 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "log.log", + "rollingInterval": "Day" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ] + } +} \ No newline at end of file