diff --git a/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs index d94f1c8..5b98774 100644 --- a/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs +++ b/ProjectCruiser/CollectionGenericObj/AbstractCompany.cs @@ -26,7 +26,7 @@ public abstract class AbstractCompany _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } // Перегрузка оператора сложения для класса diff --git a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs index 620dcc8..5c56167 100644 --- a/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ArrayGenObj.cs @@ -1,24 +1,32 @@ -namespace ProjectCruiser.CollectionGenericObj; + +namespace ProjectCruiser.CollectionGenericObj; public class ArrayGenObj : ICollectionGenObj where T : class { // Массив объектов, которые храним private T?[] _collection; - public int Count => _collection.Length; - public int SetMaxCount + + // Максимально допустимое число объектов в массиве + private int _maxCount; + public int Count => _collection.Count(s => s != null); + + public int MaxCount { + get { return _maxCount; } set { if (value > 0) { - if (_collection.Length > 0) Array.Resize(ref _collection, value); - else _collection = new T?[value]; + if (_collection.Length == 0) _collection = new T?[value]; + else Array.Resize(ref _collection, value); + + _maxCount = value; } } } - // public int SetMaxCount { set { if (value > 0) { _collection = new T?[value]; } } } + public CollectionType GetCollectionType => CollectionType.Array; public ArrayGenObj() { @@ -26,7 +34,6 @@ public class ArrayGenObj : ICollectionGenObj } // methods : - public T? GetItem(int index) { if (index > Count || index < 0) @@ -38,8 +45,13 @@ public class ArrayGenObj : ICollectionGenObj public int Insert(T? item) { - // any empty place - for (int i = 0; i < Count; i++) + if (Count >= _maxCount || item == null) + { + return -1; + } + + // any empty place -> fill immediately + for (int i = 0; i < _collection.Length; i++) { if (_collection[i] == null) { @@ -47,48 +59,59 @@ public class ArrayGenObj : ICollectionGenObj return i; } } - return -1; + return Count; } public int Insert(T? item, int index) { + if (index >= _maxCount || Count >= _maxCount || + index < 0 || _collection[index] != null + || item == null) + { + return -1; + } + if (_collection[index] == null) { _collection[index] = item; return index; } - else + int min_diff = 100, firstNullIndex = 100; + + for (int i = 0; i < Count; i++) { - int min_diff = 100, min_index = 100; - - for (int i = 0; i < Count; i++) + if (_collection[i] == null + && min_diff > Math.Abs(index - i)) { - if (_collection[i] == null - && min_diff > Math.Abs(index - i)) - { - min_diff = Math.Abs(index - i); - min_index = i; - } + min_diff = Math.Abs(index - i); + firstNullIndex = i; } - - _collection[min_index] = item; - return min_index; } - return -1; + _collection[firstNullIndex] = item; + return firstNullIndex; } public T? Remove(int index) { - T? item; - if (index < Count && index >= 0) + if (index >= Count || index < 0) + // on the other positions items don't exist { - item = _collection[index]; - _collection[index] = null; - return item; + return null; + } + + T? item = _collection[index]; + _collection[index] = null; + return item; + } + + public IEnumerable GetItems() + { + for (int i = 0; i < MaxCount; ++i) + { + yield return _collection[i]; } - return null; } } diff --git a/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs b/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs index d87998c..4af2547 100644 --- a/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ICollectionGenObj.cs @@ -6,7 +6,7 @@ public interface ICollectionGenObj where T : class int Count { get; } // Установка max кол-ва элементов - int SetMaxCount { set; } + int MaxCount { set; get; } /// Добавление объекта в коллекцию /// Добавляемый объект @@ -21,4 +21,10 @@ public interface ICollectionGenObj where T : class // Получение объекта по позиции T? GetItem(int position); + + // Получение типа коллекции + CollectionType GetCollectionType { get; } + + // Получение объектов коллекции по одному + IEnumerable GetItems(); } diff --git a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs index 0b33867..fd256d3 100644 --- a/ProjectCruiser/CollectionGenericObj/ListGenObj.cs +++ b/ProjectCruiser/CollectionGenericObj/ListGenObj.cs @@ -1,4 +1,6 @@ using System; +using System.Collections; +using System.Collections.Generic; using System.Reflection; namespace ProjectCruiser.CollectionGenericObj; @@ -8,13 +10,28 @@ public class ListGenObj : ICollectionGenObj where T : class { // Список объектов, которые храним - private readonly List _collection; + private List _collection; // Максимально допустимое число объектов в списке private int _maxCount; public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount + { + get { return _maxCount; } + set + { + if (value > 0) + { + if (_collection.Count == 0) _collection = new List(value); + else _collection.Capacity = value; // instead of resizing + + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; public ListGenObj() { @@ -31,7 +48,7 @@ public class ListGenObj : ICollectionGenObj return _collection[position]; } - public int Insert(T obj) + public int Insert(T? obj) { if (Count >= _maxCount || obj == null) { @@ -42,7 +59,7 @@ public class ListGenObj : ICollectionGenObj return Count; } - public int Insert(T obj, int position) + public int Insert(T? obj, int position) { if (position >= _maxCount || Count >= _maxCount || position < 0 || _collection[position] != null @@ -67,4 +84,12 @@ public class ListGenObj : ICollectionGenObj _collection.RemoveAt(position); return item; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } diff --git a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs index cd62ac5..93ae0b4 100644 --- a/ProjectCruiser/CollectionGenericObj/StorageCollection.cs +++ b/ProjectCruiser/CollectionGenericObj/StorageCollection.cs @@ -1,8 +1,19 @@ -namespace ProjectCruiser.CollectionGenericObj; +using System.Text; +using ProjectCruiser.DrawningSamples; + +namespace ProjectCruiser.CollectionGenericObj; public class StorageCollection -where T : class + where T : DrawningBase // class { + // Разделитель для записи ключа и значения элемента словаря + private readonly string _separatorForKeyValue = "|"; + // Разделитель для записей коллекции данных в файл + private readonly string _separatorItems = ";"; + + // Ключевое слово, с которого должен начинаться файл + private readonly string _collectionKey = "CollectionsStorage"; + // Словарь (хранилище) с коллекциями < name, type (class) > readonly Dictionary> _storages; @@ -14,9 +25,7 @@ where T : class _storages = new Dictionary>(); } - /// Добавление коллекции в хранилище - /// Название коллекции - /// тип коллекции + // Добавление коллекции в хранилище public void AddCollection(string name, CollectionType collType) { if (name == null || _storages.ContainsKey(name) @@ -25,27 +34,165 @@ where T : class return; } - switch (collType) - { - case CollectionType.List: _storages.Add(name, new ListGenObj()); break; - // _storages[name] = new ListGenericObjects(); break; [*] - - case CollectionType.Array: _storages.Add(name, new ArrayGenObj()); break; - } + ICollectionGenObj collection = CreateCollection(collType); + _storages.Add(name, collection); } - /// Удаление коллекции ( по ключу-строке - её имени ) - /// Название коллекции + // Удаление коллекции ( по ключу-строке - её имени ) public void DelCollection(string name) { if (_storages.ContainsKey(name)) _storages.Remove(name); return; } - /// Доступ к коллекции ( по ключу-строке - её имени ) + // Доступ к коллекции ( по ключу-строке - её имени ) - индексатор [!!!] public ICollectionGenObj? this[string name] { get => _storages.ContainsKey(name) ? _storages[name] : null; } + + /// Сохранение информации по автомобилям в хранилище в файл + /// Путь и имя файла + /// true - сохранение прошло успешно, + /// false - ошибка при сохранении данных + public bool SaveData(string filename) + { + if (_storages.Count == 0) { return false; } + if (File.Exists(filename)) { File.Delete(filename); } + + StringBuilder sb = new(); + + sb.Append(_collectionKey); // const + + foreach (KeyValuePair> pair in _storages) + { + sb.Append(Environment.NewLine); // не сохраняем пустые коллекции + if (pair.Value.Count == 0) { continue; } + + sb.Append(pair.Key); + sb.Append(_separatorForKeyValue); + sb.Append(pair.Value.GetCollectionType); + sb.Append(_separatorForKeyValue); + sb.Append(pair.Value.MaxCount); + sb.Append(_separatorForKeyValue); + + foreach (T? item in pair.Value.GetItems()) + { + string data = item?.GetDataForSave() ?? string.Empty; + + /* + string n = item.GetType().Name; + string data = null; + + if (n != null && n == "DrawningCruiser") + { + data = ExtentionDrShip.GetDataForSave(item); + } + else if (n != null && n == "DrawningBase") + { + data = ExtentionDrShip.GetDataForSave(item); + } + */ + + if (string.IsNullOrEmpty(data)) + { + continue; + } + + sb.Append(data); + sb.Append(_separatorItems); + } + } + + using FileStream fs = new(filename, FileMode.Create); + byte[] info = new UTF8Encoding(true).GetBytes(sb.ToString()); + fs.Write(info, 0, info.Length); + return true; + } + + // Создание коллекции по типу + private static ICollectionGenObj? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Array => new ArrayGenObj(), + CollectionType.List => new ListGenObj(), + _ => null, + }; + } + + // Загрузка информации по кораблям в хранилище из файла + public bool LoadData(string filename) + { + if (!File.Exists(filename)) + { + return false; + } + + string bufferTextFromFile = ""; + + using (FileStream fs = new(filename, FileMode.Open)) + { + byte[] b = new byte[fs.Length]; + UTF8Encoding temp = new(true); + while (fs.Read(b, 0, b.Length) > 0) + { + bufferTextFromFile += temp.GetString(b); + } + } + + string[] strs = bufferTextFromFile.Split( + new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); + + if (strs == null || strs.Length == 0) + { + return false; + } + if (!strs[0].Equals(_collectionKey)) + { + //если нет такой записи, то это не те данные + return false; + } + + string[] companies = new string[strs.Length - 1]; + for (int k = 1; k < strs.Length; k++) + { + companies[k - 1] = strs[k]; + } + + _storages.Clear(); + foreach (string data in companies) + { + string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); + if (record.Length != 4) // > + // key | collType | maxcount | all next inf > 4 + { + continue; + } + CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); + ICollectionGenObj? 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?.CreateDrawningCar() is T ship) + { + if (collection.Insert(ship) == -1) + { + return false; + } + } + } + _storages.Add(record[0], collection); + } + return true; + } } diff --git a/ProjectCruiser/DrawningSamples/DrawningBase.cs b/ProjectCruiser/DrawningSamples/DrawningBase.cs index 4b7884f..7812c65 100644 --- a/ProjectCruiser/DrawningSamples/DrawningBase.cs +++ b/ProjectCruiser/DrawningSamples/DrawningBase.cs @@ -14,9 +14,9 @@ public class DrawningBase private readonly int _drawningHeight = 42; // Высота прорисовки автомобиля // Инициализация свойств (теперь через конструктор) - public DrawningBase(int speed, double weight, Color bodyColor) : this() + public DrawningBase(EntityBase ship) : this() { - EntityTransport = new EntityBase(speed, weight, bodyColor); + EntityTransport = ship; } private DrawningBase() diff --git a/ProjectCruiser/DrawningSamples/DrawningCruiser.cs b/ProjectCruiser/DrawningSamples/DrawningCruiser.cs index 8b1c8c7..faebb2b 100644 --- a/ProjectCruiser/DrawningSamples/DrawningCruiser.cs +++ b/ProjectCruiser/DrawningSamples/DrawningCruiser.cs @@ -5,11 +5,9 @@ namespace ProjectCruiser.DrawningSamples; public class DrawningCruiser : DrawningBase { // Инициализация свойств (все параметры класса (сущности)) - public DrawningCruiser(int speed, double weight, Color bodyColor, - Color additionalColor, bool pad, bool hangars) : base(302, 42) + public DrawningCruiser(EntityCruiser ship) : base((EntityBase)ship) { - EntityTransport = new EntityCruiser(speed, weight, - bodyColor, additionalColor, pad, hangars); + EntityTransport = ship; } public override void DrawTransport(Graphics g) diff --git a/ProjectCruiser/DrawningSamples/ExtentionDrShip.cs b/ProjectCruiser/DrawningSamples/ExtentionDrShip.cs new file mode 100644 index 0000000..ad88fac --- /dev/null +++ b/ProjectCruiser/DrawningSamples/ExtentionDrShip.cs @@ -0,0 +1,41 @@ +using ProjectCruiser.Entities; +namespace ProjectCruiser.DrawningSamples; +public static class ExtentionDrShip +{ + // Разделитель для записи информации по объекту в файл + private static readonly string _separatorForObject = ":"; + + // Создание объекта из строки + public static DrawningBase? CreateDrawningCar(this string info) + { + string[] strs = info.Split(_separatorForObject); + + EntityBase? ship = EntityCruiser.CreateEntity(strs); + if (ship != null) + { + return new DrawningCruiser((EntityCruiser)ship); + } + + ship = EntityBase.CreateEntity(strs); + if (ship != null) + { + return new DrawningBase(ship); + } + + return null; + } + + // Получение данных для сохранения в файл - - - - - - - + public static string GetDataForSave(this DrawningBase drShip) + // метод расширения за счёт ключевого слова 'this' + // вызов метода достигается не через имя класса, + // а при вызове у объекта типа DrawningBase [*] + { + string[]? array = drShip?.EntityTransport?.GetStringRepresentation(); + if (array == null) + { + return string.Empty; + } + return string.Join(_separatorForObject, array); + } +} diff --git a/ProjectCruiser/EditorForm3.cs b/ProjectCruiser/EditorForm3.cs index 269f27b..0acc113 100644 --- a/ProjectCruiser/EditorForm3.cs +++ b/ProjectCruiser/EditorForm3.cs @@ -63,12 +63,14 @@ public partial class EditorForm3 : Form switch (e.Data?.GetData(DataFormats.Text)?.ToString()) { case "BaseLabel": - _cruiser = new DrawningBase((int)SpeedN.Value, (double)WeightN.Value, Color.White); + EntityBase ship = new EntityBase((int)SpeedN.Value, (double)WeightN.Value, Color.White); + _cruiser = new DrawningBase(ship); break; case "AdvLabel": Random rn = new Random(); - _cruiser = new DrawningCruiser((int)SpeedN.Value, (double)WeightN.Value, + EntityCruiser cruiser = new EntityCruiser((int)SpeedN.Value, (double)WeightN.Value, Color.White, Color.Black, checkBoxPads.Checked, checkBoxHangars.Checked); + _cruiser = new DrawningCruiser(cruiser); break; } labelMcolor.BackColor = Color.Empty; diff --git a/ProjectCruiser/Entities/EntityBase.cs b/ProjectCruiser/Entities/EntityBase.cs index ba5b0cf..fda56bf 100644 --- a/ProjectCruiser/Entities/EntityBase.cs +++ b/ProjectCruiser/Entities/EntityBase.cs @@ -24,9 +24,26 @@ public class EntityBase Speed = speed; Weight = weight; MainColor = mainc; - // Deckhouse = deckhouse; values[0] = rn.Next(1, 4); values[1] = rn.Next(5, 10); values[2] = rn.Next(1, 3); } + + // Получение массива строк со значениями свойств + // объекта : тип (название класса), скорость, вес, осн. цвет [*] + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityBase), Speed.ToString(), + Weight.ToString(), MainColor.Name }; + } + + // decoding string to object + public static EntityBase? CreateEntity(string[] parameters) + { + if (parameters.Length != 4 || parameters.Length == 0 || + parameters[0] != "EntityBase") return null; + + return new EntityBase(Convert.ToInt32(parameters[1]), + Convert.ToDouble(parameters[2]), Color.FromName(parameters[3])); + } } diff --git a/ProjectCruiser/Entities/EntityCruiser.cs b/ProjectCruiser/Entities/EntityCruiser.cs index e04588a..e53bbe9 100644 --- a/ProjectCruiser/Entities/EntityCruiser.cs +++ b/ProjectCruiser/Entities/EntityCruiser.cs @@ -21,4 +21,26 @@ public class EntityCruiser : EntityBase HelicopterPads = pad; // non-default now for editor Form3 Hangars = hangars; } + + // Получение массива строк со значениями свойств + // объекта : тип (название класса), скорость, вес, осн. цвет [*], + // доп. цвет, истинность наличия площадки и (,) ангаров. + public override string[] GetStringRepresentation() // :O + { + return new[] { nameof(EntityCruiser), Speed.ToString(), + Weight.ToString(), MainColor.Name, AdditionalColor.Name, + HelicopterPads.ToString(), Hangars.ToString()}; + } + + // decoding string to object + public static EntityCruiser? CreateEntity(string[] parameters) + { + if (parameters.Length != 7 || parameters.Length == 0 || + parameters[0] != "EntityCruiser") return null; + + return new EntityCruiser(Convert.ToInt32(parameters[1]), + Convert.ToDouble(parameters[2]), Color.FromName(parameters[3]), + Color.FromName(parameters[4]), Convert.ToBoolean(parameters[5]), + Convert.ToBoolean(parameters[6])); + } } diff --git a/ProjectCruiser/OceanForm1.cs b/ProjectCruiser/OceanForm1.cs index 3c9e341..1e43641 100644 --- a/ProjectCruiser/OceanForm1.cs +++ b/ProjectCruiser/OceanForm1.cs @@ -1,4 +1,5 @@ using ProjectCruiser.DrawningSamples; +using ProjectCruiser.Entities; using ProjectCruiser.MoveStrategy; namespace ProjectCruiser @@ -59,16 +60,18 @@ namespace ProjectCruiser switch (type) { case nameof(DrawningBase): - _drawningCruiser = new DrawningBase(random.Next(100, 300), random.Next(1000, 3000), + EntityBase ship = new EntityBase(random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256))); + _drawningCruiser = new DrawningBase(ship); break; case nameof(DrawningCruiser): - _drawningCruiser = new DrawningCruiser( + EntityCruiser cruiser = new EntityCruiser( random.Next(100, 300), random.Next(1000, 3000), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), Color.FromArgb(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)), Convert.ToBoolean(random.Next(0, 2)), Convert.ToBoolean(random.Next(0, 2))); + _drawningCruiser = new DrawningCruiser(cruiser); break; default: diff --git a/ProjectCruiser/Program.cs b/ProjectCruiser/Program.cs index faeb072..ecba91c 100644 --- a/ProjectCruiser/Program.cs +++ b/ProjectCruiser/Program.cs @@ -12,7 +12,6 @@ namespace ProjectCruiser // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); Application.Run(new ServiceForm2()); - // -> OceanForm1() inside* } } } \ No newline at end of file diff --git a/ProjectCruiser/ServiceForm2.Designer.cs b/ProjectCruiser/ServiceForm2.Designer.cs index 3a92906..d065feb 100644 --- a/ProjectCruiser/ServiceForm2.Designer.cs +++ b/ProjectCruiser/ServiceForm2.Designer.cs @@ -46,10 +46,17 @@ btnAddCruiser = new Button(); btnCreateCompany = new Button(); pictureBox = new PictureBox(); + menuStrip = new MenuStrip(); + fileToolStripMenuItem = new ToolStripMenuItem(); + saveToolStripMenuItem = new ToolStripMenuItem(); + loadToolStripMenuItem = new ToolStripMenuItem(); + saveFileDialog = new SaveFileDialog(); + openFileDialog = new OpenFileDialog(); groupBox.SuspendLayout(); companyPanel.SuspendLayout(); toolPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit(); + menuStrip.SuspendLayout(); SuspendLayout(); // // comboBoxArrList @@ -57,7 +64,7 @@ comboBoxArrList.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; comboBoxArrList.FormattingEnabled = true; comboBoxArrList.Items.AddRange(new object[] { "Storage" }); - comboBoxArrList.Location = new Point(17, 41); + comboBoxArrList.Location = new Point(17, 51); comboBoxArrList.Name = "comboBoxArrList"; comboBoxArrList.Size = new Size(241, 40); comboBoxArrList.TabIndex = 0; @@ -70,9 +77,9 @@ groupBox.Controls.Add(toolPanel); groupBox.Controls.Add(btnCreateCompany); groupBox.Controls.Add(comboBoxArrList); - groupBox.Location = new Point(1421, 10); + groupBox.Location = new Point(1421, 47); groupBox.Name = "groupBox"; - groupBox.Size = new Size(273, 986); + groupBox.Size = new Size(273, 934); groupBox.TabIndex = 2; groupBox.TabStop = false; groupBox.Text = "Tool panel"; @@ -86,7 +93,7 @@ companyPanel.Controls.Add(rBtnArray); companyPanel.Controls.Add(maskedTxtBoxCName); companyPanel.Controls.Add(label); - companyPanel.Location = new Point(17, 91); + companyPanel.Location = new Point(17, 98); companyPanel.Name = "companyPanel"; companyPanel.Size = new Size(243, 391); companyPanel.TabIndex = 7; @@ -168,7 +175,7 @@ toolPanel.Controls.Add(btnDelete); toolPanel.Controls.Add(btnAddCruiser); toolPanel.Enabled = false; - toolPanel.Location = new Point(26, 567); + toolPanel.Location = new Point(26, 608); toolPanel.Name = "toolPanel"; toolPanel.Size = new Size(226, 317); toolPanel.TabIndex = 13; @@ -230,9 +237,9 @@ // btnCreateCompany // btnCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - btnCreateCompany.Location = new Point(16, 488); + btnCreateCompany.Location = new Point(16, 510); btnCreateCompany.Name = "btnCreateCompany"; - btnCreateCompany.Size = new Size(245, 73); + btnCreateCompany.Size = new Size(245, 79); btnCreateCompany.TabIndex = 12; btnCreateCompany.Text = "Create or switch to Company"; btnCreateCompany.UseVisualStyleBackColor = true; @@ -241,12 +248,53 @@ // pictureBox // pictureBox.Dock = DockStyle.Left; - pictureBox.Location = new Point(0, 0); + pictureBox.Location = new Point(0, 40); pictureBox.Name = "pictureBox"; - pictureBox.Size = new Size(1415, 1007); + pictureBox.Size = new Size(1415, 967); pictureBox.TabIndex = 3; pictureBox.TabStop = false; // + // menuStrip + // + menuStrip.ImageScalingSize = new Size(32, 32); + menuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem }); + menuStrip.Location = new Point(0, 0); + menuStrip.Name = "menuStrip"; + menuStrip.Size = new Size(1700, 40); + menuStrip.TabIndex = 4; + menuStrip.Text = "menuStrip1"; + // + // fileToolStripMenuItem + // + fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem }); + fileToolStripMenuItem.Name = "fileToolStripMenuItem"; + fileToolStripMenuItem.Size = new Size(71, 36); + fileToolStripMenuItem.Text = "File"; + // + // saveToolStripMenuItem + // + saveToolStripMenuItem.Name = "saveToolStripMenuItem"; + saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S; + saveToolStripMenuItem.Size = new Size(277, 44); + saveToolStripMenuItem.Text = "Save"; + saveToolStripMenuItem.Click += saveToolStripMenuItem_Click; + // + // loadToolStripMenuItem + // + loadToolStripMenuItem.Name = "loadToolStripMenuItem"; + loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + loadToolStripMenuItem.Size = new Size(277, 44); + loadToolStripMenuItem.Text = "Load"; + loadToolStripMenuItem.Click += loadToolStripMenuItem_Click; + // + // saveFileDialog + // + saveFileDialog.Filter = "txt file|*.txt"; + // + // openFileDialog + // + openFileDialog.Filter = "txt file|*.txt"; + // // ServiceForm2 // AutoScaleDimensions = new SizeF(13F, 32F); @@ -254,6 +302,8 @@ ClientSize = new Size(1700, 1007); Controls.Add(pictureBox); Controls.Add(groupBox); + Controls.Add(menuStrip); + MainMenuStrip = menuStrip; Name = "ServiceForm2"; Text = "ServiceForm2"; groupBox.ResumeLayout(false); @@ -262,7 +312,10 @@ toolPanel.ResumeLayout(false); toolPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)pictureBox).EndInit(); + menuStrip.ResumeLayout(false); + menuStrip.PerformLayout(); ResumeLayout(false); + PerformLayout(); } #endregion @@ -285,5 +338,11 @@ private Button btnDeleteCollection; private Button btnCreateCompany; private Panel toolPanel; + private MenuStrip menuStrip; + private ToolStripMenuItem fileToolStripMenuItem; + private ToolStripMenuItem saveToolStripMenuItem; + private ToolStripMenuItem loadToolStripMenuItem; + private SaveFileDialog saveFileDialog; + private OpenFileDialog openFileDialog; } } \ No newline at end of file diff --git a/ProjectCruiser/ServiceForm2.cs b/ProjectCruiser/ServiceForm2.cs index fb6f4d7..3b0c05f 100644 --- a/ProjectCruiser/ServiceForm2.cs +++ b/ProjectCruiser/ServiceForm2.cs @@ -21,17 +21,7 @@ public partial class ServiceForm2 : Form toolPanel.Enabled = false; } - // Color picker (default : random) - private static Color pickColor(Random r) - { - Color cl = new Color(); - ColorDialog dialog = new(); - - if (dialog.ShowDialog() == DialogResult.OK) cl = dialog.Color; - else Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256)); - - return cl; - } + // Color picker (default : random) <...> // Добавление корабля private void btnAddTransport_Click(object sender, EventArgs e) @@ -194,4 +184,41 @@ public partial class ServiceForm2 : Form toolPanel.Enabled = true; // block of buttons at the right bottom RefreshListBoxItems(); } + + // saving to file + private void saveToolStripMenuItem_Click(object sender, EventArgs e) + { + if (saveFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.SaveData(saveFileDialog.FileName)) + { + MessageBox.Show(" < Saved succesfully >", + "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + else + { + MessageBox.Show("< Failed to save >", "Result :", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + // loading from file + private void loadToolStripMenuItem_Click(object sender, EventArgs e) + { + if (openFileDialog.ShowDialog() == DialogResult.OK) + { + if (_storageCollection.LoadData(openFileDialog.FileName)) + { + MessageBox.Show(" < Loaded succesfully >", + "Result :", MessageBoxButtons.OK, MessageBoxIcon.Information); + RefreshListBoxItems(); + } + else + { + MessageBox.Show("< Failed to load >", "Result :", + MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } } diff --git a/ProjectCruiser/ServiceForm2.resx b/ProjectCruiser/ServiceForm2.resx index af32865..e8405d2 100644 --- a/ProjectCruiser/ServiceForm2.resx +++ b/ProjectCruiser/ServiceForm2.resx @@ -117,4 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + 17, 17 + + + 217, 17 + + + 460, 17 + \ No newline at end of file