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 1/4] =?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 @@ + + + + + + + + + + + -- 2.25.1 From 28b59aba442377f07ceba6e31d5f50e1d13d2ca4 Mon Sep 17 00:00:00 2001 From: "yuliya.mavrina@internet.ru" Date: Sun, 10 Dec 2023 21:55:01 +0300 Subject: [PATCH 2/4] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=E2=84=967?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DoubleDeckerBus/DoubleDeckerBus.csproj | 3 +- .../Exceptions/BusNotFoundException.cs | 2 +- .../Exceptions/StorageOverflowException.cs | 5 +- .../FormBusCollection.Designer.cs | 30 +++-- .../DoubleDeckerBus/FormBusCollection.cs | 106 ++++++++++-------- .../DoubleDeckerBus/FormBusCollection.resx | 3 + .../Generics/BusesGenericStorage.cs | 3 +- .../DoubleDeckerBus/Generics/SetGeneric.cs | 30 ++--- 8 files changed, 96 insertions(+), 86 deletions(-) diff --git a/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj b/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj index cee80ce..c96926e 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj +++ b/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj @@ -10,7 +10,8 @@ - + + \ No newline at end of file diff --git a/DoubleDeckerBus/DoubleDeckerBus/Exceptions/BusNotFoundException.cs b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/BusNotFoundException.cs index bca3916..0fd89c2 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/Exceptions/BusNotFoundException.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/BusNotFoundException.cs @@ -10,7 +10,7 @@ namespace DoubleDeckerBus.Exceptions [Serializable] internal class BusNotFoundException : ApplicationException { - public BusNotFoundException(int i) : base($"Не найден объект по позиции { i}") { } + public BusNotFoundException(int i) : base($"Не найден объект по позиции {i}") { } public BusNotFoundException() : base() { } public BusNotFoundException(string message) : base(message) { } public BusNotFoundException(string message, Exception exception) : base(message, exception){ } diff --git a/DoubleDeckerBus/DoubleDeckerBus/Exceptions/StorageOverflowException.cs b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/StorageOverflowException.cs index ff06c09..908e54c 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/Exceptions/StorageOverflowException.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/Exceptions/StorageOverflowException.cs @@ -10,11 +10,10 @@ namespace DoubleDeckerBus.Exceptions [Serializable] internal class StorageOverflowException : ApplicationException { - public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: { count}") { } + public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: {count}") { } public StorageOverflowException() : base() { } public StorageOverflowException(string message) : base(message) { } - public StorageOverflowException(string message, Exception exception) - : base(message, exception) { } + public StorageOverflowException(string message, Exception exception): base(message, exception) { } protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { } } } diff --git a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.Designer.cs b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.Designer.cs index c1a9038..86433c4 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.Designer.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.Designer.cs @@ -39,10 +39,11 @@ ButtonDelObject = new Button(); ButtonAddObject = new Button(); menuStrip = new MenuStrip(); - SaveToolStripMenuItem = new ToolStripMenuItem(); + ToolStripMenuItem = new ToolStripMenuItem(); LoadToolStripMenuItem = new ToolStripMenuItem(); openFileDialog = new OpenFileDialog(); saveFileDialog = new SaveFileDialog(); + SaveToolStripMenuItem = new ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)pictureBoxCollection).BeginInit(); panel.SuspendLayout(); menuStrip.SuspendLayout(); @@ -155,26 +156,25 @@ // // menuStrip // - menuStrip.Items.AddRange(new ToolStripItem[] { SaveToolStripMenuItem }); + menuStrip.Items.AddRange(new ToolStripItem[] { ToolStripMenuItem }); menuStrip.Location = new Point(0, 0); menuStrip.Name = "menuStrip"; menuStrip.Size = new Size(168, 24); menuStrip.TabIndex = 10; menuStrip.Text = "menuStrip1"; // - // SaveToolStripMenuItem + // ToolStripMenuItem // - SaveToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { LoadToolStripMenuItem }); - SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; - SaveToolStripMenuItem.Size = new Size(144, 20); - SaveToolStripMenuItem.Text = "SaveToolStripMenuItem"; - SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + ToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { LoadToolStripMenuItem, SaveToolStripMenuItem }); + ToolStripMenuItem.Name = "ToolStripMenuItem"; + ToolStripMenuItem.Size = new Size(48, 20); + ToolStripMenuItem.Text = "файл"; // // LoadToolStripMenuItem // LoadToolStripMenuItem.Name = "LoadToolStripMenuItem"; - LoadToolStripMenuItem.Size = new Size(201, 22); - LoadToolStripMenuItem.Text = "LoadToolStripMenuItem"; + LoadToolStripMenuItem.Size = new Size(180, 22); + LoadToolStripMenuItem.Text = "Загрузить"; LoadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; // // openFileDialog @@ -186,6 +186,13 @@ // saveFileDialog.Filter = "«txt file | *.txt»"; // + // SaveToolStripMenuItem + // + SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; + SaveToolStripMenuItem.Size = new Size(180, 22); + SaveToolStripMenuItem.Text = "Сохранить"; + SaveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // // FormBusCollection // AutoScaleDimensions = new SizeF(7F, 15F); @@ -219,7 +226,8 @@ private OpenFileDialog openFileDialog; private SaveFileDialog saveFileDialog; private MenuStrip menuStrip; - private ToolStripMenuItem SaveToolStripMenuItem; + private ToolStripMenuItem ToolStripMenuItem; private ToolStripMenuItem LoadToolStripMenuItem; + private ToolStripMenuItem SaveToolStripMenuItem; } } \ No newline at end of file diff --git a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs index 03555b7..7048df9 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs @@ -14,29 +14,30 @@ using static System.Windows.Forms.DataFormats; using System.Windows.Forms; using DoubleDeckerBus.Exceptions; using Microsoft.Extensions.Logging; +using System.Xml.Linq; +using Serilog; +using Log = Serilog.Log; namespace DoubleDeckerBus { public partial class FormBusCollection : Form { private readonly BusesGenericStorage _storage; - 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; } @@ -52,15 +53,14 @@ namespace DoubleDeckerBus } private void ButtonAddObject_Click(object sender, EventArgs e) { - 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}"); + Log.Information($"Добавлен набор:{textBoxStorageName.Text}"); } private void ButtonDelObject_Click(object sender, EventArgs e) { @@ -68,47 +68,16 @@ namespace DoubleDeckerBus { return; } - string name = listBoxStorages.SelectedItem.ToString() ?? - string.Empty; + string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty; if (MessageBox.Show($"Удалить объект {name}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { _storage.DelSet(name); ReloadObjects(); - _logger.LogInformation($"Удален набор: {name}"); + Log.Information($"Удален набор: {name}"); } } private void buttonAddBus_Click(object sender, EventArgs e) - { - if (listBoxStorages.SelectedIndex == -1) - { - return; - } - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; - if (obj == null) - { - return; - } - FormBusConfig form = new FormBusConfig(); - form.AddEvent(AddBus); - form.Show(); - } - private void AddBus(DrawningBus boat) - { - boat._pictureWidth = pictureBoxCollection.Width; - boat._pictureHeight = pictureBoxCollection.Height; if (listBoxStorages.SelectedIndex == -1) return; - var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; if (obj == null) return; - if (obj + boat) - { - MessageBox.Show("Объект добавлен"); - pictureBoxCollection.Image = obj.ShowBuses(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } - private void buttonRemoveBus_Click(object sender, EventArgs e) { if (listBoxStorages.SelectedIndex == -1) { @@ -120,29 +89,64 @@ namespace DoubleDeckerBus { return; } - if (MessageBox.Show("Удалить объект?", "Удаление", - MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + FormBusConfig form = new(); + form.Show(); + Action? busDelegate = new((m) => + { + try + { + bool q = obj + m; + MessageBox.Show("Объект добавлен"); + Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); + pictureBoxCollection.Image = obj.ShowBuses(); + } + catch (StorageOverflowException ex) + { + Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена"); + MessageBox.Show(ex.Message); + } + }); + form.AddEvent(busDelegate); + } + private void buttonRemoveBus_Click(object sender, EventArgs e) + { + if (listBoxStorages.SelectedIndex == -1) + { + return; + } + var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty]; + if (obj == null) + { + return; + } + if (MessageBox.Show("Удалить объект?", "Удалить", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } - int pos = Convert.ToInt32(maskedTextBoxNumber.Text); try { + int pos = Convert.ToInt32(maskedTextBoxNumber.Text); if (obj - pos != null) { MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowBuses(); + pictureBoxCollection.Image = obj.ShowBuses(); + Log.Information($"лодка удалена из набора {listBoxStorages.SelectedItem.ToString()}"); } else { - MessageBox.Show("Не удалось удалить объект"); + MessageBox.Show("Объект не удален"); + Log.Warning($"лодка не удалена из набора {listBoxStorages.SelectedItem.ToString()}"); } } catch (BusNotFoundException ex) { MessageBox.Show(ex.Message); + Log.Warning($"BoatNotFound: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}"); + } + catch (Exception ex) + { + MessageBox.Show("Объект не добавлен"); Log.Warning("Not input"); } - } private void ButtonRefreshCollection_Click(object sender, EventArgs e) { @@ -165,12 +169,16 @@ namespace DoubleDeckerBus { _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно","Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен"); } catch (Exception ex) { + Log.Warning("Не удалось сохранить"); MessageBox.Show($"Не сохранилось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } + } private void LoadToolStripMenuItem_Click(object sender, EventArgs e) { @@ -180,14 +188,18 @@ namespace DoubleDeckerBus { _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно","Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + Log.Information($"Файл {openFileDialog.FileName} успешно загружен"); foreach (var collection in _storage.Keys) { listBoxStorages.Items.Add(collection); } + ReloadObjects(); } catch (Exception ex) { - MessageBox.Show($"Не открылось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + Log.Warning("Не удалось загрузить"); + MessageBox.Show($"Не загрузилось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } } } diff --git a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.resx b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.resx index 7ea2349..11110dc 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.resx +++ b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.resx @@ -120,6 +120,9 @@ 11, 17 + + 11, 17 + 132, 17 diff --git a/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs b/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs index 1b142a9..263df3a 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/Generics/BusesGenericStorage.cs @@ -36,8 +36,7 @@ namespace DoubleDeckerBus.Generics _busStorages.Remove(name); } - public BusesGenericCollection? - this[string ind] + public BusesGenericCollection?this[string ind] { get { diff --git a/DoubleDeckerBus/DoubleDeckerBus/Generics/SetGeneric.cs b/DoubleDeckerBus/DoubleDeckerBus/Generics/SetGeneric.cs index 22e9633..b0df051 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/Generics/SetGeneric.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/Generics/SetGeneric.cs @@ -1,4 +1,5 @@ -using System; +using DoubleDeckerBus.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Numerics; @@ -21,30 +22,23 @@ namespace DoubleDeckerBus.Generics public bool Insert(T bus) { if (_places.Count == _maxCount) - { - return false; - } - + throw new StorageOverflowException(_maxCount); Insert(bus, 0); return true; } public bool Insert(T bus, int position) { - if (!(position >= 0 && position <= Count && _places.Count < _maxCount)) - { + if (_places.Count == _maxCount) + throw new StorageOverflowException(_maxCount); + if (!(position >= 0 && position <= Count)) return false; - } - _places.Insert(position, bus); return true; } public bool Remove(int position) { - if (position < 0 || position >= Count) - { - return false; - } - + if (!(position >= 0 && position < Count)) + throw new BusNotFoundException(position); _places.RemoveAt(position); return true; } @@ -52,20 +46,14 @@ namespace DoubleDeckerBus.Generics { get { - if (position < 0 || position >= _maxCount) - { + if (!(position >= 0 && position < Count)) return null; - } - return _places[position]; } set { if (!(position >= 0 && position < Count && _places.Count < _maxCount)) - { return; - } - _places.Insert(position, value); return; } -- 2.25.1 From 8aa0b7ef16a18c7165fc38d07df1f3bd84413454 Mon Sep 17 00:00:00 2001 From: "yuliya.mavrina@internet.ru" Date: Sat, 16 Dec 2023 19:23:29 +0300 Subject: [PATCH 3/4] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=E2=84=967?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../DoubleDeckerBus/DoubleDeckerBus.csproj | 12 +++++++ .../DoubleDeckerBus/FormBusCollection.cs | 32 ++++++++++--------- DoubleDeckerBus/DoubleDeckerBus/Program.cs | 22 ++++++++++--- .../DoubleDeckerBus/appSettings.json | 20 ++++++++++++ .../{nlog.config => nlog.config.xml} | 0 5 files changed, 66 insertions(+), 20 deletions(-) create mode 100644 DoubleDeckerBus/DoubleDeckerBus/appSettings.json rename DoubleDeckerBus/DoubleDeckerBus/{nlog.config => nlog.config.xml} (100%) diff --git a/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj b/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj index c96926e..257fc89 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj +++ b/DoubleDeckerBus/DoubleDeckerBus/DoubleDeckerBus.csproj @@ -9,9 +9,21 @@ + + + + + + + + + + + Always + \ No newline at end of file diff --git a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs index 7048df9..78b69e5 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/FormBusCollection.cs @@ -15,18 +15,20 @@ using System.Windows.Forms; using DoubleDeckerBus.Exceptions; using Microsoft.Extensions.Logging; using System.Xml.Linq; -using Serilog; -using Log = Serilog.Log; + + namespace DoubleDeckerBus { public partial class FormBusCollection : Form { private readonly BusesGenericStorage _storage; + private readonly ILogger _logger; public FormBusCollection(ILogger logger) { InitializeComponent(); _storage = new BusesGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height); + _logger = logger; } private void ReloadObjects() { @@ -60,7 +62,7 @@ namespace DoubleDeckerBus } _storage.AddSet(textBoxStorageName.Text); ReloadObjects(); - Log.Information($"Добавлен набор:{textBoxStorageName.Text}"); + _logger.LogInformation($"Добавлен набор:{textBoxStorageName.Text}"); } private void ButtonDelObject_Click(object sender, EventArgs e) { @@ -74,7 +76,7 @@ namespace DoubleDeckerBus { _storage.DelSet(name); ReloadObjects(); - Log.Information($"Удален набор: {name}"); + _logger.LogInformation($"Удален набор: {name}"); } } private void buttonAddBus_Click(object sender, EventArgs e) @@ -97,12 +99,12 @@ namespace DoubleDeckerBus { bool q = obj + m; MessageBox.Show("Объект добавлен"); - Log.Information($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); + _logger.LogInformation($"Добавлен объект в коллекцию {listBoxStorages.SelectedItem.ToString() ?? string.Empty}"); pictureBoxCollection.Image = obj.ShowBuses(); } catch (StorageOverflowException ex) { - Log.Warning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена"); + _logger.LogWarning($"Коллекция {listBoxStorages.SelectedItem.ToString() ?? string.Empty} переполнена"); MessageBox.Show(ex.Message); } }); @@ -129,23 +131,23 @@ namespace DoubleDeckerBus if (obj - pos != null) { MessageBox.Show("Объект удален"); - pictureBoxCollection.Image = obj.ShowBuses(); - Log.Information($"лодка удалена из набора {listBoxStorages.SelectedItem.ToString()}"); + pictureBoxCollection.Image = obj.ShowBuses(); + _logger.LogInformation($"лодка удалена из набора {listBoxStorages.SelectedItem.ToString()}"); } else { MessageBox.Show("Объект не удален"); - Log.Warning($"лодка не удалена из набора {listBoxStorages.SelectedItem.ToString()}"); + _logger.LogWarning($"лодка не удалена из набора {listBoxStorages.SelectedItem.ToString()}"); } } catch (BusNotFoundException ex) { MessageBox.Show(ex.Message); - Log.Warning($"BoatNotFound: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}"); + _logger.LogWarning($"BoatNotFound: {ex.Message} in set {listBoxStorages.SelectedItem.ToString()}"); } catch (Exception ex) { - MessageBox.Show("Объект не добавлен"); Log.Warning("Not input"); + MessageBox.Show("Объект не добавлен"); _logger.LogWarning("Not input"); } } private void ButtonRefreshCollection_Click(object sender, EventArgs e) @@ -169,11 +171,11 @@ namespace DoubleDeckerBus { _storage.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно","Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - Log.Information($"Файл {saveFileDialog.FileName} успешно сохранен"); + _logger.LogInformation($"Файл {saveFileDialog.FileName} успешно сохранен"); } catch (Exception ex) { - Log.Warning("Не удалось сохранить"); + _logger.LogWarning("Не удалось сохранить"); MessageBox.Show($"Не сохранилось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } @@ -188,7 +190,7 @@ namespace DoubleDeckerBus { _storage.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно","Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - Log.Information($"Файл {openFileDialog.FileName} успешно загружен"); + _logger.LogInformation($"Файл {openFileDialog.FileName} успешно загружен"); foreach (var collection in _storage.Keys) { listBoxStorages.Items.Add(collection); @@ -197,7 +199,7 @@ namespace DoubleDeckerBus } catch (Exception ex) { - Log.Warning("Не удалось загрузить"); + _logger.LogWarning("Не удалось загрузить"); MessageBox.Show($"Не загрузилось: {ex.Message}","Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } diff --git a/DoubleDeckerBus/DoubleDeckerBus/Program.cs b/DoubleDeckerBus/DoubleDeckerBus/Program.cs index 5d5a9e8..a4f778c 100644 --- a/DoubleDeckerBus/DoubleDeckerBus/Program.cs +++ b/DoubleDeckerBus/DoubleDeckerBus/Program.cs @@ -2,6 +2,8 @@ using Microsoft.Extensions.DependencyInjection; using System.Drawing; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; namespace DoubleDeckerBus { @@ -10,22 +12,32 @@ namespace DoubleDeckerBus [STAThread] static void Main() { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); var services = new ServiceCollection(); ConfigureServices(services); - using (ServiceProvider serviceProvider = - services.BuildServiceProvider()) + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) { Application.Run(serviceProvider.GetRequiredService()); } } private static void ConfigureServices(ServiceCollection services) { - services.AddSingleton() - .AddLogging(option => + services.AddSingleton().AddLogging(option => { + string[] path = Directory.GetCurrentDirectory().Split('\\'); + string pathNeed = ""; + for (int i = 0; i < path.Length - 3; i++) + { + pathNeed += path[i] + "\\"; + } + var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()) + .AddJsonFile(path: $"appSettings.json", optional: false, reloadOnChange: true).Build(); + + var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger(); option.SetMinimumLevel(LogLevel.Information); - option.AddNLog("nlog.config"); + option.AddSerilog(logger); }); } } diff --git a/DoubleDeckerBus/DoubleDeckerBus/appSettings.json b/DoubleDeckerBus/DoubleDeckerBus/appSettings.json new file mode 100644 index 0000000..5d067ed --- /dev/null +++ b/DoubleDeckerBus/DoubleDeckerBus/appSettings.json @@ -0,0 +1,20 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Information", + "WriteTo": [ + { + "Name": "File", + "Args": { + "path": "Logs/log_.log", + "rollingInterval": "Day", + "outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}" + } + } + ], + "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ], + "Properties": { + "Application": "DoubleDeckerBus" + } + } +} diff --git a/DoubleDeckerBus/DoubleDeckerBus/nlog.config b/DoubleDeckerBus/DoubleDeckerBus/nlog.config.xml similarity index 100% rename from DoubleDeckerBus/DoubleDeckerBus/nlog.config rename to DoubleDeckerBus/DoubleDeckerBus/nlog.config.xml -- 2.25.1 From dba41901751c76862a030bd889a568cc570a5157 Mon Sep 17 00:00:00 2001 From: "yuliya.mavrina@internet.ru" Date: Sat, 16 Dec 2023 19:27:05 +0300 Subject: [PATCH 4/4] =?UTF-8?q?=D0=9B=D0=B0=D0=B1=D0=BE=D1=80=D0=B0=D1=82?= =?UTF-8?q?=D0=BE=D1=80=D0=BD=D0=B0=D1=8F=20=E2=84=967?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DoubleDeckerBus/DoubleDeckerBus/nlog.config.xml | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 DoubleDeckerBus/DoubleDeckerBus/nlog.config.xml diff --git a/DoubleDeckerBus/DoubleDeckerBus/nlog.config.xml b/DoubleDeckerBus/DoubleDeckerBus/nlog.config.xml deleted file mode 100644 index 6518387..0000000 --- a/DoubleDeckerBus/DoubleDeckerBus/nlog.config.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - -- 2.25.1