From dc45fbd65d419e82369e4409d8f8f740010d7fe5 Mon Sep 17 00:00:00 2001 From: "yuliya.mavrina@internet.ru" Date: Mon, 27 Nov 2023 10:16:16 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=5F7=5F=D1=84=D0=B8=D0=BA?= =?UTF-8?q?=D1=811?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DoubleDeckerBus/BusDelegate.cs | 11 -- .../DoubleDeckerBus/DoubleDeckerBus.csproj | 5 + .../Exceptions/BusNotFoundException.cs | 20 +++ .../Exceptions/StorageOverflowException.cs | 20 +++ .../DoubleDeckerBus/FormBusCollection.cs | 67 ++++--- .../Generics/BusesGenericStorage.cs | 166 +++++++++--------- DoubleDeckerBus/DoubleDeckerBus/Program.cs | 22 ++- DoubleDeckerBus/DoubleDeckerBus/nlog.config | 14 ++ 8 files changed, 205 insertions(+), 120 deletions(-) delete mode 100644 DoubleDeckerBus/DoubleDeckerBus/BusDelegate.cs create mode 100644 DoubleDeckerBus/DoubleDeckerBus/Exceptions/BusNotFoundException.cs create mode 100644 DoubleDeckerBus/DoubleDeckerBus/Exceptions/StorageOverflowException.cs create mode 100644 DoubleDeckerBus/DoubleDeckerBus/nlog.config diff --git a/DoubleDeckerBus/DoubleDeckerBus/BusDelegate.cs b/DoubleDeckerBus/DoubleDeckerBus/BusDelegate.cs deleted file mode 100644 index 3def398..0000000 --- a/DoubleDeckerBus/DoubleDeckerBus/BusDelegate.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using DoubleDeckerBus.DrawningObjects; - -namespace DoubleDeckerBus -{ - public delegate void BusDelegate(DrawningBus bus); -} diff --git a/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj b/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj index b57c89e..cee80ce 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj +++ b/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj @@ -8,4 +8,9 @@ enable + + + + + \ No newline at end of file diff --git a/DoubleDeckerBus/DoubleDeckerBus/Exceptions/BusNotFoundException.cs b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/BusNotFoundException.cs new file mode 100644 index 0000000..bca3916 --- /dev/null +++ b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/BusNotFoundException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace DoubleDeckerBus.Exceptions +{ + [Serializable] + internal class BusNotFoundException : ApplicationException + { + public BusNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public BusNotFoundException() : base() { } + public BusNotFoundException(string message) : base(message) { } + public BusNotFoundException(string message, Exception exception) : base(message, exception){ } + protected BusNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } + } +} + diff --git a/DoubleDeckerBus/DoubleDeckerBus/Exceptions/StorageOverflowException.cs b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/StorageOverflowException.cs new file mode 100644 index 0000000..ff06c09 --- /dev/null +++ b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/StorageOverflowException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.Serialization; + +namespace DoubleDeckerBus.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/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs index 3e2c112..03555b7 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs @@ -12,33 +12,36 @@ using DoubleDeckerBus.Generics; using DoubleDeckerBus.MovementStrategy; using static System.Windows.Forms.DataFormats; using System.Windows.Forms; +using DoubleDeckerBus.Exceptions; +using Microsoft.Extensions.Logging; namespace DoubleDeckerBus { public partial class FormBusCollection : Form { private readonly BusesGenericStorage _storage; - public FormBusCollection() + private readonly ILogger _logger; + public FormBusCollection(ILogger logger) { InitializeComponent(); _storage = new BusesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() { int index = listBoxStorages.SelectedIndex; - listBoxStorages.Items.Clear(); for (int i = 0; i < _storage.Keys.Count; i++) { listBoxStorages.Items.Add(_storage.Keys[i]); } - - if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count)) + if (listBoxStorages.Items.Count > 0 && (index == -1 || index + >= listBoxStorages.Items.Count)) { listBoxStorages.SelectedIndex = 0; } - - else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count) + else if (listBoxStorages.Items.Count > 0 && index > -1 && + index < listBoxStorages.Items.Count) { listBoxStorages.SelectedIndex = index; } @@ -52,11 +55,12 @@ namespace DoubleDeckerBus if (string.IsNullOrEmpty(textBoxStorageName.Text)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка",MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); + _logger.LogInformation($"Добавлен набор:{ textBoxStorageName.Text}"); } private void ButtonDelObject_Click(object sender, EventArgs e) { @@ -64,12 +68,14 @@ namespace DoubleDeckerBus { return; } - if (MessageBox.Show($"Удалить объект{listBoxStorages.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, - MessageBoxIcon.Question) == DialogResult.Yes) + string name = listBoxStorages.SelectedItem.ToString() ?? + string.Empty; + if (MessageBox.Show($"Удалить объект {name}?", "Удаление", + MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - _storage.DelSet(listBoxStorages.SelectedItem.ToString() - ?? string.Empty); + _storage.DelSet(name); ReloadObjects(); + _logger.LogInformation($"Удален набор: {name}"); } } private void buttonAddBus_Click(object sender, EventArgs e) @@ -120,15 +126,23 @@ namespace DoubleDeckerBus return; } int pos = Convert.ToInt32(maskedTextBoxNumber.Text); - if (obj - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowBuses(); + if (obj - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBoxCollection.Image = obj.ShowBuses(); + } + else + { + MessageBox.Show("Не удалось удалить объект"); + } } - else + catch (BusNotFoundException ex) { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show(ex.Message); } + } private void ButtonRefreshCollection_Click(object sender, EventArgs e) { @@ -136,8 +150,7 @@ namespace DoubleDeckerBus { return; } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? - string.Empty]; + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) { return; @@ -148,13 +161,14 @@ namespace DoubleDeckerBus { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.SaveData(saveFileDialog.FileName)) + try { - MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно","Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не сохранилось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } @@ -162,17 +176,18 @@ namespace DoubleDeckerBus { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storage.LoadData(openFileDialog.FileName)) + try { - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _storage.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно","Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); foreach (var collection in _storage.Keys) { listBoxStorages.Items.Add(collection); } } - else + catch (Exception ex) { - MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show($"Не открылось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } diff --git a/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs b/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs index 81800ad..1b142a9 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs @@ -23,87 +23,6 @@ namespace DoubleDeckerBus.Generics _pictureWidth = pictureWidth; _pictureHeight = pictureHeight; } - public bool SaveData(string filename) - { - if (File.Exists(filename)) - { - File.Delete(filename); - } - StringBuilder data = new(); - foreach (KeyValuePair> record in _busStorages) - { - StringBuilder records = new(); - foreach (DrawningBus? elem in record.Value.GetTheBuses) - { - records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); - } - data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); - } - - if (data.Length == 0) - { - return false; - } - string toWrite = $"BusStorage{Environment.NewLine}{data}"; - var strs = toWrite.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - - using (StreamWriter sw = new(filename)) - { - foreach (var str in strs) - { - sw.WriteLine(str); - } - } - return true; - } - public bool LoadData(string filename) - { - if (!File.Exists(filename)) - { - return false; - } - using (StreamReader sr = new(filename)) - { - string str = sr.ReadLine(); - var strs = str.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); - if (strs == null || strs.Length == 0) - { - return false; - } - if (!strs[0].StartsWith("BusStorage")) - { - return false; - } - _busStorages.Clear(); - do - { - string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); - if (record.Length != 2) - { - str = sr.ReadLine(); - continue; - } - BusesGenericCollection collection = new(_pictureWidth, _pictureHeight); - string[] set = record[1].Split(_separatorRecords, StringSplitOptions.RemoveEmptyEntries); - foreach (string elem in set) - { - DrawningBus? bus = - elem?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight); - if (bus != null) - { - if (!(collection + bus)) - { - return false; - } - } - } - _busStorages.Add(record[0], collection); - - str = sr.ReadLine(); - } while (str != null); - } - return true; - } public void AddSet(string name) { _busStorages.Add(name, new BusesGenericCollection(_pictureWidth, _pictureHeight)); @@ -130,5 +49,90 @@ namespace DoubleDeckerBus.Generics return null; } } + public void SaveData(string filename) + { + if (File.Exists(filename)) + { + File.Delete(filename); + } + StringBuilder data = new(); + foreach (KeyValuePair> record in _busStorages) + { + StringBuilder records = new(); + foreach (DrawningBus? elem in record.Value.GetTheBuses) + { + records.Append($"{elem?.GetDataForSave(_separatorForObject)}{_separatorRecords}"); + } + data.AppendLine($"{record.Key}{_separatorForKeyValue}{records}"); + } + if (data.Length == 0) + { + throw new Exception("Невалидная операция, нет данных для сохранения"); + } + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new + UTF8Encoding(true).GetBytes($"BusStorage{Environment.NewLine}{data}"); + fs.Write(info, 0, info.Length); + return; + } + public void LoadData(string filename) + { + if (!File.Exists(filename)) + { + throw new Exception("Файл не найден"); + } + 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); + } + } + var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' }, + StringSplitOptions.RemoveEmptyEntries); + if (strs == null || strs.Length == 0) + { + throw new Exception("Нет данных для загрузки"); + } + if (!strs[0].StartsWith("BusStorage")) + { + //если нет такой записи, то это не те данные + throw new Exception("Неверный формат данных"); + } + _busStorages.Clear(); + foreach (string data in strs) + { + string[] record = data.Split(_separatorForKeyValue, + StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 2) + { + continue; + } + BusesGenericCollection + collection = new(_pictureWidth, _pictureHeight); + string[] set = record[1].Split(_separatorRecords, + StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + DrawningBus? car = + elem?.CreateDrawningBus(_separatorForObject, _pictureWidth, _pictureHeight); + if (car != null) + { + if (!(collection + car)) + { + throw new Exception("Ошибка добавления в коллекцию"); + } + } + } + _busStorages.Add(record[0], collection); + } + } } } + + + diff --git a/DoubleDeckerBus/DoubleDeckerBus/Program.cs b/DoubleDeckerBus/DoubleDeckerBus/Program.cs index 08776e0..5d5a9e8 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/Program.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/Program.cs @@ -1,4 +1,7 @@ +using Microsoft.Extensions.DependencyInjection; using System.Drawing; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; namespace DoubleDeckerBus { @@ -8,7 +11,22 @@ namespace DoubleDeckerBus static void Main() { ApplicationConfiguration.Initialize(); - Application.Run(new FormBusCollection()); + 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 => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); } } -} \ No newline at end of file +} diff --git a/DoubleDeckerBus/DoubleDeckerBus/nlog.config b/DoubleDeckerBus/DoubleDeckerBus/nlog.config new file mode 100644 index 0000000..6518387 --- /dev/null +++ b/DoubleDeckerBus/DoubleDeckerBus/nlog.config @@ -0,0 +1,14 @@ + + + + + + + + + + +