diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs index 172b0c8..a7df920 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AbstractCompany.cs @@ -1,12 +1,13 @@ using Microsoft.VisualBasic; using ProjectRoadTrain.Drawnings; +using ProjectRoadTrain.Exceptions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ProjectElectroTrans.CollectionGenericObjects; +namespace ProjectRoadTrain.CollectionGenericObjects; /// /// Абстракция компании, хранящий коллекцию автомобилей @@ -41,7 +42,7 @@ public abstract class AbstractCompany /// /// Вычисление максимального количества элементов, который можно разместить в окне /// - private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + private int GetMaxCount => (_pictureWidth / _placeSizeWidth) * (_pictureHeight / _placeSizeHeight); /// /// Конструктор @@ -63,9 +64,9 @@ public abstract class AbstractCompany /// Компания /// Добавляемый объект /// - public static int operator +(AbstractCompany company, DrawningTrain trains) + public static int operator +(AbstractCompany company, DrawningTrain train) { - return company._collection.Insert(trains); + return company._collection.Insert(train); } /// @@ -78,10 +79,7 @@ public abstract class AbstractCompany { return company._collection?.Remove(position); } - public static bool operator <(AbstractCompany company1, AbstractCompany company2) => company1._collection.Count < company2._collection.Count; - - public static bool operator >(AbstractCompany company1, AbstractCompany company2) => company1._collection.Count > company2._collection.Count; - + /// /// Получение случайного объекта из коллекции @@ -106,8 +104,19 @@ public abstract class AbstractCompany SetObjectsPosition(); for (int i = 0; i < (_collection?.Count ?? 0); ++i) { - DrawningTrain? obj = _collection?.Get(i); - obj?.DrawTransport(graphics); + try + { + DrawningTrain? obj = _collection?.Get(i); + obj?.DrawTransport(graphics); + } + catch (ObjectNotFoundException e) + { + // Relax Man ;) + } + catch (PositionOutOfCollectionException e) + { + // Relax Man ;) + } } return bitmap; diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AutoParkService.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AutoParkService.cs index 62cd451..52081c1 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AutoParkService.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/AutoParkService.cs @@ -1,11 +1,12 @@ using ProjectRoadTrain.Drawnings; +using ProjectRoadTrain.Exceptions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -namespace ProjectElectroTrans.CollectionGenericObjects; +namespace ProjectRoadTrain.CollectionGenericObjects; public class AutoParkService : AbstractCompany @@ -43,13 +44,25 @@ public class AutoParkService : AbstractCompany { for (int j = 0; j < _pictureHeight / _placeSizeHeight; j++) { - DrawningTrain? drawningTrain = _collection?.Get(n); - n++; - if (drawningTrain != null) + try { - drawningTrain.SetPictureSize(_pictureWidth, _pictureHeight); - drawningTrain.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); + DrawningTrain? drawingTrans = _collection?.Get(n); + if (drawingTrans != null) + { + drawingTrans.SetPictureSize(_pictureWidth, _pictureHeight); + drawingTrans.SetPosition(i * _placeSizeWidth + 5, j * _placeSizeHeight + 5); + } } + catch (ObjectNotFoundException e) + { + // Relax Man ;) + } + catch (PositionOutOfCollectionException e) + { + // Relax Man ;) + } + + n++; } } } diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs index 58ab71b..e84d42b 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/ListGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectRoadTrain.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -21,10 +22,7 @@ public class ListGenericObjects : ICollectionGenericObjects public int MaxCount { - get - { - return Count; - } + get { return Count; } set { if (value > 0) @@ -44,22 +42,17 @@ public class ListGenericObjects : ICollectionGenericObjects _collection = new(); } - public T? Get(int position) + public T Get(int position) { - - if (position < 0 || position > _collection.Count - 1) - { - return null; - } + if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); return _collection[position]; } public int Insert(T obj) { - if (_collection.Count + 1 > _maxCount) { return 0; } + if (Count == _maxCount) throw new CollectionOverflowException(Count); _collection.Add(obj); - - return 1; + return Count; } public IEnumerable GetItems() { @@ -70,23 +63,17 @@ public class ListGenericObjects : ICollectionGenericObjects } public int Insert(T obj, int position) { - if (_collection.Count + 1 < _maxCount) { return 0; } - if (position > _collection.Count || position < 0) - { - return 0; - } + 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) { - if (position > _collection.Count || position < 0) - { - return null; - } - T temp = _collection[position]; + if (position >= _collection.Count || position < 0) throw new PositionOutOfCollectionException(position); + T obj = _collection[position]; _collection.RemoveAt(position); - return temp; + return obj; } } diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs index d46bcae..6d70ac0 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/MassiveGenericObjects.cs @@ -1,4 +1,5 @@ -using System; +using ProjectRoadTrain.Exceptions; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -45,16 +46,14 @@ public class MassiveGenericObjects : ICollectionGenericObjects public T? Get(int position) { - if (position >= 0 && position < Count) - { - return _collection[position]; - } - - return null; + 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) { + // вставка в свободное место набора for (int i = 0; i < Count; i++) { if (_collection[i] == null) @@ -64,17 +63,17 @@ public class MassiveGenericObjects : ICollectionGenericObjects } } - return -1; + throw new CollectionOverflowException(Count); } public int Insert(T obj, int position) { - - if (position < 0 || position >= Count) - { - return -1; - } + // проверка позиции + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + // проверка, что элемент массива по этой позиции пустой, если нет, то + // ищется свободное место после этой позиции и идет вставка туда + // если нет после, ищем до if (_collection[position] != null) { bool pushed = false; @@ -103,20 +102,26 @@ public class MassiveGenericObjects : ICollectionGenericObjects if (!pushed) { - return position; + throw new CollectionOverflowException(Count); } } + // вставка _collection[position] = obj; return position; } + public T? Remove(int position) { - if (position >= Count || position < 0) return null; - T? myObject = _collection[position]; + // проверка позиции + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + + if (_collection[position] == null) throw new ObjectNotFoundException(position); + + T? temp = _collection[position]; _collection[position] = null; - return myObject; + return temp; } public IEnumerable GetItems() { diff --git a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs index a0a5463..219d840 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/CollectionGenericObjects/StorageCollection.cs @@ -1,5 +1,6 @@ using ProjectRoadTrain.CollectionGenericObjects; using ProjectRoadTrain.Drawnings; +using ProjectRoadTrain.Exceptions; using System; using System.Collections.Generic; using System.Linq; @@ -22,18 +23,18 @@ public class StorageCollection public void AddCollection(string name, CollectionType collectionType) { - if (_storages.ContainsKey(name)) return; - if (collectionType == CollectionType.None) return; - else if (collectionType == CollectionType.Massive) + if (_storages.ContainsKey(name)) throw new CollectionAlreadyExistsException(name); + if (collectionType == CollectionType.None) throw new CollectionTypeException("Пустой тип коллекции"); + if (collectionType == CollectionType.Massive) _storages[name] = new MassiveGenericObjects(); else if (collectionType == CollectionType.List) _storages[name] = new ListGenericObjects(); - } public void DelCollection(string name) { - if (name == null || !_storages.ContainsKey(name)) { return; } - _storages.Remove(name); + if (_storages.ContainsKey(name)) + _storages.Remove(name); + } public ICollectionGenericObjects? this[string name] @@ -58,7 +59,7 @@ public class StorageCollection { if (_storages.Count == 0) { - return false; + throw new EmptyFileExeption(); } if (File.Exists(filename)) @@ -119,14 +120,17 @@ public class StorageCollection using (StreamReader fs = File.OpenText(filename)) { string str = fs.ReadLine(); - if (str == null || str.Length == 0) + if (string.IsNullOrEmpty(str)) { - return false; + throw new FileNotFoundException(filename); + } + if (!str.StartsWith(_collectionKey)) { - return false; + throw new FileFormatException(filename); } + _storages.Clear(); string strs = ""; while ((strs = fs.ReadLine()) != null) @@ -136,29 +140,37 @@ public class StorageCollection { continue; } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); if (collection == null) { - return false; + throw new CollectionTypeException("Не удалось определить тип коллекции:" + record[1]); } + collection.MaxCount = Convert.ToInt32(record[2]); string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); foreach (string elem in set) { - if (elem?.CreateTrain() is T machine) + if (elem?.CreateTrain() is T ship) { - if (collection.Insert(machine) == -1) + try { - return false; + collection.Insert(ship); + } + catch (Exception ex) + { + throw new FileFormatException(filename, ex); } } } + _storages.Add(record[0], collection); } + return true; - } + } } private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) { diff --git a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionAlreadyExistsException.cs b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionAlreadyExistsException.cs new file mode 100644 index 0000000..1e3e9f8 --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionAlreadyExistsException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Exceptions; +[Serializable] +public class CollectionAlreadyExistsException : Exception +{ + public CollectionAlreadyExistsException() : base() { } + public CollectionAlreadyExistsException(string name) : base($"Коллекция {name} уже существует!") { } + public CollectionAlreadyExistsException(string name, Exception exception) : + base($"Коллекция {name} уже существует!", exception) + { } + protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} diff --git a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionInsertException.cs b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionInsertException.cs new file mode 100644 index 0000000..c9bbd3b --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionInsertException.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Exceptions; + +public class CollectionInsertException : Exception +{ + public CollectionInsertException() : base() { } + public CollectionInsertException(string message) : base(message) { } + public CollectionInsertException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionInsertException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionOverflowException.cs b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionOverflowException.cs new file mode 100644 index 0000000..def2c2d --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionOverflowException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Exceptions; +/// +/// Класс, описывающий ошибку переполнения коллекции +/// +[Serializable] +public class CollectionOverflowException : ApplicationException +{ + public CollectionOverflowException(int count) : base("В коллекции превышено допустимое кол-во: count " + count) { } + public CollectionOverflowException() : base() { } + public CollectionOverflowException(string message) : base(message) { } + public CollectionOverflowException(string message, Exception innerException) : base(message, innerException) { } + protected CollectionOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionTypeException.cs b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionTypeException.cs new file mode 100644 index 0000000..c9c30dc --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/CollectionTypeException.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 ProjectRoadTrain.Exceptions; + +[Serializable] + +public class CollectionTypeException : Exception +{ + public CollectionTypeException() : base() { } + public CollectionTypeException(string message) : base(message) { } + public CollectionTypeException(string message, Exception exception) : + base(message, exception) + { } + protected CollectionTypeException(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/EmptyFileExeption.cs b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/EmptyFileExeption.cs new file mode 100644 index 0000000..49d891a --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/EmptyFileExeption.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Exceptions; + +public class EmptyFileExeption : Exception +{ + public EmptyFileExeption(string name) : base($"Файл {name} пустой ") { } + public EmptyFileExeption() : base("В хранилище отсутствуют коллекции для сохранения") { } + public EmptyFileExeption(string name, string message) : base(message) { } + public EmptyFileExeption(string name, string message, Exception exception) : + base(message, exception) + { } + protected EmptyFileExeption(SerializationInfo info, StreamingContext + contex) : base(info, contex) { } +} diff --git a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/ObjectNotFoundException.cs b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/ObjectNotFoundException.cs new file mode 100644 index 0000000..c10cf7a --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/ObjectNotFoundException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace ProjectRoadTrain.Exceptions; + +[Serializable] +public class ObjectNotFoundException : ApplicationException +{ + public ObjectNotFoundException(int i) : base("Не найден объект по позиции " + i) { } + public ObjectNotFoundException() : base() { } + public ObjectNotFoundException(string message) : base(message) { } + public ObjectNotFoundException(string message, Exception innerException) : base(message, innerException) { } + protected ObjectNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/Exceptions/PositionOutOfCollectionException.cs b/ProjectRoadTrain/ProjectRoadTrain/Exceptions/PositionOutOfCollectionException.cs new file mode 100644 index 0000000..d01da3d --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/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 ProjectRoadTrain.Exceptions; + +[Serializable] + +/// +/// Класс, описывающий ошибку выхода за границы коллекции +/// +public class PositionOutOfCollectionException : ApplicationException +{ + public PositionOutOfCollectionException(int i) : base("Выход за границы коллекции. Позиция " + i) { } + public PositionOutOfCollectionException() : base() { } + public PositionOutOfCollectionException(string message) : base(message) { } + public PositionOutOfCollectionException(string message, Exception innerException) : base(message, innerException) { } + protected PositionOutOfCollectionException(SerializationInfo info, StreamingContext context) : base(info, context) { } +} \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs index 7b2b101..50010c3 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.Designer.cs @@ -48,10 +48,17 @@ namespace ProjectRoadTrain labelCollectionName = new Label(); comboBoxSelectCompany = new ComboBox(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog = new OpenFileDialog(); groupBoxTools.SuspendLayout(); panelCompanyTools.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -61,63 +68,12 @@ namespace ProjectRoadTrain groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(820, 0); + groupBoxTools.Location = new Point(952, 0); groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Size = new Size(218, 780); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "инструменты"; - // menuStrip - // - menuStrip = new MenuStrip(); - файлToolStripMenuItem = new ToolStripMenuItem(); - saveToolStripMenuItem = new ToolStripMenuItem(); - loadToolStripMenuItem = new ToolStripMenuItem(); - saveFileDialog = new SaveFileDialog(); - openFileDialog = new OpenFileDialog(); - Controls.Add(menuStrip); - MainMenuStrip = menuStrip; - menuStrip.ResumeLayout(false); - menuStrip.PerformLayout(); - PerformLayout(); - menuStrip.ImageScalingSize = new Size(20, 20); - menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); - menuStrip.Location = new Point(0, 0); - menuStrip.Name = "menuStrip"; - menuStrip.Size = new Size(980, 28); - menuStrip.TabIndex = 6; - menuStrip.Text = "menuStrip1"; - // - // файлToolStripMenuItem - // - файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); - файлToolStripMenuItem.Name = "файлToolStripMenuItem"; - файлToolStripMenuItem.Size = new Size(59, 24); - файлToolStripMenuItem.Text = "Файл"; - // - // saveToolStripMenuItem - // - saveToolStripMenuItem.Name = "saveToolStripMenuItem"; - saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; - saveToolStripMenuItem.Size = new Size(227, 26); - saveToolStripMenuItem.Text = "Сохранение"; - saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; - // - // loadToolStripMenuItem - // - loadToolStripMenuItem.Name = "loadToolStripMenuItem"; - loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; - loadToolStripMenuItem.Size = new Size(227, 26); - loadToolStripMenuItem.Text = "Загрузка"; - loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; - // - // saveFileDialog - // - saveFileDialog.Filter = "txt file | *.txt"; - // - // openFileDialog - // - openFileDialog.Filter = "txt file | *.txt"; // // panelCompanyTools // @@ -295,17 +251,60 @@ namespace ProjectRoadTrain pictureBox.Dock = DockStyle.Fill; pictureBox.Location = new Point(0, 0); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(820, 780); + pictureBox.Size = new Size(952, 780); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(20, 20); + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(952, 28); + menuStrip.TabIndex = 6; + menuStrip.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(59, 24); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(227, 26); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(227, 26); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; + // // FormTrainCollection // AutoScaleDimensions = new SizeF(8F, 20F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(1038, 780); + ClientSize = new Size(1170, 780); + Controls.Add(menuStrip); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + MainMenuStrip = menuStrip; Name = "FormTrainCollection"; Text = "Коллекция камазов"; groupBoxTools.ResumeLayout(false); @@ -314,7 +313,10 @@ namespace ProjectRoadTrain panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion diff --git a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs index 1ea003b..f267c7d 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.cs @@ -1,7 +1,8 @@ -using ProjectElectroTrans.CollectionGenericObjects; -using ProjectRoadTrain.CollectionGenericObjects; +using ProjectRoadTrain.CollectionGenericObjects; using ProjectRoadTrain.Drawnings; using System; +using Microsoft.Extensions.Logging; +using ProjectRoadTrain.Exceptions; using System.Collections.Generic; using System.ComponentModel; using System.Data; @@ -11,331 +12,298 @@ using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -namespace ProjectRoadTrain +namespace ProjectRoadTrain; + +public partial class FormTrainCollection : Form { - public partial class FormTrainCollection : Form + private readonly StorageCollection _storageCollection; + private AbstractCompany? _company = null; + private readonly ILogger _logger; + public FormTrainCollection(ILogger logger) { - private readonly StorageCollection _storageCollection; - private AbstractCompany? _company = null; - public FormTrainCollection() + InitializeComponent(); + _storageCollection = new(); + _logger = logger; + } + private void RerfreshListBoxItems() + { + listBoxCollection.Items.Clear(); + for (int i = 0; i < _storageCollection.Keys?.Count; ++i) { - InitializeComponent(); - _storageCollection = new(); - } - private void RerfreshListBoxItems() - { - listBoxCollection.Items.Clear(); - for (int i = 0; i < _storageCollection.Keys?.Count; ++i) + string? colName = _storageCollection.Keys?[i]; + if (!string.IsNullOrEmpty(colName)) { - string? colName = _storageCollection.Keys?[i]; - if (!string.IsNullOrEmpty(colName)) - { - listBoxCollection.Items.Add(colName); - } + listBoxCollection.Items.Add(colName); } - - } - - private void comboBoxSelectCompany_SelectedIndexChanged(object sender, EventArgs e) - { - switch (comboBoxSelectCompany.Text) - { - case "Хранилище": - _company = new AutoParkService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects()); - break; - } - } - private void ButtonAddTrain_Click(object sender, EventArgs e) - { - FormTrainConfig form = new(); - - form.Show(); - form.AddEvent(SetTrains); - } - - - /// - /// Создание объекта класса-перемещения - /// - /// Тип создаваемого объекта - - /// - /// Получение цвета - /// - /// Генератор случайных чисел - /// - - - /// - /// Удаление объекта - /// - /// - /// - private void ButtonRemoveTrans_Click(object sender, EventArgs e) - { - if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) - { - return; - } - - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - { - return; - } - - int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); - } - } - - /// - /// Передача объекта в другую форму - /// - /// - /// - private void ButtonGoToCheck_Click(object sender, EventArgs e) - { - if (_company == null) - { - return; - } - - DrawningTrain? train = null; - int counter = 100; - while (train == null) - { - train = _company.GetRandomObject(); - counter--; - if (counter <= 0) - { - break; - } - } - - if (train == null) - { - return; - } - - FormRoadTrain form = new() - { - SetTrain = train - }; - form.ShowDialog(); - } - - /// - /// Перерисовка коллекции - /// - /// - /// - private void ButtonRefresh_Click(object sender, EventArgs e) - { - if (_company == null) - { - return; - } - - pictureBox.Image = _company.Show(); - } - - - private void CreateObject(string type) - { - if (_company == null) - { - return; - } - Random random = new(); - DrawningTrain drawningTrain; - switch (type) - { - case nameof(DrawningTrain): - drawningTrain = new DrawningTrain(random.Next(100, 300), random.Next(1000, 3000), GetColor(random)); - break; - case nameof(DrawningRoadTrain): - // вызов диалогового окна для выбора цвета - drawningTrain = new DrawningRoadTrain(random.Next(100, 300), random.Next(1000, 3000), - GetColor(random), - GetColor(random), - Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); - break; - default: - return; - } - - if (_company + drawningTrain != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else - { - _ = MessageBox.Show(drawningTrain.ToString()); - } - } - private static Color GetColor(Random random) - { - Color color = Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)); - ColorDialog dialog = new(); - if (dialog.ShowDialog() == DialogResult.OK) - { - color = dialog.Color; - } - - return color; - } - - - private void SetTrains(DrawningTrain? drawningTrain) - { - if (_company == null || drawningTrain == null) - { - return; - } - - if (_company + drawningTrain != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else - { - _ = MessageBox.Show(drawningTrain.ToString()); - } - } - private void ButtonDelTrain_Click(object sender, EventArgs e) - { - if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) - { - return; - } - - if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - { - return; - } - - int pos = Convert.ToInt32(maskedTextBox.Text); - if (_company - pos != null) - { - MessageBox.Show("Объект удален"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось удалить объект"); - } - } - - private void ButtonCollectionAdd_Click(object sender, EventArgs e) - { - 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; - } - - _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); - RerfreshListBoxItems(); - } - private void SaveToolStripMenuItem_Click(object sender, EventArgs e) - { - if (saveFileDialog.ShowDialog() == DialogResult.OK) - { - if (_storageCollection.SaveData(saveFileDialog.FileName)) - { - MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - else - { - MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - - } - - /// - /// Обработка нажатия "Загрузка" - /// - /// - /// - private void LoadToolStripMenuItem_Click(object sender, EventArgs e) - { - // TODO продумать логику - if (openFileDialog.ShowDialog() == DialogResult.OK) - { - if (_storageCollection.LoadData(openFileDialog.FileName)) - { - MessageBox.Show("Загрузка прошла успешно", - "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); - RerfreshListBoxItems(); - } - else - { - MessageBox.Show("Не сохранилось", "Результат", - MessageBoxButtons.OK, MessageBoxIcon.Error); - } - } - } - private void ButtonCollectionDel_Click(object sender, EventArgs e) - { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) - { - MessageBox.Show("Коллекция не выбрана"); - return; - } - if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) - { - return; - } - _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); - RerfreshListBoxItems(); - } - - private void ButtonCreateCompany_Click(object sender, EventArgs e) - { - if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) - { - MessageBox.Show("Коллекция не выбрана"); - return; - } - - ICollectionGenericObjects? collection = _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; - if (collection == null) - { - MessageBox.Show("Коллекция не проинициализирована"); - return; - } - - switch (comboBoxSelectCompany.Text) - { - case "хранилище": - _company = new AutoParkService(pictureBox.Width, pictureBox.Height, collection); - break; - } - - panelCompanyTools.Enabled = true; - RerfreshListBoxItems(); } } + + private void comboBoxSelectCompany_SelectedIndexChanged(object sender, EventArgs e) + { + switch (comboBoxSelectCompany.Text) + { + case "Хранилище": + _company = new AutoParkService(pictureBox.Width, pictureBox.Height, new MassiveGenericObjects()); + break; + } + } + private void ButtonAddTrain_Click(object sender, EventArgs e) + { + FormTrainConfig form = new(); + + form.Show(); + form.AddEvent(SetTrains); + } + + + /// + /// Создание объекта класса-перемещения + /// + /// Тип создаваемого объекта + + /// + /// Получение цвета + /// + /// Генератор случайных чисел + /// + + + /// + /// Удаление объекта + /// + /// + /// + + + /// + /// Передача объекта в другую форму + /// + /// + /// + private void ButtonGoToCheck_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + DrawningTrain? car = null; + int counter = 100; + while (car == null) + { + car = _company.GetRandomObject(); + counter--; + if (counter <= 0) + { + break; + } + } + + if (car == null) + { + return; + } + + FormRoadTrain form = new() + { + SetTrain = car + }; + form.ShowDialog(); + } + + /// + /// Перерисовка коллекции + /// + /// + /// + private void ButtonRefresh_Click(object sender, EventArgs e) + { + if (_company == null) + { + return; + } + + pictureBox.Image = _company.Show(); + } + + + + + + private void SetTrains(DrawningTrain? drawningTrain) + { + if (_company == null || drawningTrain == null) + { + return; + } + try + { + var res = _company + drawningTrain; + MessageBox.Show("Объект добавлен"); + _logger.LogInformation($"Объект добавлен под индексом {res}"); + pictureBox.Image = _company.Show(); + } + catch (Exception ex) + { + MessageBox.Show($"Объект не добавлен: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); + } + } + private void ButtonDelTrain_Click(object sender, EventArgs e) + { + if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) + { + return; + } + + if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) + { + return; + } + + int pos = Convert.ToInt32(maskedTextBox.Text); + try + { + var res = _company - pos; + MessageBox.Show("Объект удален"); + _logger.LogInformation($"Объект удален под индексом {pos}"); + pictureBox.Image = _company.Show(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Не удалось удалить объект", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); + } + } + + private void ButtonCollectionAdd_Click(object sender, EventArgs e) + { + 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 + { + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); + _logger.LogInformation("Добавление коллекции"); + RerfreshListBoxItems(); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); + } + + } + private void SaveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _storageCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation("Сохранение в файл: {filename}", + saveFileDialog.FileName); + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Результат", + MessageBoxButtons.OK, MessageBoxIcon.Error); + _logger.LogError($"Ошибка: {ex.Message}", ex.Message); + } + } + } + + /// + /// Обработка нажатия "Загрузка" + /// + /// + /// + private void LoadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _storageCollection.LoadData(openFileDialog.FileName); + MessageBox.Show("Загрузка прошла успешно", + "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + _logger.LogInformation($"Загрузка прошла успешно в {openFileDialog.FileName}"); + + RerfreshListBoxItems(); + } + catch (Exception ex) + { + MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, + MessageBoxIcon.Error); + _logger.LogError("Ошибка: {Message}", ex.Message); + } + } + } + private void ButtonCollectionDel_Click(object sender, EventArgs e) + { + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + { + MessageBox.Show("Коллекция не выбрана"); + return; + } + + if (MessageBox.Show("Удалить коллекцию?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != + DialogResult.Yes) + { + return; + } + + _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); + _logger.LogInformation("Коллекция удалена"); + RerfreshListBoxItems(); + } + + private void ButtonCreateCompany_Click(object sender, EventArgs e) + { + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) + { + MessageBox.Show("Коллекция не выбрана"); + return; + } + + ICollectionGenericObjects? collection = + _storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty]; + if (collection == null) + { + MessageBox.Show("Коллекция не проинициализирована"); + return; + } + + switch (comboBoxSelectCompany.Text) + { + case "хранилище": + _company = new AutoParkService(pictureBox.Width, pictureBox.Height, collection); + _logger.LogInformation("Компания создана"); + break; + } + + panelCompanyTools.Enabled = true; + RerfreshListBoxItems(); + } } diff --git a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.resx b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.resx index af32865..9d8f0e9 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.resx +++ b/ProjectRoadTrain/ProjectRoadTrain/FormTrainCollection.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 145, 17 + + + 302, 17 + \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/FormTrainConfig.cs b/ProjectRoadTrain/ProjectRoadTrain/FormTrainConfig.cs index ebef068..62f38a0 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/FormTrainConfig.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/FormTrainConfig.cs @@ -18,7 +18,7 @@ public partial class FormTrainConfig : Form private DrawningTrain? _train; - private event TrainDelegate? TrainDelegate; + private event Action? RoadTrainDelegate; public FormTrainConfig() { InitializeComponent(); @@ -87,9 +87,9 @@ public partial class FormTrainConfig : Form e.Effect = DragDropEffects.None; } } - public void AddEvent(TrainDelegate trainDelegate) + public void AddEvent(Action trainDelegate) { - TrainDelegate += trainDelegate; + RoadTrainDelegate += trainDelegate; } private void labelBodyColor_DragDrop(object sender, DragEventArgs e) { @@ -124,7 +124,7 @@ public partial class FormTrainConfig : Form { if (_train != null) { - TrainDelegate?.Invoke(_train); + RoadTrainDelegate?.Invoke(_train); Close(); } } diff --git a/ProjectRoadTrain/ProjectRoadTrain/Program.cs b/ProjectRoadTrain/ProjectRoadTrain/Program.cs index 2ccde8f..5e2190a 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/Program.cs +++ b/ProjectRoadTrain/ProjectRoadTrain/Program.cs @@ -1,17 +1,36 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Configuration; +using Serilog; +using NLog.Extensions.Logging; + namespace ProjectRoadTrain { 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 FormTrainCollection()); + var services = new ServiceCollection(); + ConfigureServices(services); + using (ServiceProvider serviceProvider = services.BuildServiceProvider()) + { + Application.Run(serviceProvider.GetRequiredService()); + } + } + + private static void ConfigureServices(ServiceCollection services) + { + services.AddSingleton() + .AddLogging(option => + { + option.SetMinimumLevel(LogLevel.Information); + option.AddNLog("nlog.config"); + }); } } } \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/ProjectRoadTrain.csproj b/ProjectRoadTrain/ProjectRoadTrain/ProjectRoadTrain.csproj index 244387d..a40cb7e 100644 --- a/ProjectRoadTrain/ProjectRoadTrain/ProjectRoadTrain.csproj +++ b/ProjectRoadTrain/ProjectRoadTrain/ProjectRoadTrain.csproj @@ -8,6 +8,13 @@ enable + + + + + + + True diff --git a/ProjectRoadTrain/ProjectRoadTrain/nlog.config b/ProjectRoadTrain/ProjectRoadTrain/nlog.config new file mode 100644 index 0000000..5c71e85 --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/nlog.config @@ -0,0 +1,15 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/ProjectRoadTrain/ProjectRoadTrain/serilog.json b/ProjectRoadTrain/ProjectRoadTrain/serilog.json new file mode 100644 index 0000000..fa91ef7 --- /dev/null +++ b/ProjectRoadTrain/ProjectRoadTrain/serilog.json @@ -0,0 +1,15 @@ +{ + "Serilog": { + "Using": [ "Serilog.Sinks.File" ], + "MinimumLevel": "Debug", + "WriteTo": [ + { + "Name": "File", + "Args": { "path": "log.log" } + } + ], + "Properties": { + "Application": "Sample" + } + } +} \ No newline at end of file