9 Commits

Author SHA1 Message Date
Макс Бондаренко
9c0a1678a0 Готов к pull 2022-12-01 23:00:18 +04:00
Макс Бондаренко
0a4cfe48c3 Для pull 2022-12-01 22:53:59 +04:00
Макс Бондаренко
9980a9395d удалил лишний файл 2022-11-30 09:37:47 +04:00
Макс Бондаренко
fa3f46c12c готово 2022-11-30 09:34:54 +04:00
Макс Бондаренко
02a9aee9a3 подправил 2022-11-30 09:15:42 +04:00
Макс Бондаренко
84f6cf46f9 дополнил 2022-11-30 09:01:56 +04:00
Макс Бондаренко
deb44d6146 Готово 2022-11-28 00:42:09 +04:00
Макс Бондаренко
3a49819994 Этап 1 2022-11-27 23:12:56 +04:00
Макс Бондаренко
c71fd055da Готово 2022-11-23 17:09:15 +04:00
15 changed files with 406 additions and 56 deletions

View File

@@ -36,5 +36,9 @@ namespace WarmlyShip
{
_warmlyShip?.SetPosition(x, y, width, height);
}
public string GetInfo() => _warmlyShip?.GetDataForSave();
public static IDrawningObject Create(string data) => new DrawningObjectShip(data.CreateDrawningShip());
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
internal static class ExtentionShip
{
private static readonly char _separatorForObject = ':';
public static DrawingWarmlyShip CreateDrawningShip(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawingWarmlyShip(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawningMotorShip(Convert.ToInt32(strs[0]), Convert.ToInt32(strs[1]), Color.FromName(strs[2]), Color.FromName(strs[3]), Convert.ToBoolean(strs[4]), Convert.ToBoolean(strs[5]));
}
return null;
}
public static string GetDataForSave(this DrawingWarmlyShip warmlyShip)
{
var ship = warmlyShip.warmlyShip;
var str = $"{ship.Speed}{_separatorForObject}{ship.Weight}{_separatorForObject}{ship.BodyColor.Name}";
if (ship is not EntityMotorShip motorShip)
{
return str;
}
return $"{str}{_separatorForObject}{motorShip.DopColor.Name}{_separatorForObject}{motorShip.Tubes}{_separatorForObject}{motorShip.Cistern}";
}
}
}

View File

@@ -45,9 +45,16 @@
this.buttonRemoveShip = new System.Windows.Forms.Button();
this.buttonAddShip = new System.Windows.Forms.Button();
this.pictureBox = new System.Windows.Forms.PictureBox();
this.menuStrip = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.LoadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.groupBox1.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
@@ -63,9 +70,9 @@
this.groupBox1.Controls.Add(this.buttonRemoveShip);
this.groupBox1.Controls.Add(this.buttonAddShip);
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox1.Location = new System.Drawing.Point(815, 0);
this.groupBox1.Location = new System.Drawing.Point(815, 24);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(200, 648);
this.groupBox1.Size = new System.Drawing.Size(200, 624);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
@@ -132,7 +139,6 @@
this.comboBoxSelectorMap.Name = "comboBoxSelectorMap";
this.comboBoxSelectorMap.Size = new System.Drawing.Size(176, 23);
this.comboBoxSelectorMap.TabIndex = 0;
//this.comboBoxSelectorMap.SelectedIndexChanged += new System.EventHandler(this.ComboBoxSelectorMap_SelectedIndexChanged);
//
// maskedTextBoxPosition
//
@@ -147,7 +153,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::WarmlyShip.Properties.Resources.todown;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(75, 589);
this.buttonDown.Location = new System.Drawing.Point(75, 565);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(50, 50);
this.buttonDown.TabIndex = 10;
@@ -159,7 +165,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::WarmlyShip.Properties.Resources.toleft;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(19, 589);
this.buttonLeft.Location = new System.Drawing.Point(19, 565);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(50, 50);
this.buttonLeft.TabIndex = 9;
@@ -171,7 +177,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::WarmlyShip.Properties.Resources.totop;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(75, 533);
this.buttonUp.Location = new System.Drawing.Point(75, 509);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(50, 50);
this.buttonUp.TabIndex = 8;
@@ -183,7 +189,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::WarmlyShip.Properties.Resources.toright;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(131, 589);
this.buttonRight.Location = new System.Drawing.Point(131, 565);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(50, 50);
this.buttonRight.TabIndex = 7;
@@ -233,12 +239,52 @@
// pictureBox
//
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 0);
this.pictureBox.Location = new System.Drawing.Point(0, 24);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(815, 648);
this.pictureBox.Size = new System.Drawing.Size(815, 624);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(1015, 24);
this.menuStrip.TabIndex = 2;
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.SaveToolStripMenuItem,
this.LoadToolStripMenuItem});
this.файлToolStripMenuItem.Name = айлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
// openFileDialog
//
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormMapWithSetShip
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
@@ -246,6 +292,8 @@
this.ClientSize = new System.Drawing.Size(1015, 648);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetShip";
this.Text = "FormMapWithSetShip";
this.groupBox1.ResumeLayout(false);
@@ -253,7 +301,10 @@
this.groupBoxMaps.ResumeLayout(false);
this.groupBoxMaps.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit();
this.menuStrip.ResumeLayout(false);
this.menuStrip.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
@@ -276,5 +327,11 @@
private ListBox listBoxMaps;
private Button buttonAddMap;
private TextBox textBoxNewMapName;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@@ -23,9 +24,12 @@ namespace WarmlyShip
private readonly MapsCollection _mapsCollection;
public FormMapWithSetShip()
private readonly ILogger _logger;
public FormMapWithSetShip(ILogger<FormMapWithSetShip> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapsDict)
@@ -66,6 +70,7 @@ namespace WarmlyShip
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
@@ -81,9 +86,9 @@ namespace WarmlyShip
}
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ??
string.Empty);
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
}
@@ -100,15 +105,24 @@ namespace WarmlyShip
{
return;
}
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectShip(ship) > -1)
try
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectShip(ship) > -1)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Добавлен объект: {ship} на карте: {listBoxMaps.SelectedItem}");
}
}
else
catch (StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Ошибка переполнения при добавлении объекта: {ex.Message}");
MessageBox.Show($"Ошибка переполнения: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning($"Неизвестная ошибка при добавлении объекта: {ex.Message}");
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
@@ -127,15 +141,29 @@ namespace WarmlyShip
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
MessageBox.Show("Объект удален");
pictureBox.Image =
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
{
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Удален объект с позиции: [{pos}] на карте: {listBoxMaps.SelectedItem}");
}
}
else
catch (ShipNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning($"Ошибка при удалении объекта на позиции: {ex.Message}");
MessageBox.Show($"Ошибка удаления: {ex.Message} ");
}
catch (StorageOverflowException ex)
{
_logger.LogWarning($"Ошибка при удалении объекта на позиции: {ex.Message}");
MessageBox.Show($"Превышение размерности: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning($"Неизвестная ошибка при удалении объекта на позиции: {ex.Message}");
MessageBox.Show($"Неизвестная ошибка: {ex.Message} ");
}
}
@@ -146,6 +174,7 @@ namespace WarmlyShip
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Переход в хранилище: {listBoxMaps.SelectedItem}");
}
private void ButtonShowOnMap_Click(object sender, EventArgs e)
@@ -155,6 +184,7 @@ namespace WarmlyShip
return;
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowOnMap();
_logger.LogInformation($"Переход на карту: {listBoxMaps.SelectedItem}");
}
private void ButtonMove_Click(object sender, EventArgs e)
@@ -183,5 +213,42 @@ namespace WarmlyShip
}
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].MoveObject(dir);
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation($"Карта успешно сохранена в файл: {saveFileDialog.FileName}");
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogWarning($"Не сохранилось в файл: {saveFileDialog.FileName}");
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation($"Карта успешно загружена из файла: {openFileDialog.FileName}");
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
}
catch (Exception ex)
{
_logger.LogWarning($"Не загрузилось из файла: {openFileDialog.FileName}");
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}

View File

@@ -57,4 +57,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>125, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>265, 17</value>
</metadata>
</root>

View File

@@ -13,5 +13,7 @@ namespace WarmlyShip
void MoveObject(Direction direction);
void DrawningObject(Graphics g);
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
string GetInfo();
}
}

View File

@@ -65,6 +65,24 @@ namespace WarmlyShip
return new(_pictureWidth, _pictureHeight);
}
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var ship in _setShips.GetShips())
{
data += $"{ship.GetInfo()}{separatorData}";
}
return data;
}
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setShips.Insert(DrawningObjectShip.Create(rec) as T);
}
}
private void Shaking()
{
int j = _setShips.Count - 1;
@@ -107,17 +125,6 @@ namespace WarmlyShip
private void DrawShips(Graphics g)
{
/*for (int i = 0; i < _setShips.Count; ++i)
{
if (_setShips[i] != null )
{
int temp = 0;
if (_setShips[i].GetCurrentPosition().Bottom - _setShips[i].GetCurrentPosition().Top < 75) temp = (int)(_setShips[i].GetCurrentPosition().Bottom - _setShips[i].GetCurrentPosition().Top);
_setShips[i].SetObject((_pictureWidth / _placeSizeWidth - (i % (_pictureWidth / _placeSizeWidth)) - 1) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight + temp, _pictureWidth, _pictureHeight);
_setShips[i].DrawningObject(g);
}
}*/
int i = 0;
foreach (var ship in _setShips.GetShips())
{
@@ -131,6 +138,5 @@ namespace WarmlyShip
++i;
}
}
}
}

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -9,7 +10,7 @@ namespace WarmlyShip
{
internal class MapsCollection
{
readonly Dictionary<string, MapWithSetShipGeneric<DrawningObjectShip, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetShipGeneric<IDrawningObject, AbstractMap>> _mapStorages;
public List<string> Keys => _mapStorages.Keys.ToList();
@@ -17,9 +18,13 @@ namespace WarmlyShip
private readonly int _pictureHeight;
private readonly char separatorDict = '|';
private readonly char separatorData = ';';
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetShipGeneric<DrawningObjectShip, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetShipGeneric<IDrawningObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@@ -27,7 +32,7 @@ namespace WarmlyShip
public void AddMap(string name, AbstractMap map)
{
if (_mapStorages.ContainsKey(name)) return;
_mapStorages.Add(name, new MapWithSetShipGeneric<DrawningObjectShip, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.Add(name, new MapWithSetShipGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
public void DelMap(string name)
@@ -36,7 +41,7 @@ namespace WarmlyShip
_mapStorages.Remove(name);
}
public MapWithSetShipGeneric<DrawningObjectShip, AbstractMap> this[string ind]
public MapWithSetShipGeneric<IDrawningObject, AbstractMap> this[string ind]
{
get
{
@@ -45,5 +50,68 @@ namespace WarmlyShip
}
}
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter sw = new(filename))
{
sw.Write($"MapsCollection{Environment.NewLine}");
foreach (var storage in _mapStorages)
{
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
}
}
}
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string bufferStr;
bool firstIn = true;
while ((bufferStr = sr.ReadLine()) != null)
{
if (firstIn)
{
if (!bufferStr.Contains("MapsCollection"))
{
throw new FormatException("Формат данных в файле не правильный");
}
else
{
_mapStorages.Clear();
}
firstIn = false;
}
else
{
var elem = bufferStr.Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "SecondMap":
map = new SecondMap();
break;
case "LastMap":
map = new LastMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetShipGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
}
}

View File

@@ -1,3 +1,8 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
namespace WarmlyShip
{
internal static class Program
@@ -11,7 +16,31 @@ namespace WarmlyShip
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormMapWithSetShip());
}
}
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider =
services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetShip>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetShip>().AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilogConfig.json", optional: false, reloadOnChange: true)
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@@ -27,15 +27,16 @@ namespace WarmlyShip
public int Insert(T ship, int position)
{
if (position < 0 || position > Count || Count == _maxCount) return -1;
if (position < 0 || position > Count || Count == _maxCount) throw new StorageOverflowException(_maxCount);
_places.Insert(position, ship);
return position;
}
public T Remove(int position)
{
if (position >= _maxCount || position >= _places.Count) throw new ShipNotFoundException(position);
T DelElement = _places[position];
_places[position] = null;
_places.Remove(DelElement);
return DelElement;
}

View File

@@ -1,10 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WarmlyShip
{
public delegate void ShipDelegate(DrawingWarmlyShip warmlyShip);
}

View File

@@ -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 WarmlyShip
{
[Serializable]
internal class ShipNotFoundException : Exception
{
public ShipNotFoundException(int i) : base($"Не найден объект по позиции { i}") { }
public ShipNotFoundException() : base() { }
public ShipNotFoundException(string message) : base(message) { }
public ShipNotFoundException(string message, Exception exception) : base(message, exception) { }
protected ShipNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -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 WarmlyShip
{
[Serializable]
internal class StorageOverflowException : Exception
{
public StorageOverflowException(int count) : base($"В наборе превышено допустимое количество: { count}") { }
public StorageOverflowException() : base() { }
public StorageOverflowException(string message) : base(message) { }
public StorageOverflowException(string message, Exception exception) : base(message, exception) { }
protected StorageOverflowException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@@ -8,6 +8,30 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="serilogConfig.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="serilogConfig.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Serilog" Version="2.12.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Settings.Delegates" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "Logs/log_.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
]
}
}