diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs index 8bec219..0a55ad4 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/AbstractCompany.cs @@ -1,88 +1,114 @@ -using HoistingCrane.Drawning; -namespace HoistingCrane.CollectionGenericObjects +using HoistingCrane.CollectionGenericObjects; +using HoistingCrane.Drawning; + +public abstract class AbstractCompany { - public abstract class AbstractCompany + /// + /// Размер места (ширина) + /// + protected readonly int _placeSizeWidth = 180; + + /// + /// Размер места (высота) + /// + protected readonly int _placeSizeHeight = 100; + + /// + /// Ширина окна + /// + protected readonly int _pictureWidth; + + /// + /// Высота окна + /// + protected readonly int _pictureHeight; + + /// + /// Коллекция военных кораблей + /// + protected ICollectionGenericObjects? _collection = null; + + /// + /// Вычисление максимального количества элементов, которые можно разместить в окне + /// + private int GetMaxCount => _pictureWidth * _pictureHeight / (_placeSizeWidth * _placeSizeHeight); + + /// + /// Конструктор + /// + /// Ширина окна + /// Высота окна + /// Коллекция военных кораблей + public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects collection) { - /// - /// Ширина ячейки гаража - /// - protected readonly int _placeSizeWidth = 150; - /// - /// Высота ячейки гаража - /// - protected readonly int _placeSizeHeight = 90; - /// - /// Ширина окна - /// - protected readonly int pictureWidth; - /// - /// Высота окна - /// - protected readonly int pictureHeight; - /// - /// Коллекция автомобилей - /// - protected ICollectionGenericObjects? arr = null; - /// - /// Максимальное количество гаражей - /// - private int GetMaxCount - { - get - { - return (pictureWidth * pictureHeight) / (_placeSizeHeight * _placeSizeWidth)-3; - } - } - public AbstractCompany(int picWidth, int picHeight, ICollectionGenericObjects array) - { - pictureWidth = picWidth; - pictureHeight = picHeight; - arr = array; - arr.SetMaxCount = GetMaxCount; - } + _pictureWidth = picWidth; + _pictureHeight = picHeight; + _collection = collection; + _collection.MaxCount = GetMaxCount; + } - public static int operator +(AbstractCompany company, DrawningTrackedVehicle car) - { - return company.arr?.Insert(car) ?? -1; - } - public static DrawningTrackedVehicle operator -(AbstractCompany company, int position) - { - return company.arr?.Remove(position); - } + /// + /// Перегрузка оператора сложения для класса + /// + /// Компания + /// Добавляемый объект + /// + public static int operator +(AbstractCompany company, DrawningTrackedVehicle crane) + { + return company._collection.Insert(crane); + } - public DrawningTrackedVehicle? GetRandomObject() - { - Random rnd = new(); - return arr?.Get(rnd.Next(GetMaxCount)); - } + /// + /// Перегрузка оператора удаления для класса + /// + /// Компания + /// Номер удаляемого объекта + /// + public static DrawningTrackedVehicle operator -(AbstractCompany company, int position) + { + return company._collection.Remove(position); + } - /// - /// Вывод всей коллекции - /// - /// - public Bitmap? Show() - { - Bitmap bitmap = new(pictureWidth, pictureHeight); - Graphics graphics = Graphics.FromImage(bitmap); - DrawBackgound(graphics); + /// + /// Получение случайного объекта из коллекции + /// + /// + public DrawningTrackedVehicle? GetRandomObject() + { + Random rnd = new(); + return arr?.Get(rnd.Next(GetMaxCount)); + } - SetObjectsPosition(); - for (int i = 0; i < (arr?.Count ?? 0); i++) + /// + /// Вывод всей коллекции + /// + /// + public Bitmap? Show() + { + Bitmap bitmap = new(pictureWidth, pictureHeight); + Graphics graphics = Graphics.FromImage(bitmap); + DrawBackgound(graphics); + SetObjectsPosition(); + for (int i = 0; i < (arr?.Count ?? 0); ++i) + { + try { DrawningTrackedVehicle? obj = arr?.Get(i); obj?.DrawTransport(graphics); } - return bitmap; + catch (Exception) { } } - /// - /// Вывод заднего фона - /// - /// - protected abstract void DrawBackgound(Graphics g); - - /// - /// Расстановка объектов - /// - protected abstract void SetObjectsPosition(); + return bitmap; } -} + + /// + /// Вывод заднего фона + /// + /// + protected abstract void DrawBackgound(Graphics g); + + /// + /// Расстановка объектов + /// + protected abstract void SetObjectsPosition(); +} \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs index 22ffa84..93433c2 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/CollectionType.cs @@ -1,5 +1,4 @@ -using System; -namespace HoistingCrane.CollectionGenericObjects +namespace HoistingCrane.CollectionGenericObjects { public enum CollectionType { diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs index 6ba0162..9455238 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/Garage.cs @@ -8,8 +8,8 @@ namespace HoistingCrane.CollectionGenericObjects } protected override void DrawBackgound(Graphics g) { - int width = pictureWidth / _placeSizeWidth; - int height = pictureHeight / _placeSizeHeight; + int width = _pictureWidth / _placeSizeWidth; + int height = _pictureHeight / _placeSizeHeight; Pen pen = new(Color.Black, 3); for (int i = 0; i < width; i++) { @@ -22,18 +22,18 @@ namespace HoistingCrane.CollectionGenericObjects } protected override void SetObjectsPosition() { - int countWidth = pictureWidth / _placeSizeWidth; - int countHeight = pictureHeight / _placeSizeHeight; + int countWidth = _pictureWidth / _placeSizeWidth; + int countHeight = _pictureHeight / _placeSizeHeight; int currentPosWidth = countWidth - 1; int currentPosHeight = countHeight - 1; - - for (int i = 0; i < (arr?.Count ?? 0); i++) + + for (int i = 0; i < (_collection?.Count ?? 0); i++) { - if (arr?.Get(i) != null) + if (_collection?.Get(i) != null) { - arr?.Get(i)?.SetPictureSize(pictureWidth, pictureHeight); - arr?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15); + _collection?.Get(i)?.SetPictureSize(_pictureWidth, _pictureHeight); + _collection?.Get(i)?.SetPosition(_placeSizeWidth * currentPosWidth + 25, _placeSizeHeight * currentPosHeight + 15); } if (currentPosWidth > 0) @@ -47,7 +47,6 @@ namespace HoistingCrane.CollectionGenericObjects { break; } - } } diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs index 007db42..89b4686 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -1,40 +1,55 @@ -namespace HoistingCrane.CollectionGenericObjects +using HoistingCrane.CollectionGenericObjects; + +public interface ICollectionGenericObjects + where T : class { - public interface ICollectionGenericObjects - where T: class - { - /// - /// Кол-во объектов в коллекции - /// - int Count { get; } - /// - /// Максимальное количество элементов - /// - int SetMaxCount { set; } - /// - /// Добавление элемента в коллекцию - /// - /// - /// - int Insert(T obj); - /// - /// Добавление элемента в коллекцию на определенную позицию - /// - /// - /// - /// - int Insert(T obj, int position); - /// - /// Удаление элемента из коллекции по его позиции - /// - /// - /// - T? Remove(int position); - /// - /// Получение объекта коллекции - /// - /// - /// - T? Get(int position); - } -} + /// + /// Количество объектов в коллекции + /// + int Count { get; } + + /// + /// Установка максимального количества элементов + /// + int MaxCount { get; set; } + + /// + /// Добавление объекта в коллекцию + /// + /// Добавляемый объект + /// true - вставка прошла удачно, false - вставка не удалась + int Insert(T obj); + + /// + /// Добавление объекта в коллекцию на конкретную позицию + /// + /// Добавляемый объект + /// Позиция + /// true - вставка прошла удачно, false - вставка не удалась + int Insert(T obj, int position); + + /// + /// Удаление объекта из коллекции с конкретной позиции + /// + /// Позиция + /// true - удаление прошло удачно, false - удаление не удалось + T? Remove(int position); + + /// + /// Получение объекта по позиции + /// + /// Позиция + /// Объект + T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); +} \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs index 251a246..291f5cf 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/ListGenericObjects.cs @@ -1,74 +1,86 @@ -using System; -using System.CodeDom.Compiler; -using System.Windows.Forms.VisualStyles; +using HoistingCrane.Drawning; +using HoistingCrane.Exceptions; +namespace HoistingCrane.CollectionGenericObjects; -namespace HoistingCrane.CollectionGenericObjects +public class ListGenericObjects : ICollectionGenericObjects where T : class { - public class ListGenericObjects : ICollectionGenericObjects where T : class - { - /// - /// Список объектов, которые храним - /// - readonly List list; - /// - /// Конструктор - /// - public ListGenericObjects() - { - list = new List(); - } - /// - /// Максимально допустимое число объектов в списке - /// - private int _maxCount; - public int Count - { - get { return list.Count; } - } - public int SetMaxCount - { - set - { - if (value > 0) - { - _maxCount = value; - } - } - } + /// + /// Список объектов, которые храним + /// + private readonly List _collection; - public T? Get(int position) + /// + /// Максимально допустимое число объектов в списке + /// + private int _maxCount; + + public int Count => _collection.Count; + + public int MaxCount + { + get { - if (position >= Count || position < 0) return null; - return list[position]; - } - public int Insert(T obj) - { - if (Count == _maxCount) - { - return -1; - } - list.Add(obj); return Count; } - public int Insert(T obj, int position) + set { - if (position < 0 || position >= Count || Count == _maxCount) + if (value > 0) { - return -1; + _maxCount = value; } - list.Insert(position, obj); - return position; - } - public T? Remove(int position) - { - if(position >= 0 && position < list.Count) - { - T? temp = list[position]; - list.RemoveAt(position); - return temp; - } - return null; } } -} + + public CollectionType GetCollectionType => CollectionType.List; + + /// + /// Конструктор + /// + public ListGenericObjects() + { + _collection = new(); + } + + public T? Get(int position) + { + // Проверка позиции + if (position >= Count || position < 0) + { + return null; + } + return _collection[position]; + } + + public int Insert(T obj) + { + // Проверка, что не превышено максимальное количество элементов + if (Count == _maxCount) + { + return -1; + } + _collection.Add(obj); + return Count; + } + + public T? Remove(int position) + { + if (position < 0 || position >= list.Count) throw new PositionOutOfCollectionException(position); + T? temp = list[position]; + list.RemoveAt(position); + return temp; + } + + public IEnumerable GetItems() + { + for(int i = 0; i < list.Count; i++) + { + yield return list[i]; + } + } + + public void CollectionSort(IComparer comparer) + { + list.Sort(comparer); + } + } diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs index ed0e4fd..9680bbf 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/MassivGenericObjects.cs @@ -1,89 +1,154 @@ -using System; -namespace HoistingCrane.CollectionGenericObjects +namespace HoistingCrane.CollectionGenericObjects; + +public class MassiveGenericObjects : ICollectionGenericObjects +where T : class { - public class MassivGenericObjects : ICollectionGenericObjects where T : class + private T?[] arr; + public MassivGenericObjects() { - private T?[] arr; - public MassivGenericObjects() + arr = Array.Empty(); + } + public int Count + { + get { return arr.Length; } + } + public int MaxCount + { + get { - arr = Array.Empty(); + return _collection.Length; } - public int Count + + set { - get { return arr.Length; } - } - public int SetMaxCount - { - set + if (value > 0) { - if (value > 0) + if (_collection.Length > 0) { - if (arr.Length > 0) - { - Array.Resize(ref arr, value); - } - else - { - arr = new T?[value]; - } + Array.Resize(ref _collection, value); + } + else + { + _collection = new T?[value]; } } } - public T? Get(int position) - { - if (position >= 0 && position < arr.Length) - { - return arr[position]; + if (arr[i] == null) + { + arr[i] = obj; + return i; + } + } + } + } + throw new CollectionOverflowException(Count); } - return null; - } - - public int Insert(T obj) - { - return Insert(obj, 0); - } - - public int Insert(T obj, int position) - { - - if (position < 0 || position >= Count) + catch (PositionOutOfCollectionException ex) { + MessageBox.Show(ex.Message); return -1; } - - int copyPos = position - 1; - - while (position < Count) + catch (ObjectIsPresentInTheCollectionException ex) { - if (arr[position] == null) - { - arr[position] = obj; - return position; - } - position++; + MessageBox.Show(ex.Message); + return -1; } - while (copyPos > 0) - { - if (arr[copyPos] == null) - { - arr[copyPos] = obj; - return copyPos; - } - copyPos--; - } - - return -1; } public T? Remove(int position) { - if (position >= 0 && position < Count) + if (position < 0 || position >= Count) throw new PositionOutOfCollectionException(position); + if (arr[position] == null) throw new ObjectNotFoundException(position); + T? temp = arr[position]; + arr[position] = null; + return temp; + } + + public IEnumerable GetItems() + { + for (int i = 0; i < arr.Length; i++) { - T? temp = arr[position]; - arr[position] = null; - return temp; + yield return arr[i]; +========= +>>>>>>>>> Temporary merge branch 2 } - return null; + } + public void CollectionSort(IComparer comparer) + { + T[] notNullArr = arr.OfType().ToArray(); + Array.Sort(notNullArr, comparer); + Array.Copy(notNullArr, 0, arr, 0, notNullArr.Length); } } -} + + public T? Get(int position) + { + // Проверка позиции + if (position < 0 || position >= Count) + { + return null; + } + return _collection[position]; + } + + public int Insert(T obj) + { + // Вставка в свободное место набора + return Insert(obj, 0); + } + + public int Insert(T obj, int position) + { + // Проверка позиции + if (position < 0 || position >= Count) + { + return -1; + } + // Проверка, что элемент массива по этой позиции пустой + if (_collection[position] == null) + { + _collection[position] = obj; + return position; + } + //Свободное место после этой позиции + for (int i = position + 1; i < Count; i++) + { + 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; + } + } + return -1; + } + + public T? Remove(int position) + { + // Проверка позиции и наличия объекта + if (position < 0 || position >= Count || _collection[position] == null) + { + return null; + } + // Удаление объекта из массива + T? obj = _collection[position]; + _collection[position] = null; + return obj; + } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } +} \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs b/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs index 4f6c693..7e7b79e 100644 --- a/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs +++ b/HoistingCrane/HoistingCrane/CollectionGenericObjects/StorageCollection.cs @@ -1,62 +1,218 @@ -using System; -namespace HoistingCrane.CollectionGenericObjects +using HoistingCrane.Drawning; +namespace HoistingCrane.CollectionGenericObjects; + +public class StorageCollection +where T : DrawningTrackedVehicle { - public class StorageCollection where T : class + /// + /// Словарь (хранилище) с коллекциями + /// + readonly Dictionary> _storages; + + /// + /// Возвращение списка названий коллекций + /// + public List Keys => _storages.Keys.ToList(); + + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + + /// + /// Конструктор + /// + public StorageCollection() { - /// - /// Словарь (хранилище) с коллекциями - /// - readonly Dictionary> dict; - /// - /// Возвращение списка названий коллекций - /// - public List Keys => dict.Keys.ToList(); - /// - /// Конструктор - /// - public StorageCollection() + _storages = new Dictionary>(); + } + + /// + /// Добавление коллекции в хранилище + /// + /// Название коллекции + /// Тип коллекции + public void AddCollection(string name, CollectionType collectionType) + { + // Проверка, что name не пустой и нет в словаре записи с таким ключом + if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name) || collectionType == CollectionType.None) { - dict = new Dictionary>(); + return; } - /// - /// Добавление коллекции в хранилище - /// - /// Название коллекции - /// тип коллекции - public void AddCollection(string name, CollectionType collectionType) + if (collectionType == CollectionType.Massive) { - if (dict.ContainsKey(name)) return; - if (collectionType == CollectionType.None) return; - else if (collectionType == CollectionType.Massive) - dict[name] = new MassivGenericObjects(); - else if (collectionType == CollectionType.List) - dict[name] = new ListGenericObjects(); + _storages[name] = new MassiveGenericObjects(); } - /// - /// Удаление коллекции - /// - /// Название коллекции - public void DelCollection(string name) + if (collectionType == CollectionType.List) { - if (Keys.Contains(name)) + _storages[name] = new ListGenericObjects(); + } + } + + /// + /// Удаление коллекции + /// + /// Название коллекции + public void DelCollection(string name) + { + if (_storages.ContainsKey(name)) + { + _storages.Remove(name); + } + } + + /// + /// Доступ к коллекции + /// + /// Название коллекции + /// + public ICollectionGenericObjects? this[string name] + { + get + { + if (_storages.ContainsKey(name)) { - dict.Remove(name); + return _storages[name]; } - } - /// - /// Доступ к коллекции - /// - /// Название коллекции - /// - public ICollectionGenericObjects? this[string name] - { - get + else { - if (dict.ContainsKey(name)) - return dict[name]; return null; } } + } + /// + /// Сохранение информации по военным кораблям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (_storages.Count == 0) + { + return false; + } + + if (File.Exists(filename)) + { + File.Delete(filename); + } + + using (StreamWriter writer = new StreamWriter(filename)) + { + writer.Write(_collectionKey); + foreach (KeyValuePair> value in _storages) + { + writer.Write(Environment.NewLine); + // не сохраняем пустые коллекции + if (value.Value.Count == 0) + { + continue; + } + writer.Write(value.Key); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.GetCollectionType); + writer.Write(_separatorForKeyValue); + writer.Write(value.Value.MaxCount); + writer.Write(_separatorForKeyValue); + foreach (T? item in value.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + if (string.IsNullOrEmpty(data)) + { + continue; + } + writer.Write(data); + writer.Write(_separatorItems); + } + } + } + return true; + } + + /// + /// Загрузка информации по военным кораблям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + using (StreamReader read = File.OpenText(filename)) + { + string str = read.ReadLine(); + if (str == null || str.Length == 0) + { + return false; + } + + if (!str.StartsWith(_collectionKey)) + { + return false; + } + + _storages.Clear(); + string strs = ""; + while ((strs = read.ReadLine()) != null) + { + string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) + { + continue; + } + + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenericObjects? collection = StorageCollection.CreateCollection(collectionType); + if (collection == null) + { + return false; + } + + collection.MaxCount = Convert.ToInt32(record[2]); + + string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); + foreach (string elem in set) + { + if (elem?.CreateDrawningTrackedVehicle() is T warship) + { + if (collection.Insert(warship) == -1) + { + return false; + } + } + } + _storages.Add(record[0], collection); + } + } + return true; + } + + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; } } + diff --git a/HoistingCrane/HoistingCrane/Drawning/DrawningHoistingCrane.cs b/HoistingCrane/HoistingCrane/Drawning/DrawningHoistingCrane.cs index 2023b34..b52830c 100644 --- a/HoistingCrane/HoistingCrane/Drawning/DrawningHoistingCrane.cs +++ b/HoistingCrane/HoistingCrane/Drawning/DrawningHoistingCrane.cs @@ -1,5 +1,6 @@ using HoistingCrane.Entities; using System.Configuration; +using System.Reflection.PortableExecutable; namespace HoistingCrane.Drawning; @@ -39,6 +40,15 @@ public class DrawningHoistingCrane : DrawningTrackedVehicle EntityTrackedVehicle = new EntityHoistingCrane(speed, weight, bodyColor, additionalColor, counterweight, platform); } + /// + /// Конструктор для Extention + /// + /// + public DrawningHoistingCrane(EntityHoistingCrane entityHoistingCrane) : base(115, 63) + { + EntityTrackedVehicle = new EntityHoistingCrane(entityHoistingCrane.Speed, entityHoistingCrane.Weight, entityHoistingCrane.BodyColor, entityHoistingCrane.AdditionalColor, entityHoistingCrane.Counterweight, entityHoistingCrane.Platform); + } + /// /// Метод отрисовки объекта /// @@ -49,7 +59,6 @@ public class DrawningHoistingCrane : DrawningTrackedVehicle { return; } - base.DrawTransport(gr); Brush b = new SolidBrush(EntityHoistingCrane.AdditionalColor); Pen pen = new Pen(EntityHoistingCrane.AdditionalColor); diff --git a/HoistingCrane/HoistingCrane/Drawning/DrawningTrackedVehicle.cs b/HoistingCrane/HoistingCrane/Drawning/DrawningTrackedVehicle.cs index 29846b3..be19768 100644 --- a/HoistingCrane/HoistingCrane/Drawning/DrawningTrackedVehicle.cs +++ b/HoistingCrane/HoistingCrane/Drawning/DrawningTrackedVehicle.cs @@ -1,4 +1,5 @@ using HoistingCrane.Entities; +using System.Reflection.PortableExecutable; namespace HoistingCrane.Drawning { @@ -80,6 +81,15 @@ namespace HoistingCrane.Drawning _startPosY = null; } + /// + /// Конструктор для Extention + /// + /// + public DrawningTrackedVehicle(EntityTrackedVehicle entityTrackedVehicle) : this() + { + EntityTrackedVehicle = new EntityTrackedVehicle(entityTrackedVehicle.Speed, entityTrackedVehicle.Weight, entityTrackedVehicle.BodyColor); + } + /// /// Метод отрисовки игрового поля diff --git a/HoistingCrane/HoistingCrane/Drawning/ExtentionDrawningCrane.cs b/HoistingCrane/HoistingCrane/Drawning/ExtentionDrawningCrane.cs new file mode 100644 index 0000000..2b9a11e --- /dev/null +++ b/HoistingCrane/HoistingCrane/Drawning/ExtentionDrawningCrane.cs @@ -0,0 +1,55 @@ +using HoistingCrane.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace HoistingCrane.Drawning +{ + public static class ExtentionDrawningCrane + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningTrackedVehicle? CreateDrawningTrackedVehicle(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityTrackedVehicle? trackedVehicle = EntityHoistingCrane.CreateEntityHoistingCrane(strs); + if (trackedVehicle != null) + { + return new DrawningHoistingCrane((EntityHoistingCrane)trackedVehicle); + } + trackedVehicle = EntityTrackedVehicle.CreateEntityTrackedVehicle(strs); + if (trackedVehicle != null) + { + return new DrawningTrackedVehicle(trackedVehicle); + } + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningTrackedVehicle drawningTrackedVehicle) + { + string[]? array = drawningTrackedVehicle?.EntityTrackedVehicle?.GetStringRepresentation(); + + if (array == null) + { + return string.Empty; + + } + return string.Join(_separatorForObject, array); + } + } +} diff --git a/HoistingCrane/HoistingCrane/Entities/EntityHoistingCrane.cs b/HoistingCrane/HoistingCrane/Entities/EntityHoistingCrane.cs index 3c6c8f9..ea0f5de 100644 --- a/HoistingCrane/HoistingCrane/Entities/EntityHoistingCrane.cs +++ b/HoistingCrane/HoistingCrane/Entities/EntityHoistingCrane.cs @@ -30,7 +30,7 @@ public class EntityHoistingCrane : EntityTrackedVehicle // . - public EntityHoistingCrane(int Speed, int Weight, Color BodyColor, Color AdditionalColor, bool Counterweight, bool Platform) : base(Speed, Weight, BodyColor) + public EntityHoistingCrane(int Speed, double Weight, Color BodyColor, Color AdditionalColor, bool Counterweight, bool Platform) : base(Speed, Weight, BodyColor) { this.AdditionalColor = AdditionalColor; this.Counterweight = Counterweight; @@ -42,4 +42,27 @@ public class EntityHoistingCrane : EntityTrackedVehicle { AdditionalColor = newColor; } + + /// + /// - + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityHoistingCrane), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, Counterweight.ToString(), Platform.ToString()}; + } + + /// + /// + /// + /// + /// + public static EntityHoistingCrane? CreateEntityHoistingCrane(string[] strs) + { + if (strs.Length != 7 || strs[0] != nameof(EntityHoistingCrane)) + { + return null; + } + return new EntityHoistingCrane(Convert.ToInt32(strs[1]), Convert.ToInt32(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6])); + } } \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/Entities/EntityTrackedVehicle.cs b/HoistingCrane/HoistingCrane/Entities/EntityTrackedVehicle.cs index caef6bc..409e6e4 100644 --- a/HoistingCrane/HoistingCrane/Entities/EntityTrackedVehicle.cs +++ b/HoistingCrane/HoistingCrane/Entities/EntityTrackedVehicle.cs @@ -43,11 +43,34 @@ this.Weight = Weight; this.BodyColor = BodyColor; } - + public void SetBodyColor(Color newBodyColor) { BodyColor = newBodyColor; } + /// + /// Получуеин строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityTrackedVehicle), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityTrackedVehicle? CreateEntityTrackedVehicle(string[] strs) + { + if(strs.Length != 4 || strs[0] != nameof(EntityTrackedVehicle)) + { + return null; + } + return new EntityTrackedVehicle(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } + } } diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.Designer.cs b/HoistingCrane/HoistingCrane/FormCarCollection.Designer.cs index 0977933..537d3a6 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.Designer.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.Designer.cs @@ -29,6 +29,12 @@ private void InitializeComponent() { groupBoxTools = new GroupBox(); + panelCompanyTool = new Panel(); + buttonCreateHoistingCrane = new Button(); + maskedTextBox = new MaskedTextBox(); + buttonRefresh = new Button(); + buttonGoToChek = new Button(); + buttonDeleteCar = new Button(); buttonCreateCompany = new Button(); panelStorage = new Panel(); buttonDeleteCollection = new Button(); @@ -38,18 +44,21 @@ radioButtonMassive = new RadioButton(); textBoxCollectionName = new TextBox(); labelCollectionName = new Label(); - buttonGoToChek = new Button(); - buttonRefresh = new Button(); - buttonDeleteCar = new Button(); - maskedTextBox = new MaskedTextBox(); comboBoxSelectorCompany = new ComboBox(); - buttonCreateHoistingCrane = new Button(); pictureBox = new PictureBox(); - panelCompanyTool = new Panel(); + menuStrip = new MenuStrip(); + файлToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog = new OpenFileDialog(); + buttonSortByType = new Button(); + buttonSortByColor = new Button(); groupBoxTools.SuspendLayout(); + panelCompanyTool.SuspendLayout(); panelStorage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); - panelCompanyTool.SuspendLayout(); + menuStrip.SuspendLayout(); SuspendLayout(); // // groupBoxTools @@ -59,16 +68,84 @@ groupBoxTools.Controls.Add(panelStorage); groupBoxTools.Controls.Add(comboBoxSelectorCompany); groupBoxTools.Dock = DockStyle.Right; - groupBoxTools.Location = new Point(763, 0); + groupBoxTools.Location = new Point(763, 24); groupBoxTools.Name = "groupBoxTools"; - groupBoxTools.Size = new Size(210, 509); + groupBoxTools.Size = new Size(210, 524); groupBoxTools.TabIndex = 0; groupBoxTools.TabStop = false; groupBoxTools.Text = "Инструменты"; // + // panelCompanyTool + // + panelCompanyTool.Anchor = AnchorStyles.None; + panelCompanyTool.Controls.Add(buttonSortByColor); + panelCompanyTool.Controls.Add(buttonSortByType); + panelCompanyTool.Controls.Add(buttonCreateHoistingCrane); + panelCompanyTool.Controls.Add(maskedTextBox); + panelCompanyTool.Controls.Add(buttonRefresh); + panelCompanyTool.Controls.Add(buttonGoToChek); + panelCompanyTool.Controls.Add(buttonDeleteCar); + panelCompanyTool.Location = new Point(6, 296); + panelCompanyTool.Name = "panelCompanyTool"; + panelCompanyTool.Size = new Size(204, 221); + panelCompanyTool.TabIndex = 8; + // + // buttonCreateHoistingCrane + // + buttonCreateHoistingCrane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonCreateHoistingCrane.Location = new Point(6, 3); + buttonCreateHoistingCrane.Name = "buttonCreateHoistingCrane"; + buttonCreateHoistingCrane.Size = new Size(192, 22); + buttonCreateHoistingCrane.TabIndex = 0; + buttonCreateHoistingCrane.Text = "Добавить транспорт"; + buttonCreateHoistingCrane.UseVisualStyleBackColor = true; + buttonCreateHoistingCrane.Click += buttonCreateHoistingCrane_Click; + // + // maskedTextBox + // + maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + maskedTextBox.Location = new Point(6, 31); + maskedTextBox.Mask = "00"; + maskedTextBox.Name = "maskedTextBox"; + maskedTextBox.Size = new Size(192, 23); + maskedTextBox.TabIndex = 3; + // + // buttonRefresh + // + buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonRefresh.Location = new Point(6, 119); + buttonRefresh.Name = "buttonRefresh"; + buttonRefresh.Size = new Size(192, 27); + buttonRefresh.TabIndex = 5; + buttonRefresh.Text = "Обновить"; + buttonRefresh.UseVisualStyleBackColor = true; + buttonRefresh.Click += buttonRefresh_Click; + // + // buttonGoToChek + // + buttonGoToChek.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonGoToChek.Location = new Point(6, 89); + buttonGoToChek.Name = "buttonGoToChek"; + buttonGoToChek.Size = new Size(192, 24); + buttonGoToChek.TabIndex = 6; + buttonGoToChek.Text = "Передать на тесты"; + buttonGoToChek.UseVisualStyleBackColor = true; + buttonGoToChek.Click += buttonGoToChek_Click; + // + // buttonDeleteCar + // + buttonDeleteCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + buttonDeleteCar.Location = new Point(6, 60); + buttonDeleteCar.Name = "buttonDeleteCar"; + buttonDeleteCar.Size = new Size(192, 23); + buttonDeleteCar.TabIndex = 4; + buttonDeleteCar.Text = "Удалить автомобиль"; + buttonDeleteCar.UseVisualStyleBackColor = true; + buttonDeleteCar.Click += buttonDeleteCar_Click; + // // buttonCreateCompany // - buttonCreateCompany.Location = new Point(12, 295); + buttonCreateCompany.Location = new Point(12, 267); buttonCreateCompany.Name = "buttonCreateCompany"; buttonCreateCompany.Size = new Size(192, 23); buttonCreateCompany.TabIndex = 7; @@ -88,12 +165,12 @@ panelStorage.Dock = DockStyle.Top; panelStorage.Location = new Point(3, 19); panelStorage.Name = "panelStorage"; - panelStorage.Size = new Size(204, 229); + panelStorage.Size = new Size(204, 216); panelStorage.TabIndex = 7; // // buttonDeleteCollection // - buttonDeleteCollection.Location = new Point(9, 199); + buttonDeleteCollection.Location = new Point(9, 186); buttonDeleteCollection.Name = "buttonDeleteCollection"; buttonDeleteCollection.Size = new Size(192, 27); buttonDeleteCollection.TabIndex = 6; @@ -105,14 +182,14 @@ // listBoxCollection.FormattingEnabled = true; listBoxCollection.ItemHeight = 15; - listBoxCollection.Location = new Point(9, 118); + listBoxCollection.Location = new Point(9, 101); listBoxCollection.Name = "listBoxCollection"; listBoxCollection.Size = new Size(192, 79); listBoxCollection.TabIndex = 5; // // buttonCollectionAdd // - buttonCollectionAdd.Location = new Point(9, 81); + buttonCollectionAdd.Location = new Point(9, 72); buttonCollectionAdd.Name = "buttonCollectionAdd"; buttonCollectionAdd.Size = new Size(192, 23); buttonCollectionAdd.TabIndex = 4; @@ -123,9 +200,9 @@ // radioButtonList // radioButtonList.AutoSize = true; - radioButtonList.Location = new Point(128, 56); + radioButtonList.Location = new Point(128, 47); radioButtonList.Name = "radioButtonList"; - radioButtonList.Size = new Size(67, 19); + radioButtonList.Size = new Size(66, 19); radioButtonList.TabIndex = 3; radioButtonList.TabStop = true; radioButtonList.Text = "Список"; @@ -134,9 +211,9 @@ // radioButtonMassive // radioButtonMassive.AutoSize = true; - radioButtonMassive.Location = new Point(18, 56); + radioButtonMassive.Location = new Point(12, 47); radioButtonMassive.Name = "radioButtonMassive"; - radioButtonMassive.Size = new Size(69, 19); + radioButtonMassive.Size = new Size(67, 19); radioButtonMassive.TabIndex = 2; radioButtonMassive.TabStop = true; radioButtonMassive.Text = "Массив"; @@ -154,113 +231,92 @@ labelCollectionName.AutoSize = true; labelCollectionName.Location = new Point(35, 0); labelCollectionName.Name = "labelCollectionName"; - labelCollectionName.Size = new Size(135, 15); + labelCollectionName.Size = new Size(125, 15); labelCollectionName.TabIndex = 0; labelCollectionName.Text = "Название коллекции:"; // - // buttonGoToChek - // - buttonGoToChek.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonGoToChek.Location = new Point(9, 99); - buttonGoToChek.Name = "buttonGoToChek"; - buttonGoToChek.Size = new Size(192, 24); - buttonGoToChek.TabIndex = 6; - buttonGoToChek.Text = "Передать на тесты"; - buttonGoToChek.UseVisualStyleBackColor = true; - buttonGoToChek.Click += buttonGoToChek_Click; - // - // buttonRefresh - // - buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonRefresh.Location = new Point(9, 129); - buttonRefresh.Name = "buttonRefresh"; - buttonRefresh.Size = new Size(192, 27); - buttonRefresh.TabIndex = 5; - buttonRefresh.Text = "Обновить"; - buttonRefresh.UseVisualStyleBackColor = true; - buttonRefresh.Click += buttonRefresh_Click; - // - // buttonDeleteCar - // - buttonDeleteCar.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonDeleteCar.Location = new Point(9, 70); - buttonDeleteCar.Name = "buttonDeleteCar"; - buttonDeleteCar.Size = new Size(192, 23); - buttonDeleteCar.TabIndex = 4; - buttonDeleteCar.Text = "Удалить автомобиль"; - buttonDeleteCar.UseVisualStyleBackColor = true; - buttonDeleteCar.Click += buttonDeleteCar_Click; - // - // maskedTextBox - // - maskedTextBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - maskedTextBox.Location = new Point(9, 41); - maskedTextBox.Mask = "00"; - maskedTextBox.Name = "maskedTextBox"; - maskedTextBox.Size = new Size(192, 23); - maskedTextBox.TabIndex = 3; - // // comboBoxSelectorCompany // comboBoxSelectorCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList; comboBoxSelectorCompany.FormattingEnabled = true; comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" }); - comboBoxSelectorCompany.Location = new Point(12, 266); + comboBoxSelectorCompany.Location = new Point(12, 238); comboBoxSelectorCompany.Name = "comboBoxSelectorCompany"; comboBoxSelectorCompany.Size = new Size(192, 23); comboBoxSelectorCompany.TabIndex = 2; comboBoxSelectorCompany.SelectedIndexChanged += comboBoxSelectorCompany_SelectedIndexChanged; // - // buttonCreateHoistingCrane - // - buttonCreateHoistingCrane.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - buttonCreateHoistingCrane.Location = new Point(9, 13); - buttonCreateHoistingCrane.Name = "buttonCreateHoistingCrane"; - buttonCreateHoistingCrane.Size = new Size(192, 22); - buttonCreateHoistingCrane.TabIndex = 0; - buttonCreateHoistingCrane.Text = "Добавить транспорт"; - buttonCreateHoistingCrane.UseVisualStyleBackColor = true; - buttonCreateHoistingCrane.Click += buttonCreateHoistingCrane_Click; - // // pictureBox // pictureBox.Dock = DockStyle.Fill; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 24); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(763, 509); + pictureBox.Size = new Size(763, 524); pictureBox.TabIndex = 1; pictureBox.TabStop = false; // - // panelCompanyTool + // menuStrip // - panelCompanyTool.Anchor = AnchorStyles.None; - panelCompanyTool.Controls.Add(buttonCreateHoistingCrane); - panelCompanyTool.Controls.Add(maskedTextBox); - panelCompanyTool.Controls.Add(buttonRefresh); - panelCompanyTool.Controls.Add(buttonGoToChek); - panelCompanyTool.Controls.Add(buttonDeleteCar); - panelCompanyTool.Location = new Point(6, 324); - panelCompanyTool.Name = "panelCompanyTool"; - panelCompanyTool.Size = new Size(204, 185); - panelCompanyTool.TabIndex = 8; + menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(973, 24); + menuStrip.TabIndex = 2; + menuStrip.Text = "menuStrip1"; + // + // файлToolStripMenuItem + // + файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + файлToolStripMenuItem.Name = "файлToolStripMenuItem"; + файлToolStripMenuItem.Size = new Size(48, 20); + файлToolStripMenuItem.Text = "Файл"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(181, 22); + saveToolStripMenuItem.Text = "Сохранение"; + saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(181, 22); + loadToolStripMenuItem.Text = "Загрузка"; + loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file | *.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file | *.txt"; // // FormCarCollection // AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleMode = AutoScaleMode.Font; - ClientSize = new Size(973, 509); + ClientSize = new Size(973, 548); Controls.Add(pictureBox); Controls.Add(groupBoxTools); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "FormCarCollection"; Text = "FormCarCollections"; groupBoxTools.ResumeLayout(false); + panelCompanyTool.ResumeLayout(false); + panelCompanyTool.PerformLayout(); panelStorage.ResumeLayout(false); panelStorage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); - panelCompanyTool.ResumeLayout(false); - panelCompanyTool.PerformLayout(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -283,5 +339,13 @@ private ListBox listBoxCollection; private Button buttonCollectionAdd; private Panel panelCompanyTool; + private MenuStrip menuStrip; + private ToolStripMenuItem файлToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog; + private Button buttonSortByColor; + private Button buttonSortByType; } } \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.cs b/HoistingCrane/HoistingCrane/FormCarCollection.cs index b0805e7..4f7d0fb 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.cs +++ b/HoistingCrane/HoistingCrane/FormCarCollection.cs @@ -1,15 +1,6 @@ using HoistingCrane.CollectionGenericObjects; using HoistingCrane.Drawning; -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; - +using Microsoft.Extensions.Logging; namespace HoistingCrane { public partial class FormCarCollection : Form @@ -17,6 +8,10 @@ namespace HoistingCrane private AbstractCompany? _company; private readonly StorageCollection _storageCollection; + /// + /// Логгер + /// + private readonly ILogger logger; public FormCarCollection() { InitializeComponent(); @@ -27,55 +22,15 @@ namespace HoistingCrane { panelCompanyTool.Enabled = false; } - private void CreateObject(string type) - { - DrawningTrackedVehicle drawning; - if (_company == null) return; - Random rand = new(); - switch (type) - { - case nameof(DrawningHoistingCrane): - drawning = new DrawningHoistingCrane(rand.Next(100, 300), rand.Next(1000, 3000), GetColor(rand), GetColor(rand), true, true); - break; - - case nameof(DrawningTrackedVehicle): - drawning = new DrawningTrackedVehicle(rand.Next(100, 300), rand.Next(1000, 3000), GetColor(rand)); - break; - default: - return; - } - if ((_company + drawning) != -1) - { - MessageBox.Show("Объект добавлен"); - pictureBox.Image = _company.Show(); - } - else - { - MessageBox.Show("Не удалось добавить объект"); - } - } - 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 buttonCreateHoistingCrane_Click(object sender, EventArgs e) { FormCarConfig form = new(); form.Show(); - form.AddEvent(SetCar); + form.AddEvent(SetCrane); } - private void SetCar(DrawningTrackedVehicle drawningTrackedVehicle) + private void SetCrane(DrawningTrackedVehicle drawningTrackedVehicle) { - if (_company == null || drawningTrackedVehicle == null) - { - return; - } + if (_company == null || drawningTrackedVehicle == null) return; if (_company + drawningTrackedVehicle != -1) { @@ -90,7 +45,6 @@ namespace HoistingCrane private void buttonDeleteCar_Click(object sender, EventArgs e) { - if (string.IsNullOrEmpty(maskedTextBox.Text) || _company == null) { return; @@ -109,6 +63,7 @@ namespace HoistingCrane { MessageBox.Show("Не удалось удалить объект"); } + } private void buttonRefresh_Click(object sender, EventArgs e) { @@ -153,8 +108,7 @@ namespace HoistingCrane { if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked)) { - MessageBox.Show("Не все данные заполнены", "Ошибка", - MessageBoxButtons.OK, MessageBoxIcon.Error); + MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } CollectionType collectionType = CollectionType.None; @@ -166,9 +120,7 @@ namespace HoistingCrane { collectionType = CollectionType.List; } - _storageCollection.AddCollection(textBoxCollectionName.Text, - collectionType); - RerfreshListBoxItems(); + _storageCollection.AddCollection(textBoxCollectionName.Text, collectionType); RerfreshListBoxItems(); } private void buttonDeleteCollection_Click(object sender, EventArgs e) { @@ -181,9 +133,11 @@ namespace HoistingCrane return; _storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString()); RerfreshListBoxItems(); + } private void buttonCreateCompany_Click(object sender, EventArgs e) { + if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null) { MessageBox.Show("Коллекция не выбрана"); @@ -194,7 +148,7 @@ namespace HoistingCrane { MessageBox.Show("Коллекция не проинициализирована"); return; - } + }; switch (comboBoxSelectorCompany.Text) { case "Хранилище": @@ -204,6 +158,50 @@ namespace HoistingCrane panelCompanyTool.Enabled = true; RerfreshListBoxItems(); } + + /// + /// Обработка нажатия "Сохранение" + /// + /// + /// + private void saveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _storageCollection.SaveData(saveFileDialog.FileName); + MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + /// + /// Обработка нажатия "Загразка" + /// + /// + /// + private void loadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + try + { + _storageCollection.LoadData(openFileDialog.FileName); + RerfreshListBoxItems(); + MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information); + + } + catch (Exception ex) + { + MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } -} \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/FormCarCollection.resx b/HoistingCrane/HoistingCrane/FormCarCollection.resx index af32865..0430c52 100644 --- a/HoistingCrane/HoistingCrane/FormCarCollection.resx +++ b/HoistingCrane/HoistingCrane/FormCarCollection.resx @@ -117,4 +117,16 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 5 + + + 130, 5 + + + 270, 5 + + + 25 + \ No newline at end of file diff --git a/HoistingCrane/HoistingCrane/FormCarConfig.cs b/HoistingCrane/HoistingCrane/FormCarConfig.cs index 2d0cd40..306b03f 100644 --- a/HoistingCrane/HoistingCrane/FormCarConfig.cs +++ b/HoistingCrane/HoistingCrane/FormCarConfig.cs @@ -31,6 +31,7 @@ namespace HoistingCrane panelColorPurple.MouseDown += panel_MouseDown; buttonCancel.Click += (sender, e) => Close(); } + /// /// Привязка метода к событию /// diff --git a/HoistingCrane/HoistingCrane/HoistingCrane.csproj b/HoistingCrane/HoistingCrane/HoistingCrane.csproj index 69ac652..3f2e375 100644 --- a/HoistingCrane/HoistingCrane/HoistingCrane.csproj +++ b/HoistingCrane/HoistingCrane/HoistingCrane.csproj @@ -12,6 +12,18 @@ + + + + + + + + + + + + True diff --git a/HoistingCrane/HoistingCrane/Program.cs b/HoistingCrane/HoistingCrane/Program.cs index 79d96ff..b7ebec0 100644 --- a/HoistingCrane/HoistingCrane/Program.cs +++ b/HoistingCrane/HoistingCrane/Program.cs @@ -1,18 +1,16 @@ -namespace HoistingCrane +namespace HoistingCrane; + +internal static class Program { - internal static class Program + /// + /// The main entry point for the application. + /// + [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(); - Application.Run(new FormCarCollection()); - - } + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + Application.Run(new FormCarCollection()); } } \ No newline at end of file