From 83c9dfd598d46894c3b677ab23e90b3702b23e68 Mon Sep 17 00:00:00 2001 From: Osyagina_Anna Date: Wed, 1 May 2024 21:23:16 +0400 Subject: [PATCH 1/4] LabWork07 --- .../ListGenericObjects.cs | 36 ++-- .../MassiveGenericObjects.cs | 78 ++++---- .../StorageCollection.cs | 41 ++-- .../Exceptions/CollectionOverflowException.cs | 22 ++ .../Exceptions/ObjectNotFoundException.cs | 21 ++ .../PositionOutOfCollectionException.cs | 22 ++ .../ProjectMotorboat/FormBoatCollection.cs | 189 +++++++++--------- ProjectMotorboat/ProjectMotorboat/Program.cs | 19 +- .../ProjectMotorboat/ProjectMotorboat.csproj | 13 ++ ProjectMotorboat/ProjectMotorboat/nlog.config | 15 ++ 10 files changed, 288 insertions(+), 168 deletions(-) create mode 100644 ProjectMotorboat/ProjectMotorboat/Exceptions/CollectionOverflowException.cs create mode 100644 ProjectMotorboat/ProjectMotorboat/Exceptions/ObjectNotFoundException.cs create mode 100644 ProjectMotorboat/ProjectMotorboat/Exceptions/PositionOutOfCollectionException.cs create mode 100644 ProjectMotorboat/ProjectMotorboat/nlog.config diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs index 370d8c8..b9de053 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectMotorboat.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -49,39 +50,36 @@ where T : class public T? Get(int position) { - // TODO проверка позиции - if (position >= Count || position < 0) return null; + //TODO выброс ошибки если выход за границу + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } - public int Insert(T obj) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO вставка в конец набора - if (Count + 1 > _maxCount) return -1; + + // TODO выброс ошибки если переполнение + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; } public int Insert(T obj, int position) { - // TODO проверка, что не превышено максимальное количество элементов - // TODO проверка позиции - // TODO вставка по позиции - if (Count + 1 > _maxCount) return -1; - if (position < 0 || position > Count) return -1; + // TODO выброс ошибки если переполнение + // TODO выброс ошибки если за границу + if (Count == _maxCount) throw new CollectionOverflowException(Count); + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); - return 1; + return position; } - public T? Remove(int position) + public T Remove(int position) { - // TODO проверка позиции - // TODO удаление объекта из списка - if (position < 0 || position > Count) return null; - T? pos = _collection[position]; + // TODO если выброс за границу + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); - return pos; + return obj; } public IEnumerable GetItems() diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs index 6047760..09046a9 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,5 +1,7 @@  +using ProjectMotorboat.Exceptions; + namespace ProjectMotorboat.CollectionGenericObjects; public class MassiveGenericObjects : ICollectionGenericObjects where T : class @@ -38,70 +40,68 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection = Array.Empty(); } - public T? Get(int position) + public T Get(int position) { - if (position < 0 || position >= _collection.Length) - { - return null; - } + // TODO выброс ошибки если выход за границу + // TODO выброс ошибки если объект пустой + 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++) + // TODO выброс ошибки если переполнение + int index = 0; + while (index < _collection.Length) { - if (_collection[i] == null) + if (_collection[index] == null) { - _collection[i] = obj; - return i; + _collection[index] = obj; + return index; } + ++index; } - - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - if (position < 0 || position >= _collection.Length) { return position; } - + // TODO выброс ошибки если выход за границу + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) { _collection[position] = obj; return position; } - else + int index = position + 1; + while (index < _collection.Length) { - for (int i = position + 1; i < _collection.Length; i++) + if (_collection[index] == null) { - if (_collection[i] == null) - { - _collection[i] = obj; - return i; - } - } - - for (int i = position - 1; i >= 0; i--) - { - if (_collection[i] == null) - { - _collection[i] = obj; - return i; - } + _collection[index] = obj; + return index; } + index++; } - - return -1; + index = position - 1; + while (index >= 0) + { + if (_collection[index] == null) + { + _collection[index] = obj; + return index; + } + index--; + } + throw new CollectionOverflowException(Count); } public T Remove(int position) { - if (position < 0 || position >= _collection.Length) - { - return null; - } - - T? obj = _collection[position]; + // TODO выброс ошибки если объект пустой + if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); + T removeObj = _collection[position]; _collection[position] = null; - - return obj; + return removeObj; } public IEnumerable GetItems() diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs index bb19f7c..b5aab3c 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs @@ -1,4 +1,5 @@ using ProjectMotorboat.Drownings; +using ProjectMotorboat.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -23,8 +24,6 @@ public class StorageCollection public void AddCollection(string name, CollectionType collectionType) { - // TODO проверка, что name не пустой и нет в словаре записи с таким ключом - // TODO Прописать логику для добавления if (name == null || _storages.ContainsKey(name)) { return; } switch (collectionType) @@ -66,22 +65,20 @@ public class StorageCollection private readonly string _separatorItems = ";"; /// - /// Сохранение информации в хранилище в файл + /// Сохранение информации по автомобилям в хранилище в файл /// /// Путь и имя файла /// 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)) { File.Delete(filename); } - using (StreamWriter writer = new StreamWriter(filename)) { writer.Write(_collectionKey); @@ -89,7 +86,6 @@ public class StorageCollection { StringBuilder sb = new(); sb.Append(Environment.NewLine); - if (value.Value.Count == 0) { continue; @@ -115,35 +111,35 @@ public class StorageCollection } - return true; } /// - /// Загрузка информации в хранилище из файла + /// Загрузка информации по автомобилям в хранилище из файла /// /// Путь и имя файла /// true - загрузка прошла успешно, false - ошибка при загрузке данных - public bool LoadData(string filename) + public void LoadData(string filename) { if (!File.Exists(filename)) { - return false; + throw new Exception("Файл не существует"); } using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); if (str == null || str.Length == 0) { - return false; + throw new Exception("В файле нет данных"); } if (!str.StartsWith(_collectionKey)) { - return false; + throw new Exception("В файле неверные данные"); } _storages.Clear(); string strs = ""; while ((strs = fs.ReadLine()) != null) { + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); if (record.Length != 4) { @@ -153,23 +149,30 @@ public class StorageCollection ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new Exception("Не удалось создать коллекцию"); } collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateDrawningBoat() is T militaryAircraft) + if (elem?.CreateDrawningBoat() is T track) { - if (collection.Insert(militaryAircraft) == -1) + try { - return false; + if (collection.Insert(track) == -1) + { + throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); + } + } + catch (CollectionOverflowException ex) + { + throw new Exception("Коллекция переполнена", ex); } } } _storages.Add(record[0], collection); } - return true; + } } private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) diff --git a/ProjectMotorboat/ProjectMotorboat/Exceptions/CollectionOverflowException.cs b/ProjectMotorboat/ProjectMotorboat/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..34abfee --- /dev/null +++ b/ProjectMotorboat/ProjectMotorboat/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMotorboat.Exceptions; + +[Serializable] +internal class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество count" + 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/ProjectMotorboat/ProjectMotorboat/Exceptions/ObjectNotFoundException.cs b/ProjectMotorboat/ProjectMotorboat/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..e5a4cad --- /dev/null +++ b/ProjectMotorboat/ProjectMotorboat/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMotorboat.Exceptions; +[Serializable] +internal class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("В коллекции превышено допустимое количество count" + 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) { } +} \ No newline at end of file diff --git a/ProjectMotorboat/ProjectMotorboat/Exceptions/PositionOutOfCollectionException.cs b/ProjectMotorboat/ProjectMotorboat/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..9692550 --- /dev/null +++ b/ProjectMotorboat/ProjectMotorboat/Exceptions/PositionOutOfCollectionException.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectMotorboat.Exceptions; +[Serializable] + +internal class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("В коллекции превышено допустимое количество count" + 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/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs index d127340..4cf7e32 100644 --- a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs +++ b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs @@ -1,84 +1,66 @@ -using ProjectMotorboat.CollectionGenericObjects; +using Microsoft.Extensions.Logging; +using ProjectMotorboat.CollectionGenericObjects; using ProjectMotorboat.Drownings; +using ProjectMotorboat.Exceptions; using System.Windows.Forms; +using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar; namespace ProjectMotorboat; -/// -/// Форма работы с компанией и ее коллекцией -/// public partial class FormBoatCollection : Form { private readonly StorageCollection _storageCollection; - /// - /// Компания - /// private AbstractCompany? _company = null; - /// - /// Конструктор - /// - public FormBoatCollection() + private readonly ILogger _logger; + + public FormBoatCollection(ILogger logger) { InitializeComponent(); _storageCollection = new(); + _logger = logger; + _logger.LogInformation("Форма загрузилась"); } - /// - /// Выбор компании - /// - /// - /// + private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { panelCompanyTools.Enabled = false; } - /// - /// Добавление обычного автомобиля - /// - /// - /// + private void ButtonAddBoat_Click(object sender, EventArgs e) { FormBoatConfig form = new(); - // TODO передать метод + form.Show(); form.AddEvent(SetBoat); - form.Show(); } private void SetBoat(DrawningBoat? boat) { - if (_company == null || boat == null) + try { - return; + if (_company == null || boat == null) + { + return; + } + if (_company + boat != -1) + { + MessageBox.Show("Объект добавлен"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Добавлен объект: " + boat.GetDataForSave()); + } } - - if (_company + boat != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else + catch (ObjectNotFoundException) { } + catch (CollectionOverflowException ex) { MessageBox.Show("Не удалось добавить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } - } - - - /// - /// Создание объекта класса-перемещения - /// - /// Тип создаваемого объекта - - /// - /// Удаление объекта - /// - /// - /// + private void ButtonRemoveBoat_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) @@ -92,22 +74,23 @@ public partial class FormBoatCollection : Form } int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) + try { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); + if (_company - pos != null) + { + MessageBox.Show("Объект удален"); + pictureBox.Image = _company.Show(); + _logger.LogInformation("Удален объект по позиции " + pos); + } } - else + catch (Exception ex) { MessageBox.Show("Не удалось удалить объект"); + _logger.LogError("Ошибка: {Message}", ex.Message); } } - /// - /// Передача объекта в другую форму - /// - /// - /// + private void ButtonGoToCheck_Click(object sender, EventArgs e) { if (_company == null) @@ -117,33 +100,31 @@ public partial class FormBoatCollection : Form DrawningBoat? boat = null; int counter = 100; - while (boat == null) + try { - boat = _company.GetRandomObject(); - counter--; - if (counter <= 0) + while (boat == null) { - break; + boat = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } } + FormMotorboat Form = new() + { + SetBoat = boat + }; + Form.ShowDialog(); } + catch (Exception ex) - if (boat == null) { - return; + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); } - - FormMotorboat form = new() - { - SetBoat = boat - }; - form.ShowDialog(); } - /// - /// Перерисовка коллекции - /// - /// - /// + private void ButtonRefresh_Click(object sender, EventArgs e) { if (_company == null) @@ -162,33 +143,53 @@ public partial class FormBoatCollection : Form return; } - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) + try { - collectionType = CollectionType.Massive; + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } - else if (radioButtonList.Checked) + catch (Exception ex) { - collectionType = CollectionType.List; + _logger.LogError("Ошибка: {Message}", ex.Message); } - - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); RerfreshListBoxItems(); } private void ButtonCollectionDel_Click(object sender, EventArgs e) { - if (listBoxCollection.SelectedItem == null) + + + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + + try { - return; + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) + { + return; + } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + RerfreshListBoxItems(); + _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); + catch (Exception ex) + { + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } private void RerfreshListBoxItems() @@ -234,13 +235,16 @@ public partial class FormBoatCollection : Form { if (saveFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.SaveData(saveFileDialog.FileName)) + try { + _storageCollection.SaveData(saveFileDialog.FileName); MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", saveFileDialog.FileName); } - else + catch (Exception ex) { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } } @@ -249,15 +253,20 @@ public partial class FormBoatCollection : Form { if (openFileDialog.ShowDialog() == DialogResult.OK) { - if (_storageCollection.LoadData(openFileDialog.FileName)) + try { + _storageCollection.LoadData(openFileDialog.FileName); MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RerfreshListBoxItems(); + _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } - else + catch (Exception ex) { + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); } } + } -} \ No newline at end of file +} diff --git a/ProjectMotorboat/ProjectMotorboat/Program.cs b/ProjectMotorboat/ProjectMotorboat/Program.cs index 0c67735..88f1800 100644 --- a/ProjectMotorboat/ProjectMotorboat/Program.cs +++ b/ProjectMotorboat/ProjectMotorboat/Program.cs @@ -1,3 +1,7 @@ +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using NLog.Extensions.Logging; + namespace ProjectMotorboat { internal static class Program @@ -10,8 +14,21 @@ namespace ProjectMotorboat { // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. + ServiceCollection services = new(); ApplicationConfiguration.Initialize(); - Application.Run(new FormBoatCollection()); + 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/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj b/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj index 663fdb8..2dc50c1 100644 --- a/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj +++ b/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj @@ -8,4 +8,17 @@ enable + + + + + + + + + + Always + + + \ No newline at end of file diff --git a/ProjectMotorboat/ProjectMotorboat/nlog.config b/ProjectMotorboat/ProjectMotorboat/nlog.config new file mode 100644 index 0000000..fc13552 --- /dev/null +++ b/ProjectMotorboat/ProjectMotorboat/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file -- 2.25.1 From 246c2ee2c2f0259c6c118121b9cc06a1eb26b3b8 Mon Sep 17 00:00:00 2001 From: Osyagina_Anna Date: Thu, 2 May 2024 10:05:13 +0400 Subject: [PATCH 2/4] LabWork07 --- ConsoleApp1/ConsoleApp1.sln | 31 ----- ConsoleApp1/ConsoleApp1/ConsoleApp1.csproj | 10 -- ConsoleApp1/ConsoleApp1/Program.cs | 68 ---------- ConsoleApp1/ConsoleApp2/ConsoleApp2.csproj | 10 -- ConsoleApp1/ConsoleApp2/Program.cs | 113 ----------------- LAB02/02/02.csproj | 11 -- LAB02/02/Program.cs | 58 --------- LAB02/03/03.csproj | 11 -- LAB02/03/Program.cs | 1 - LAB02/1/1.csproj | 39 ------ LAB02/1/Program.cs | 2 - LAB02/2/2.csproj | 11 -- LAB02/2/Program.cs | 81 ------------ LAB02/3.1/3.1.csproj | 11 -- LAB02/3.1/Program.cs | 39 ------ LAB02/3/3.csproj | 11 -- LAB02/3/Program.cs | 42 ------ LAB02/LAB02.sln | 56 -------- LAB02/LAB02/LAB02.csproj | 10 -- LAB02/LAB02/Program.cs | 56 -------- WinFormsApp1/WinFormsApp1.sln | 25 ---- WinFormsApp1/WinFormsApp1/Form1.Designer.cs | 39 ------ WinFormsApp1/WinFormsApp1/Form1.cs | 10 -- WinFormsApp1/WinFormsApp1/Form1.resx | 120 ------------------ WinFormsApp1/WinFormsApp1/Program.cs | 17 --- WinFormsApp1/WinFormsApp1/WinFormsApp1.csproj | 11 -- 26 files changed, 893 deletions(-) delete mode 100644 ConsoleApp1/ConsoleApp1.sln delete mode 100644 ConsoleApp1/ConsoleApp1/ConsoleApp1.csproj delete mode 100644 ConsoleApp1/ConsoleApp1/Program.cs delete mode 100644 ConsoleApp1/ConsoleApp2/ConsoleApp2.csproj delete mode 100644 ConsoleApp1/ConsoleApp2/Program.cs delete mode 100644 LAB02/02/02.csproj delete mode 100644 LAB02/02/Program.cs delete mode 100644 LAB02/03/03.csproj delete mode 100644 LAB02/03/Program.cs delete mode 100644 LAB02/1/1.csproj delete mode 100644 LAB02/1/Program.cs delete mode 100644 LAB02/2/2.csproj delete mode 100644 LAB02/2/Program.cs delete mode 100644 LAB02/3.1/3.1.csproj delete mode 100644 LAB02/3.1/Program.cs delete mode 100644 LAB02/3/3.csproj delete mode 100644 LAB02/3/Program.cs delete mode 100644 LAB02/LAB02.sln delete mode 100644 LAB02/LAB02/LAB02.csproj delete mode 100644 LAB02/LAB02/Program.cs delete mode 100644 WinFormsApp1/WinFormsApp1.sln delete mode 100644 WinFormsApp1/WinFormsApp1/Form1.Designer.cs delete mode 100644 WinFormsApp1/WinFormsApp1/Form1.cs delete mode 100644 WinFormsApp1/WinFormsApp1/Form1.resx delete mode 100644 WinFormsApp1/WinFormsApp1/Program.cs delete mode 100644 WinFormsApp1/WinFormsApp1/WinFormsApp1.csproj diff --git a/ConsoleApp1/ConsoleApp1.sln b/ConsoleApp1/ConsoleApp1.sln deleted file mode 100644 index 2ba4487..0000000 --- a/ConsoleApp1/ConsoleApp1.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.8.34525.116 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp1", "ConsoleApp1\ConsoleApp1.csproj", "{D8A4ACE0-0728-47AB-9F80-9EDA475782ED}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp2", "ConsoleApp2\ConsoleApp2.csproj", "{C1FC7C16-B9EC-4007-BD39-E6B47A89CE34}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D8A4ACE0-0728-47AB-9F80-9EDA475782ED}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D8A4ACE0-0728-47AB-9F80-9EDA475782ED}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D8A4ACE0-0728-47AB-9F80-9EDA475782ED}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D8A4ACE0-0728-47AB-9F80-9EDA475782ED}.Release|Any CPU.Build.0 = Release|Any CPU - {C1FC7C16-B9EC-4007-BD39-E6B47A89CE34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C1FC7C16-B9EC-4007-BD39-E6B47A89CE34}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C1FC7C16-B9EC-4007-BD39-E6B47A89CE34}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C1FC7C16-B9EC-4007-BD39-E6B47A89CE34}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {3368BA78-2800-49EC-9A71-865DC3C2F15F} - EndGlobalSection -EndGlobal diff --git a/ConsoleApp1/ConsoleApp1/ConsoleApp1.csproj b/ConsoleApp1/ConsoleApp1/ConsoleApp1.csproj deleted file mode 100644 index 2150e37..0000000 --- a/ConsoleApp1/ConsoleApp1/ConsoleApp1.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - Exe - net8.0 - enable - enable - - - diff --git a/ConsoleApp1/ConsoleApp1/Program.cs b/ConsoleApp1/ConsoleApp1/Program.cs deleted file mode 100644 index 16bb850..0000000 --- a/ConsoleApp1/ConsoleApp1/Program.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System.Collections; -using System; - -// Класс компонента компьютера -public class ComputerComponent -{ - public string Name { get; set; } - public string Type { get; set; } - - public ComputerComponent(string name, string type) - { - Name = name; - Type = type; - } -} - -// АТД Очередь на основе массива -public class CustomQueue -{ - private ArrayList elements = new ArrayList(); - - public int Count { get { return elements.Count; } } - - public void Enqueue(ComputerComponent component) - { - elements.Add(component); - } - - public ComputerComponent Dequeue() - { - if (elements.Count == 0) - { - throw new InvalidOperationException("Queue is empty"); - } - - ComputerComponent component = (ComputerComponent)elements[0]; - elements.RemoveAt(0); - return component; - } - - public ComputerComponent Peek() - { - if (elements.Count == 0) - { - throw new InvalidOperationException("Queue is empty"); - } - - return (ComputerComponent)elements[0]; - } -} -class Program -{ - public static void Main(string[] args) - { - CustomQueue queue = new CustomQueue(); - - // Добавление компонентов в очередь - ComputerComponent cpu = new ComputerComponent("Intel Core i7", "CPU"); - ComputerComponent gpu = new ComputerComponent("Nvidia RTX 3080", "GPU"); - - queue.Enqueue(cpu); - queue.Enqueue(gpu); - - // Проверка совместимости компонентов в сборке - Console.WriteLine("Первый компонент в очереди: {0} ({1})", queue.Peek().Name, queue.Peek().Type); - Console.WriteLine("Извлечен компонент из очереди: {0} ({1})", queue.Dequeue().Name, queue.Dequeue().Type); - } -} diff --git a/ConsoleApp1/ConsoleApp2/ConsoleApp2.csproj b/ConsoleApp1/ConsoleApp2/ConsoleApp2.csproj deleted file mode 100644 index 2150e37..0000000 --- a/ConsoleApp1/ConsoleApp2/ConsoleApp2.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - Exe - net8.0 - enable - enable - - - diff --git a/ConsoleApp1/ConsoleApp2/Program.cs b/ConsoleApp1/ConsoleApp2/Program.cs deleted file mode 100644 index ae6071b..0000000 --- a/ConsoleApp1/ConsoleApp2/Program.cs +++ /dev/null @@ -1,113 +0,0 @@ -using System; - -// Реализация АТД Очередь -public class Queue -{ - private T[] elements; - private int front, rear, size, capacity; - - public Queue(int capacity) - { - this.capacity = capacity; - elements = new T[capacity]; - front = size = 0; - rear = capacity - 1; - } - - public void Enqueue(T item) - { - if (size == capacity) - throw new Exception("Queue is full"); - rear = (rear + 1) % capacity; - elements[rear] = item; - size++; - } - - public T Dequeue() - { - if (size == 0) - throw new Exception("Queue is empty"); - T item = elements[front]; - front = (front + 1) % capacity; - size--; - return item; - } - - // Реализация СД Массив - public static void SelectionSort(int[] array) - { - for (int i = 0; i < array.Length - 1; i++) - { - int minIndex = i; - for (int j = i + 1; j < array.Length; j++) - { - if (array[j] < array[minIndex]) - { - minIndex = j; - } - } - if (minIndex != i) - { - int temp = array[i]; - array[i] = array[minIndex]; - array[minIndex] = temp; - } - } - } - - // Быстрая сортировка - public static void QuickSort(int[] array, int left, int right) - { - if (left < right) - { - int pivot = Partition(array, left, right); - QuickSort(array, left, pivot - 1); - QuickSort(array, pivot + 1, right); - } - } - - private static int Partition(int[] array, int left, int right) - { - int pivot = array[right]; - int i = left - 1; - for (int j = left; j < right; j++) - { - if (array[j] < pivot) - { - i++; - int temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - } - int temp1 = array[i + 1]; - array[i + 1] = array[right]; - array[right] = temp1; - return i + 1; - } - - public static void Main() - { - int[] array = { 64, 34, 25, 12, 22, 11, 90 }; - - // Сортировка выбором - Console.WriteLine("Before selection sort:"); - foreach (var item in array) Console.Write(item + " "); - SelectionSort(array); - Console.WriteLine("\n\nAfter selection sort:"); - foreach (var item in array) Console.Write(item + " "); - - // Быстрая сортировка - Console.WriteLine("\n\nBefore quick sort:"); - foreach (var item in array) Console.Write(item + " "); - QuickSort(array, 0, array.Length - 1); - Console.WriteLine("\n\nAfter quick sort:"); - foreach (var item in array) Console.Write(item + " "); - - // Использование Очереди - Queue queue = new Queue(5); - queue.Enqueue(10); - queue.Enqueue(20); - queue.Dequeue(); - } -} \ No newline at end of file diff --git a/LAB02/02/02.csproj b/LAB02/02/02.csproj deleted file mode 100644 index 1fdc33b..0000000 --- a/LAB02/02/02.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - net8.0 - _02 - enable - enable - - - diff --git a/LAB02/02/Program.cs b/LAB02/02/Program.cs deleted file mode 100644 index 6ae43fa..0000000 --- a/LAB02/02/Program.cs +++ /dev/null @@ -1,58 +0,0 @@ -using System; -using System.Diagnostics; - -class EditDistance//Определяет класс EditDistance для вычисления редакционного расстояния между двумя строками. -{ - static int Min(int a, int b, int c)//Вспомогательный метод, возвращающий минимальное из трех заданных целых чисел. - { - return Math.Min(Math.Min(a, b), c); - } - - static int EditDistanceDP(string str1, string str2)//Статический метод, который вычисляет редакционное расстояние между двумя строками str1 и str2 с использованием динамического программирования.Содержит двумерный массив dp для хранения вычисленных значений. - { - int m = str1.Length; - int n = str2.Length; - - int[,] dp = new int[m + 1, n + 1];//Инициализирует массив dp базовыми случаями: dp[i, 0] = i: Если строка str1 пуста, расстояние равно длине str2.dp[0, j] = j: Если строка str2 пуста, расстояние равно длине str1. - - // Заполняем базовые случаи - for (int i = 0; i <= m; i++) - { - for (int j = 0; j <= n; j++) - { - if (i == 0) - dp[i, j] = j; // Если первая строка пустая, расстояние - длина второй строки - else if (j == 0) - dp[i, j] = i; // Если вторая строка пустая, расстояние - длина первой строки - else if (str1[i - 1] == str2[j - 1]) - dp[i, j] = dp[i - 1, j - 1]; // Если символы совпадают, берем значение из диагонали - else - dp[i, j] = 1 + Min(dp[i - 1, j], // Удаление - dp[i, j - 1], // Вставка - dp[i - 1, j - 1]); // Замена - } - } - - return dp[m, n]; - } - - static void Main(string[] args) - { - string str1 = "кот"; - string str2 = "скат"; - - // Измерение времени выполнения - Stopwatch stopwatch = new Stopwatch(); - stopwatch.Start(); - int distance = EditDistanceDP(str1, str2); - stopwatch.Stop(); - Console.WriteLine("Редакционное расстояние между '{0}' и '{1}' равно {2}", str1, str2, distance); - Console.WriteLine("Время выполнения: " + stopwatch.ElapsedMilliseconds + " миллисекунд"); - - // Измерение использования памяти - Process currentProcess = Process.GetCurrentProcess(); - long memoryUsed = currentProcess.PrivateMemorySize64 / (1024 * 1024); // Переводим байты в мегабайты - - Console.WriteLine("Редакционное расстояние между '{0}' и '{1}' равно {2}", str1, str2, EditDistanceDP(str1, str2)); - } -} diff --git a/LAB02/03/03.csproj b/LAB02/03/03.csproj deleted file mode 100644 index 3386867..0000000 --- a/LAB02/03/03.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - net8.0 - _03 - enable - enable - - - diff --git a/LAB02/03/Program.cs b/LAB02/03/Program.cs deleted file mode 100644 index 5f28270..0000000 --- a/LAB02/03/Program.cs +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/LAB02/1/1.csproj b/LAB02/1/1.csproj deleted file mode 100644 index c828beb..0000000 --- a/LAB02/1/1.csproj +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Alg; - -class Program // O(n^2) -{ - static void Main(string[] args) - { - int n1 = Convert.ToInt32(Console.ReadLine()); - FindPrimes(n1); - } - - static void FindPrimes(int n) - { - bool[] isPrime = new bool[n + 1]; - for (int i = 2; i <= n; i++) - { - isPrime[i] = true; - } - - for (int i = 2; i <= n; i++) - { - - - if (isPrime[i] == true) - { - Console.Write(i + " "); - for (int j = i * i; j <= n; j += i) - { - isPrime[j] = false; - } - } - } - } -} diff --git a/LAB02/1/Program.cs b/LAB02/1/Program.cs deleted file mode 100644 index 3751555..0000000 --- a/LAB02/1/Program.cs +++ /dev/null @@ -1,2 +0,0 @@ -// See https://aka.ms/new-console-template for more information -Console.WriteLine("Hello, World!"); diff --git a/LAB02/2/2.csproj b/LAB02/2/2.csproj deleted file mode 100644 index 6ce99c6..0000000 --- a/LAB02/2/2.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - net8.0 - _2 - enable - enable - - - diff --git a/LAB02/2/Program.cs b/LAB02/2/Program.cs deleted file mode 100644 index 2272591..0000000 --- a/LAB02/2/Program.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Alg; -class Program // БЫСТРАЯ СОРТИРОВКА (В лучшем случае O(n*log(n)), в худшем O(n^2)) -{ - static void Main(string[] args) - { - int[] myArray = randomGenerate(10, 1, 100); // Создаем массив из 10000 элементов со значениями от 1 до 1000000 - - Console.WriteLine("Исходный массив:"); - printArray(myArray); // Выводим массив на экран - - quickSort(myArray, 0, myArray.Length - 1); // Сортируем массив быстрой сортировкой - Console.WriteLine("Отсортированный массив:"); - printArray(myArray); // Выводим отсортированный массив на экран - } - - static int[] randomGenerate(int size, int minValue, int maxValue) - { - Random rnd = new Random(); - int[] array = new int[size]; - for (int i = 0; i < size; i++) - { - array[i] = rnd.Next(minValue, maxValue + 1); // Генерируем случайное число от minValue до maxValue - } - return array; - } - - static void printArray(int[] array) - { - foreach (int num in array) - { - Console.Write(num + " "); - } - Console.WriteLine(); - } - - static void quickSort(int[] array, int low, int high) - { - if (low < high) - { - int pivotIndex = partition(array, low, high); - - // Рекурсивно сортируем элементы до и после опорного элемента - quickSort(array, low, pivotIndex - 1); - quickSort(array, pivotIndex + 1, high); - } - } - - static int partition(int[] array, int low, int high) - { - int pivot = array[high]; - int i = low - 1; // Индекс меньшего элемента - - for (int j = low; j < high; j++) - { - // Если текущий элемент меньше или равен опорному - if (array[j] <= pivot) - { - i++; - - // Обмен значениями - int temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } - } - - // Обмен значениями - int temp1 = array[i + 1]; - array[i + 1] = array[high]; - array[high] = temp1; - - return i + 1; - } -} \ No newline at end of file diff --git a/LAB02/3.1/3.1.csproj b/LAB02/3.1/3.1.csproj deleted file mode 100644 index 68d5c48..0000000 --- a/LAB02/3.1/3.1.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - net8.0 - _3._1 - enable - enable - - - diff --git a/LAB02/3.1/Program.cs b/LAB02/3.1/Program.cs deleted file mode 100644 index 22ca218..0000000 --- a/LAB02/3.1/Program.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Alg; - -class Program // O(n^2)//Это объявление класса с именем "Program". Комментарий "// O(n^2)" указывает на то, что алгоритм внутри метода "FindPrimes" имеет временную сложность O(n^2), что означает квадратичную зависимость от размера входных данных. -{ - static void Main(string[] args)//Это объявление метода Main, который является точкой входа в программу. Он принимает массив строк args в качестве аргументов. - { - int n1 = Convert.ToInt32(Console.ReadLine());//Прочитывает ввод пользователя с консоли и конвертирует его в целое число, которое сохраняется в переменной n1. - FindPrimes(n1);//Вызов метода FindPrimes с аргументом n1. - } - - static void FindPrimes(int n)//Объявление метода FindPrimes, который принимает целочисленный аргумент n. - { - bool[] isPrime = new bool[n + 1];//Создание массива isPrime длиной n+1, который будет использоваться для отслеживания простых чисел. - for (int i = 2; i <= n; i++)//Начало цикла от 2 до n. - { - isPrime[i] = true;//Установка флага isPrimei в true, так как i является простым числом. - } - - for (int i = 2; i <= n; i++)//Начало второго цикла от 2 до n. - { - - - if (isPrime[i] == true)//Проверка, является ли число i простым. - { - Console.Write(i + " ");//Вывод числа i на консоль. - for (int j = i * i; j <= n; j += i)//Цикл, который помечает значения, кратные i, как непростые. - { - isPrime[j] = false;//Установка флага isPrimej в false, так как j не является простым числом. - } - } - } - } -} diff --git a/LAB02/3/3.csproj b/LAB02/3/3.csproj deleted file mode 100644 index b499880..0000000 --- a/LAB02/3/3.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - Exe - net8.0 - _3 - enable - enable - - - diff --git a/LAB02/3/Program.cs b/LAB02/3/Program.cs deleted file mode 100644 index 27ec9af..0000000 --- a/LAB02/3/Program.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Alg; -class Program // O(log(n)) -{ - static void Main() - { - int[] arr = { 2, 3, 4, 10, 40 };//Инициализация массива arr с элементами 2, 3, 4, 10, 40. - int x = 10;//Определение переменной x, которая равна искомому элементу. - int result = BinarySearch(arr, x);//Вызов метода BinarySearch для поиска элемента x в массиве arr. - - if (result == -1)//Проверка результата поиска и вывод соответствующего сообщения. - - Console.WriteLine("Элемент не найден"); - else - Console.WriteLine("Элемент найден в индексе: " + result); - } - static int BinarySearch(int[] arr, int x)//Объявление метода BinarySearch, который принимает массив arr и искомый элемент x. - { - int left = 0;//Инициализация переменной left, которая указывает на начальный индекс массива. - int right = arr.Length - 1;//Инициализация переменной right, которая указывает на конечный индекс массива. - - while (left <= right)// Начало цикла, который выполняется, пока левая граница не превысит правую. - { - int mid = left + (right - left) / 2;//Вычисление среднего индекса mid для деления массива на две части. - - if (arr[mid] == x)//Проверка, является ли элемент в середине массива равным искомому элементу x. - return mid; - - if (arr[mid] < x)//Если элемент в середине меньше x, сдвигаем левую границу поиска. - left = mid + 1; - else - right = mid - 1;//Иначе сдвигаем правую границу поиска. - } - - return -1; // элемент не найден - } -} diff --git a/LAB02/LAB02.sln b/LAB02/LAB02.sln deleted file mode 100644 index 4fcc88b..0000000 --- a/LAB02/LAB02.sln +++ /dev/null @@ -1,56 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.8.34525.116 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LAB02", "LAB02\LAB02.csproj", "{295B61E5-A2D5-453C-87D5-7CAC7ACABE3F}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "02", "02\02.csproj", "{CD634B3A-8F12-4936-9082-3EFD2EB0C4E7}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "03", "03", "{C21E56E7-6AC7-4310-963B-BDDC0AC3CBF6}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "2", "2\2.csproj", "{E69E6275-619D-4D71-B923-9963C88A9F2B}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "3", "3\3.csproj", "{3802D8BD-C1BC-4DCB-B205-2BC83722E194}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "3.1", "3.1\3.1.csproj", "{42D05460-8C32-4F20-8606-07EA30B22E8C}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {295B61E5-A2D5-453C-87D5-7CAC7ACABE3F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {295B61E5-A2D5-453C-87D5-7CAC7ACABE3F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {295B61E5-A2D5-453C-87D5-7CAC7ACABE3F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {295B61E5-A2D5-453C-87D5-7CAC7ACABE3F}.Release|Any CPU.Build.0 = Release|Any CPU - {CD634B3A-8F12-4936-9082-3EFD2EB0C4E7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {CD634B3A-8F12-4936-9082-3EFD2EB0C4E7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CD634B3A-8F12-4936-9082-3EFD2EB0C4E7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {CD634B3A-8F12-4936-9082-3EFD2EB0C4E7}.Release|Any CPU.Build.0 = Release|Any CPU - {E69E6275-619D-4D71-B923-9963C88A9F2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {E69E6275-619D-4D71-B923-9963C88A9F2B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E69E6275-619D-4D71-B923-9963C88A9F2B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {E69E6275-619D-4D71-B923-9963C88A9F2B}.Release|Any CPU.Build.0 = Release|Any CPU - {3802D8BD-C1BC-4DCB-B205-2BC83722E194}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {3802D8BD-C1BC-4DCB-B205-2BC83722E194}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3802D8BD-C1BC-4DCB-B205-2BC83722E194}.Release|Any CPU.ActiveCfg = Release|Any CPU - {3802D8BD-C1BC-4DCB-B205-2BC83722E194}.Release|Any CPU.Build.0 = Release|Any CPU - {42D05460-8C32-4F20-8606-07EA30B22E8C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {42D05460-8C32-4F20-8606-07EA30B22E8C}.Debug|Any CPU.Build.0 = Debug|Any CPU - {42D05460-8C32-4F20-8606-07EA30B22E8C}.Release|Any CPU.ActiveCfg = Release|Any CPU - {42D05460-8C32-4F20-8606-07EA30B22E8C}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {E69E6275-619D-4D71-B923-9963C88A9F2B} = {C21E56E7-6AC7-4310-963B-BDDC0AC3CBF6} - {3802D8BD-C1BC-4DCB-B205-2BC83722E194} = {C21E56E7-6AC7-4310-963B-BDDC0AC3CBF6} - {42D05460-8C32-4F20-8606-07EA30B22E8C} = {C21E56E7-6AC7-4310-963B-BDDC0AC3CBF6} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {4B6E121E-4A2B-40E0-B768-CFD795B324BA} - EndGlobalSection -EndGlobal diff --git a/LAB02/LAB02/LAB02.csproj b/LAB02/LAB02/LAB02.csproj deleted file mode 100644 index 2150e37..0000000 --- a/LAB02/LAB02/LAB02.csproj +++ /dev/null @@ -1,10 +0,0 @@ - - - - Exe - net8.0 - enable - enable - - - diff --git a/LAB02/LAB02/Program.cs b/LAB02/LAB02/Program.cs deleted file mode 100644 index 8ed2e22..0000000 --- a/LAB02/LAB02/Program.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; - -class CoinChange -{ - static void MakeChange(int[] coins, int amount)// объявляет статический метод (без экземпляра класса) с именем MakeChange, который принимает два аргумента: coins - массив значений монет и amount - сумму, для которой нужно подобрать сдачу. - - { - Stopwatch stopwatch = new Stopwatch(); - stopwatch.Start(); - Array.Sort(coins);//сортирует массив монет в порядке возрастания. - Array.Reverse(coins);//переворачивает отсортированный массив, чтобы монеты были в порядке убывания. - - List change = new List();//создает новый пустой список для хранения монет, использованных для сдачи. - int totalCoins = 0; //инициализирует переменную totalCoins, которая будет хранить общее количество монет в сдаче, значением 0. - - - foreach (int coin in coins) // перебирает каждую монету в отсортированном массиве монет. - { - while (amount >= coin) //проверяет, является ли сумма больше или равна текущей монете. - { - change.Add(coin); //добавляет текущую монету в список сдачи. - amount -= coin;//вычитает значение текущей монеты из суммы. - - totalCoins++;//величивает счетчик общего количества монет на 1. - } - } - - Console.WriteLine("Монеты для сдачи:");//выводит строку "Монеты для сдачи:" в консоль. - foreach (int coin in change)//перебирает список сдачи - { - Console.Write(coin + " ");//выводит каждое значение монеты в консоль, разделяя их пробелами - } - Console.WriteLine("\nВсего монет: " + totalCoins);//выводит строку "Всего монет:" в консоль, а затем общее количество монет в сдаче - - - stopwatch.Stop(); - - Console.WriteLine($"\nВремя выполнения: {stopwatch.ElapsedMilliseconds} мс"); - - // Получаем данные о потреблении памяти - Process proc = Process.GetCurrentProcess(); - long memoryUsed = proc.PrivateMemorySize64; - - Console.WriteLine($"Использование памяти: {memoryUsed / 1024} KB"); - } - -static void Main(string[] args)//объявляет статический метод Main, который является входной точкой программы - { - int[] coins = { 25, 10, 5, 1 };//создает массив монет с номиналами 25, 10, 5 и 1. - int amount = 63;//устанавливает сумму для сдачи в 63 единицы. - - MakeChange(coins, amount);//вызывает метод MakeChange, передавая ему массив монет и сумму. - } -} diff --git a/WinFormsApp1/WinFormsApp1.sln b/WinFormsApp1/WinFormsApp1.sln deleted file mode 100644 index cc16879..0000000 --- a/WinFormsApp1/WinFormsApp1.sln +++ /dev/null @@ -1,25 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.8.34525.116 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinFormsApp1", "WinFormsApp1\WinFormsApp1.csproj", "{50092433-6AF5-4E71-9559-079AE2F9901A}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {50092433-6AF5-4E71-9559-079AE2F9901A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {50092433-6AF5-4E71-9559-079AE2F9901A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {50092433-6AF5-4E71-9559-079AE2F9901A}.Release|Any CPU.ActiveCfg = Release|Any CPU - {50092433-6AF5-4E71-9559-079AE2F9901A}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {59C3FED6-0E53-4AF0-9E1B-5ACF902ED5CE} - EndGlobalSection -EndGlobal diff --git a/WinFormsApp1/WinFormsApp1/Form1.Designer.cs b/WinFormsApp1/WinFormsApp1/Form1.Designer.cs deleted file mode 100644 index 1ac166c..0000000 --- a/WinFormsApp1/WinFormsApp1/Form1.Designer.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace WinFormsApp1 -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.components = new System.ComponentModel.Container(); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(800, 450); - this.Text = "Form1"; - } - - #endregion - } -} diff --git a/WinFormsApp1/WinFormsApp1/Form1.cs b/WinFormsApp1/WinFormsApp1/Form1.cs deleted file mode 100644 index dabe0d0..0000000 --- a/WinFormsApp1/WinFormsApp1/Form1.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace WinFormsApp1 -{ - public partial class Form1 : Form - { - public Form1() - { - InitializeComponent(); - } - } -} diff --git a/WinFormsApp1/WinFormsApp1/Form1.resx b/WinFormsApp1/WinFormsApp1/Form1.resx deleted file mode 100644 index 1af7de1..0000000 --- a/WinFormsApp1/WinFormsApp1/Form1.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file diff --git a/WinFormsApp1/WinFormsApp1/Program.cs b/WinFormsApp1/WinFormsApp1/Program.cs deleted file mode 100644 index 1e39c2a..0000000 --- a/WinFormsApp1/WinFormsApp1/Program.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace WinFormsApp1 -{ - internal static class Program - { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ApplicationConfiguration.Initialize(); - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/WinFormsApp1/WinFormsApp1/WinFormsApp1.csproj b/WinFormsApp1/WinFormsApp1/WinFormsApp1.csproj deleted file mode 100644 index 663fdb8..0000000 --- a/WinFormsApp1/WinFormsApp1/WinFormsApp1.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - WinExe - net8.0-windows - enable - true - enable - - - \ No newline at end of file -- 2.25.1 From 1597553ddc30e1946294f57fb5622a7c69a04efc Mon Sep 17 00:00:00 2001 From: Osyagina_Anna Date: Thu, 2 May 2024 11:23:05 +0400 Subject: [PATCH 3/4] LabWork07 --- .../AbstractCompany.cs | 15 +- .../CollectionGenericObjects/HarborService.cs | 9 +- .../ListGenericObjects.cs | 6 +- .../MassiveGenericObjects.cs | 83 +++++----- .../Exceptions/CollectionOverflowException.cs | 8 +- .../Exceptions/ObjectNotFoundException.cs | 2 +- .../PositionOutOfCollectionException.cs | 2 +- .../ProjectMotorboat/FormBoatCollection.cs | 150 ++++++++---------- .../ProjectMotorboat/FormBoatCollection.resx | 3 + ProjectMotorboat/ProjectMotorboat/Program.cs | 54 ++++--- .../ProjectMotorboat/ProjectMotorboat.csproj | 4 +- ProjectMotorboat/ProjectMotorboat/nlog.config | 15 -- .../ProjectMotorboat/serilogConfig.json | 20 +++ 13 files changed, 197 insertions(+), 174 deletions(-) delete mode 100644 ProjectMotorboat/ProjectMotorboat/nlog.config create mode 100644 ProjectMotorboat/ProjectMotorboat/serilogConfig.json diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs index 128367e..7041dfa 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs @@ -1,5 +1,6 @@ using ProjectMotorboat.CollectionGenericObjects; using ProjectMotorboat.Drownings; +using ProjectMotorboat.Exceptions; namespace ProjectMotorboat.CollectionGenericObjects; @@ -16,9 +17,8 @@ public abstract class AbstractCompany protected ICollectionGenericObjects? _collection = null; - - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) { _pictureWidth = picWidth; @@ -49,8 +49,15 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningBoat? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningBoat? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException e) + { } + catch (PositionOutOfCollectionException e) + { } } return bitmap; diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/HarborService.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/HarborService.cs index be39f68..b262de5 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/HarborService.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/HarborService.cs @@ -1,5 +1,5 @@ -using ProjectMotorboat.CollectionGenericObjects; -using ProjectMotorboat.Drownings; +using ProjectMotorboat.Drownings; +using ProjectMotorboat.Exceptions; namespace ProjectMotorboat.CollectionGenericObjects; @@ -36,12 +36,13 @@ public class HarborService : AbstractCompany for (int i = 0; i < (_collection?.Count ?? 0); i++) { - if (_collection.Get(i) != null) + try { _collection.Get(i).SetPictureSize(_pictureWidth, _pictureHeight); _collection.Get(i).SetPosition(_placeSizeWidth * boatWidth + 20, boatHeight * _placeSizeHeight + 20); } - + catch (ObjectNotFoundException) { } + catch (PositionOutOfCollectionException e) { } if (boatWidth < width - 1) boatWidth++; else diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs index b9de053..0de7f64 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs @@ -48,7 +48,7 @@ where T : class _collection = new(); } - public T? Get(int position) + public T Get(int position) { //TODO выброс ошибки если выход за границу if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); @@ -56,7 +56,6 @@ where T : class } public int Insert(T obj) { - // TODO выброс ошибки если переполнение if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); @@ -76,7 +75,8 @@ where T : class public T Remove(int position) { // TODO если выброс за границу - if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); + + if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); T obj = _collection[position]; _collection.RemoveAt(position); return obj; diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs index 09046a9..bf145fa 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs @@ -40,68 +40,76 @@ public class MassiveGenericObjects : ICollectionGenericObjects _collection = Array.Empty(); } - public T Get(int position) + public T? Get(int position) { - // TODO выброс ошибки если выход за границу - // TODO выброс ошибки если объект пустой - if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) throw new ObjectNotFoundException(position); return _collection[position]; } public int Insert(T obj) { - // TODO выброс ошибки если переполнение - int index = 0; - while (index < _collection.Length) + for (int i = 0; i < Count; i++) { - if (_collection[index] == null) + if (_collection[i] == null) { - _collection[index] = obj; - return index; + _collection[i] = obj; + return i; } - ++index; } + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - // TODO выброс ошибки если выход за границу - if (position >= _collection.Length || position < 0) 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 position; - } - int index = position + 1; - while (index < _collection.Length) - { - if (_collection[index] == null) + bool pushed = false; + for (int index = position + 1; index < Count; index++) { - _collection[index] = obj; - return index; + if (_collection[index] == null) + { + position = index; + pushed = true; + break; + } } - index++; - } - index = position - 1; - while (index >= 0) - { - if (_collection[index] == null) + + if (!pushed) { - _collection[index] = obj; - return index; + for (int index = position - 1; index >= 0; index--) + { + if (_collection[index] == null) + { + position = index; + pushed = true; + break; + } + } + } + + if (!pushed) + { + throw new CollectionOverflowException(Count); } - index--; } - throw new CollectionOverflowException(Count); + + // вставка + _collection[position] = obj; + return position; } public T Remove(int position) { - // TODO выброс ошибки если объект пустой - if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); + // проверка позиции + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + if (_collection[position] == null) throw new ObjectNotFoundException(position); - T removeObj = _collection[position]; + + T? temp = _collection[position]; _collection[position] = null; - return removeObj; + return temp; } public IEnumerable GetItems() @@ -115,3 +123,4 @@ public class MassiveGenericObjects : ICollectionGenericObjects + diff --git a/ProjectMotorboat/ProjectMotorboat/Exceptions/CollectionOverflowException.cs b/ProjectMotorboat/ProjectMotorboat/Exceptions/CollectionOverflowException.cs index 34abfee..b7f71c2 100644 --- a/ProjectMotorboat/ProjectMotorboat/Exceptions/CollectionOverflowException.cs +++ b/ProjectMotorboat/ProjectMotorboat/Exceptions/CollectionOverflowException.cs @@ -1,16 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; + using System.Runtime.Serialization; -using System.Text; -using System.Threading.Tasks; namespace ProjectMotorboat.Exceptions; [Serializable] internal class CollectionOverflowException : ApplicationException { - public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество count" + count) { } + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое количество" + count) { } public CollectionOverflowException() : base() { } diff --git a/ProjectMotorboat/ProjectMotorboat/Exceptions/ObjectNotFoundException.cs b/ProjectMotorboat/ProjectMotorboat/Exceptions/ObjectNotFoundException.cs index e5a4cad..07c8c83 100644 --- a/ProjectMotorboat/ProjectMotorboat/Exceptions/ObjectNotFoundException.cs +++ b/ProjectMotorboat/ProjectMotorboat/Exceptions/ObjectNotFoundException.cs @@ -9,7 +9,7 @@ namespace ProjectMotorboat.Exceptions; [Serializable] internal class ObjectNotFoundException : ApplicationException { - public ObjectNotFoundException(int i) : base("В коллекции превышено допустимое количество count" + i) { } + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } public ObjectNotFoundException() : base() { } diff --git a/ProjectMotorboat/ProjectMotorboat/Exceptions/PositionOutOfCollectionException.cs b/ProjectMotorboat/ProjectMotorboat/Exceptions/PositionOutOfCollectionException.cs index 9692550..093c397 100644 --- a/ProjectMotorboat/ProjectMotorboat/Exceptions/PositionOutOfCollectionException.cs +++ b/ProjectMotorboat/ProjectMotorboat/Exceptions/PositionOutOfCollectionException.cs @@ -10,7 +10,7 @@ namespace ProjectMotorboat.Exceptions; internal class PositionOutOfCollectionException : ApplicationException { - public PositionOutOfCollectionException(int i) : base("В коллекции превышено допустимое количество count" + i) { } + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } public PositionOutOfCollectionException() : base() { } diff --git a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs index 4cf7e32..cb88150 100644 --- a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs +++ b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs @@ -14,7 +14,7 @@ public partial class FormBoatCollection : Form private AbstractCompany? _company = null; private readonly ILogger _logger; - + public FormBoatCollection(ILogger logger) { InitializeComponent(); @@ -23,13 +23,13 @@ public partial class FormBoatCollection : Form _logger.LogInformation("Форма загрузилась"); } - + private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e) { panelCompanyTools.Enabled = false; } - + private void ButtonAddBoat_Click(object sender, EventArgs e) { FormBoatConfig form = new(); @@ -37,30 +37,28 @@ public partial class FormBoatCollection : Form form.AddEvent(SetBoat); } - private void SetBoat(DrawningBoat? boat) + private void SetBoat(DrawningBoat boat) { + if (_company == null || boat == null) + { + return; + } try { - if (_company == null || boat == null) - { - return; - } - if (_company + boat != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - _logger.LogInformation("Добавлен объект: " + boat.GetDataForSave()); - } + var res = _company + boat; + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Объект добавлен под индексом {res}"); + pictureBox.Image = _company.Show(); } - catch (ObjectNotFoundException) { } - catch (CollectionOverflowException ex) + catch (Exception ex) { - MessageBox.Show("Не удалось добавить объект"); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } - + private void ButtonRemoveBoat_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) @@ -68,7 +66,8 @@ public partial class FormBoatCollection : Form return; } - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) { return; } @@ -76,21 +75,21 @@ public partial class FormBoatCollection : Form int pos = Convert.ToInt32(maskedTextBox.Text); try { - if (_company - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); - _logger.LogInformation("Удален объект по позиции " + pos); - } + var res = _company - pos; + MessageBox.Show("Объект удален"); + _logger.LogInformation($"Объект удален под индексом {pos}"); + pictureBox.Image = _company.Show(); } catch (Exception ex) { - MessageBox.Show("Не удалось удалить объект"); - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show(ex.Message, "Не удалось удалить объект", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } } - + + private void ButtonGoToCheck_Click(object sender, EventArgs e) { if (_company == null) @@ -100,31 +99,27 @@ public partial class FormBoatCollection : Form DrawningBoat? boat = null; int counter = 100; - try + while (boat == null) { - while (boat == null) + boat = _company.GetRandomObject(); + counter--; + if (counter <= 0) { - boat = _company.GetRandomObject(); - counter--; - if (counter <= 0) - { - break; - } + break; } - FormMotorboat Form = new() - { - SetBoat = boat - }; - Form.ShowDialog(); } - catch (Exception ex) - + if (boat == null) { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + return; } + FormMotorboat form = new() + { + SetBoat = boat + }; + form.ShowDialog(); } - + private void ButtonRefresh_Click(object sender, EventArgs e) { if (_company == null) @@ -137,59 +132,54 @@ public partial class FormBoatCollection : Form private void ButtonCollectionAdd_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) + if (string.IsNullOrEmpty(textBoxCollectionName.Text) || + (!radioButtonList.Checked && !radioButtonMassive.Checked)) { MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } + CollectionType collectionType = CollectionType.None; + if (radioButtonMassive.Checked) + { + collectionType = CollectionType.Massive; + } + else if (radioButtonList.Checked) + { + collectionType = CollectionType.List; + } + try { - CollectionType collectionType = CollectionType.None; - if (radioButtonMassive.Checked) - { - collectionType = CollectionType.Massive; - } - else if (radioButtonList.Checked) - { - collectionType = CollectionType.List; - } _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавление коллекции"); RerfreshListBoxItems(); - _logger.LogInformation("Коллекция добавлена " + textBoxCollectionName.Text); } catch (Exception ex) { - _logger.LogError("Ошибка: {Message}", ex.Message); + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); } - RerfreshListBoxItems(); + } private void ButtonCollectionDel_Click(object sender, EventArgs e) { - - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); return; } - try + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) { - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) - { - return; - } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); - _logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена"); - } - catch (Exception ex) - { - _logger.LogError("Ошибка: {Message}", ex.Message); + return; } + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Коллекция удалена"); + RerfreshListBoxItems(); } private void RerfreshListBoxItems() @@ -213,7 +203,8 @@ public partial class FormBoatCollection : Form return; } - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + ICollectionGenericObjects? collection = + _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; if (collection == null) { MessageBox.Show("Коллекция не проинициализирована"); @@ -224,13 +215,13 @@ public partial class FormBoatCollection : Form { case "Хранилище": _company = new HarborService(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Компания создана"); break; } panelCompanyTools.Enabled = true; RerfreshListBoxItems(); } - private void SaveToolStripMenuItem_Click(object sender, EventArgs e) { if (saveFileDialog.ShowDialog() == DialogResult.OK) @@ -243,7 +234,7 @@ public partial class FormBoatCollection : Form } catch (Exception ex) { - MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } } @@ -256,17 +247,16 @@ public partial class FormBoatCollection : Form try { _storageCollection.LoadData(openFileDialog.FileName); - MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); RerfreshListBoxItems(); + MessageBox.Show("Загрузка прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); _logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName); } catch (Exception ex) { - - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Загрузка не выполнена", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); _logger.LogError("Ошибка: {Message}", ex.Message); } } - } + } diff --git a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx index ee1748a..42ce85b 100644 --- a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx +++ b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.resx @@ -126,4 +126,7 @@ 310, 17 + + 51 + \ No newline at end of file diff --git a/ProjectMotorboat/ProjectMotorboat/Program.cs b/ProjectMotorboat/ProjectMotorboat/Program.cs index 88f1800..709fd90 100644 --- a/ProjectMotorboat/ProjectMotorboat/Program.cs +++ b/ProjectMotorboat/ProjectMotorboat/Program.cs @@ -1,34 +1,44 @@ +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NLog.Extensions.Logging; +using Serilog; -namespace ProjectMotorboat +namespace ProjectMotorboat; + +internal static class Program { - internal static class Program + [STAThread] + static void Main() { - /// - /// The main entry point for the application. - /// - [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()) { - // To customize application configuration such as set high DPI settings or default font, - // see https://aka.ms/applicationconfiguration. - ServiceCollection services = new(); - ApplicationConfiguration.Initialize(); - 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"); - }); - } + } + private static void ConfigureServices(ServiceCollection services) + { + 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: $"{pathNeed}serilogConfig.json", optional: false, reloadOnChange: true) + .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/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj b/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj index 2dc50c1..83076f6 100644 --- a/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj +++ b/ProjectMotorboat/ProjectMotorboat/ProjectMotorboat.csproj @@ -13,10 +13,12 @@ + + - + Always diff --git a/ProjectMotorboat/ProjectMotorboat/nlog.config b/ProjectMotorboat/ProjectMotorboat/nlog.config deleted file mode 100644 index fc13552..0000000 --- a/ProjectMotorboat/ProjectMotorboat/nlog.config +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/ProjectMotorboat/ProjectMotorboat/serilogConfig.json b/ProjectMotorboat/ProjectMotorboat/serilogConfig.json new file mode 100644 index 0000000..9a6ec38 --- /dev/null +++ b/ProjectMotorboat/ProjectMotorboat/serilogConfig.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": "Motorboat" + } + } +} -- 2.25.1 From e5657c372eb27a81c6546ea338525dce3e9f4350 Mon Sep 17 00:00:00 2001 From: Osyagina_Anna Date: Thu, 2 May 2024 11:55:16 +0400 Subject: [PATCH 4/4] LabWork07 --- .../ProjectMotorboat/BoatDelegate.cs | 6 ----- .../AbstractCompany.cs | 2 +- .../CollectionType.cs | 8 +------ .../ICollectionGenericObjects.cs | 8 +------ .../ListGenericObjects.cs | 22 ++----------------- .../MassiveGenericObjects.cs | 4 ---- .../StorageCollection.cs | 5 ----- .../Drownings/DirectionType.cs | 6 +---- .../Drownings/DrawningBoat.cs | 18 ++++++--------- .../Drownings/DrawningMotorboat.cs | 3 --- .../Drownings/ExtentionDrawningBoat.cs | 14 ------------ .../ProjectMotorboat/FormBoatCollection.cs | 2 -- .../ProjectMotorboat/FormBoatConfig.cs | 12 ---------- .../MovementStrategy/AbstractStrategy.cs | 7 +----- .../MovementStrategy/IMoveableObject.cs | 6 +---- .../MovementStrategy/MoveToBorder.cs | 6 +---- .../MovementStrategy/MoveToCenter.cs | 7 +----- .../MovementStrategy/MoveableBoat.cs | 6 +---- .../MovementStrategy/MovementDirection.cs | 8 +------ .../MovementStrategy/ObjectParameters.cs | 8 +------ .../MovementStrategy/StrategyStatus.cs | 7 +----- ProjectMotorboat/ProjectMotorboat/Program.cs | 1 - 22 files changed, 21 insertions(+), 145 deletions(-) diff --git a/ProjectMotorboat/ProjectMotorboat/BoatDelegate.cs b/ProjectMotorboat/ProjectMotorboat/BoatDelegate.cs index d7c5e5d..dc0416c 100644 --- a/ProjectMotorboat/ProjectMotorboat/BoatDelegate.cs +++ b/ProjectMotorboat/ProjectMotorboat/BoatDelegate.cs @@ -1,10 +1,4 @@ using ProjectMotorboat.Drownings; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace ProjectMotorboat; public delegate void BoatDelegate(DrawningBoat car); \ No newline at end of file diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs index 7041dfa..707164c 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/AbstractCompany.cs @@ -1,4 +1,4 @@ -using ProjectMotorboat.CollectionGenericObjects; + using ProjectMotorboat.Drownings; using ProjectMotorboat.Exceptions; diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/CollectionType.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/CollectionType.cs index eb3ec09..0ba2999 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/CollectionType.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/CollectionType.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectMotorboat.CollectionGenericObjects; +namespace ProjectMotorboat.CollectionGenericObjects; public enum CollectionType { diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs index 155355d..9434625 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectMotorboat.CollectionGenericObjects; +namespace ProjectMotorboat.CollectionGenericObjects; public interface ICollectionGenericObjects diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs index 0de7f64..3b8480f 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/ListGenericObjects.cs @@ -1,26 +1,16 @@ using ProjectMotorboat.Exceptions; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace ProjectMotorboat.CollectionGenericObjects; public class ListGenericObjects : ICollectionGenericObjects where T : class { - /// - /// Список объектов, которые храним - /// + private readonly List _collection; public CollectionType GetCollectionType => CollectionType.List; - /// - /// Максимально допустимое число объектов в списке - /// + private int _maxCount; public int Count => _collection.Count; @@ -40,9 +30,6 @@ where T : class } } - /// - /// Конструктор - /// public ListGenericObjects() { _collection = new(); @@ -50,13 +37,11 @@ where T : class public T Get(int position) { - //TODO выброс ошибки если выход за границу if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) { - // TODO выброс ошибки если переполнение if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); return Count; @@ -64,8 +49,6 @@ where T : class public int Insert(T obj, int position) { - // TODO выброс ошибки если переполнение - // TODO выброс ошибки если за границу if (Count == _maxCount) throw new CollectionOverflowException(Count); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); _collection.Insert(position, obj); @@ -74,7 +57,6 @@ where T : class public T Remove(int position) { - // TODO если выброс за границу if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); T obj = _collection[position]; diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs index bf145fa..fb824d5 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/MassiveGenericObjects.cs @@ -61,7 +61,6 @@ public class MassiveGenericObjects : ICollectionGenericObjects } public int Insert(T obj, int position) { - // проверка позиции if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (_collection[position] != null) @@ -95,14 +94,11 @@ public class MassiveGenericObjects : ICollectionGenericObjects throw new CollectionOverflowException(Count); } } - - // вставка _collection[position] = obj; return position; } public T Remove(int position) { - // проверка позиции if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); if (_collection[position] == null) throw new ObjectNotFoundException(position); diff --git a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs index b5aab3c..93aaf8b 100644 --- a/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectMotorboat/ProjectMotorboat/CollectionGenericObjects/StorageCollection.cs @@ -1,11 +1,6 @@ using ProjectMotorboat.Drownings; using ProjectMotorboat.Exceptions; -using System; -using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; - namespace ProjectMotorboat.CollectionGenericObjects; public class StorageCollection diff --git a/ProjectMotorboat/ProjectMotorboat/Drownings/DirectionType.cs b/ProjectMotorboat/ProjectMotorboat/Drownings/DirectionType.cs index 1741509..8736b4f 100644 --- a/ProjectMotorboat/ProjectMotorboat/Drownings/DirectionType.cs +++ b/ProjectMotorboat/ProjectMotorboat/Drownings/DirectionType.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + namespace ProjectMotorboat.Drownings { diff --git a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs index 9c9321a..dfd9d01 100644 --- a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs +++ b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningBoat.cs @@ -1,9 +1,5 @@ using ProjectMotorboat.Entities; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + namespace ProjectMotorboat.Drownings; @@ -114,28 +110,28 @@ public class DrawningBoat } switch (direction) { - //влево + case DirectionType.Left: if (_startPosX.Value - EntityBoat.Step > 0) { _startPosX -= (int)EntityBoat.Step; } return true; - //вверх + case DirectionType.Up: if (_startPosY.Value - EntityBoat.Step > 0) { _startPosY -= (int)EntityBoat.Step; } return true; - // вправо + case DirectionType.Right: if (_startPosX.Value + EntityBoat.Step + _drawningBoatWidth < _pictureWidth) { _startPosX += (int)EntityBoat.Step; } return true; - //вниз + case DirectionType.Down: if (_startPosY.Value + EntityBoat.Step + _drawningBoatHeight < _pictureHeight) { @@ -155,7 +151,7 @@ public class DrawningBoat Pen pen = new(Color.Black); Brush mainBrush = new SolidBrush(EntityBoat.BodyColor); - // корпус + Point[] hull = new Point[] { new Point(_startPosX.Value + 5, _startPosY.Value + 0), @@ -167,7 +163,7 @@ public class DrawningBoat g.FillPolygon(mainBrush, hull); g.DrawPolygon(pen, hull); - // основная часть + Brush blockBrush = new SolidBrush(EntityBoat.BodyColor); g.FillRectangle(blockBrush, _startPosX.Value + 20, _startPosY.Value + 15, 80, 40); g.DrawRectangle(pen, _startPosX.Value + 20, _startPosY.Value + 15, 80, 40); diff --git a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs index fcda9e0..3c5a389 100644 --- a/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs +++ b/ProjectMotorboat/ProjectMotorboat/Drownings/DrawningMotorboat.cs @@ -26,15 +26,12 @@ public class DrawningMotorboat : DrawningBoat Brush additionalBrush = new SolidBrush(motorboat.AdditionalColor); base.DrawTransport(g); - - // стекло впереди if (motorboat.Glass) { Brush glassBrush = new SolidBrush(Color.LightBlue); g.FillEllipse(glassBrush, _startPosX.Value + 20, _startPosY.Value + 15, 100, 40); g.DrawEllipse(pen, _startPosX.Value + 20, _startPosY.Value + 15, 100, 40); } - // двигатель if (motorboat.Motor) { Brush engineBrush = new diff --git a/ProjectMotorboat/ProjectMotorboat/Drownings/ExtentionDrawningBoat.cs b/ProjectMotorboat/ProjectMotorboat/Drownings/ExtentionDrawningBoat.cs index 93a04ba..b100371 100644 --- a/ProjectMotorboat/ProjectMotorboat/Drownings/ExtentionDrawningBoat.cs +++ b/ProjectMotorboat/ProjectMotorboat/Drownings/ExtentionDrawningBoat.cs @@ -8,16 +8,8 @@ using System.Threading.Tasks; namespace ProjectMotorboat.Drownings; public static class ExtentionDrawningBoat { - /// - /// Разделитель для записи информации по объекту в файл - /// private static readonly string _separatorForObject = ":"; - /// - /// Создание объекта из строки - /// - /// - /// public static DrawningBoat? CreateDrawningBoat(this string info) { string[] strs = info.Split(_separatorForObject); @@ -34,12 +26,6 @@ public static class ExtentionDrawningBoat } return null; } - - /// - /// Получение данных для сохранения в файл - /// - /// - /// public static string GetDataForSave(this DrawningBoat drawningBoat) { string[]? array = drawningBoat?.EntityBoat?.GetStringRepresentation(); diff --git a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs index cb88150..c11963e 100644 --- a/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs +++ b/ProjectMotorboat/ProjectMotorboat/FormBoatCollection.cs @@ -1,8 +1,6 @@ using Microsoft.Extensions.Logging; using ProjectMotorboat.CollectionGenericObjects; using ProjectMotorboat.Drownings; -using ProjectMotorboat.Exceptions; -using System.Windows.Forms; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrackBar; namespace ProjectMotorboat; diff --git a/ProjectMotorboat/ProjectMotorboat/FormBoatConfig.cs b/ProjectMotorboat/ProjectMotorboat/FormBoatConfig.cs index cdcba04..9f80f39 100644 --- a/ProjectMotorboat/ProjectMotorboat/FormBoatConfig.cs +++ b/ProjectMotorboat/ProjectMotorboat/FormBoatConfig.cs @@ -1,15 +1,5 @@ using ProjectMotorboat.Drownings; using ProjectMotorboat.Entities; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; - namespace ProjectMotorboat { public partial class FormBoatConfig : Form @@ -81,11 +71,9 @@ namespace ProjectMotorboat private void Panel_MouseDown(object? sender, MouseEventArgs e) { - // TODO отправка цвета в Drag&Drop (sender as Control)?.DoDragDrop((sender as Control).BackColor, DragDropEffects.Move | DragDropEffects.Copy); } - // Логика смены цветов: основного и дополнительного (для продвинутого объекта) private void LabelBodyColor_DragEnter(object sender, DragEventArgs e) { if (e.Data?.GetDataPresent(typeof(Color)) ?? false) diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/AbstractStrategy.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/AbstractStrategy.cs index 3a1d329..dff9ae5 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/AbstractStrategy.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/AbstractStrategy.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - + namespace ProjectMotorboat.MovementStrategy; diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/IMoveableObject.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/IMoveableObject.cs index 898afa6..593b279 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/IMoveableObject.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/IMoveableObject.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + namespace ProjectMotorboat.MovementStrategy; diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToBorder.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToBorder.cs index 3da281d..03b0866 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToBorder.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToBorder.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + namespace ProjectMotorboat.MovementStrategy; public class MoveToBorder : AbstractStrategy diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToCenter.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToCenter.cs index 08b425a..7538fc1 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToCenter.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveToCenter.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - + namespace ProjectMotorboat.MovementStrategy; public class MoveToCenter : AbstractStrategy { diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveableBoat.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveableBoat.cs index 6e59fee..0b43cfe 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveableBoat.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MoveableBoat.cs @@ -1,9 +1,5 @@ using ProjectMotorboat.Drownings; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; + namespace ProjectMotorboat.MovementStrategy; diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MovementDirection.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MovementDirection.cs index 329e8d9..a79ea1f 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MovementDirection.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/MovementDirection.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectMotorboat.MovementStrategy; +namespace ProjectMotorboat.MovementStrategy; public enum MovementDirection { diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/ObjectParameters.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/ObjectParameters.cs index 51bb02b..254e951 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/ObjectParameters.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/ObjectParameters.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace ProjectMotorboat.MovementStrategy; +namespace ProjectMotorboat.MovementStrategy; public class ObjectParameters { diff --git a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/StrategyStatus.cs b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/StrategyStatus.cs index e4b58f8..85a9fc8 100644 --- a/ProjectMotorboat/ProjectMotorboat/MovementStrategy/StrategyStatus.cs +++ b/ProjectMotorboat/ProjectMotorboat/MovementStrategy/StrategyStatus.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - + namespace ProjectMotorboat.MovementStrategy; public enum StrategyStatus diff --git a/ProjectMotorboat/ProjectMotorboat/Program.cs b/ProjectMotorboat/ProjectMotorboat/Program.cs index 709fd90..35730ce 100644 --- a/ProjectMotorboat/ProjectMotorboat/Program.cs +++ b/ProjectMotorboat/ProjectMotorboat/Program.cs @@ -1,7 +1,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; -using NLog.Extensions.Logging; using Serilog; namespace ProjectMotorboat; -- 2.25.1