lab7 done

This commit is contained in:
Valitov.Damir 2023-04-21 23:04:27 +04:00
parent a3476e7c7e
commit c24f435746
15 changed files with 418 additions and 34 deletions

View File

@ -40,7 +40,6 @@ namespace Sailboat
{
BodyColor = newBaseColor;
}
}
}

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

View File

@ -36,5 +36,9 @@ namespace Sailboat
{
_boat.SetPosition(x, y, width, height);
}
public string GetInfo() => _boat?.GetDataForSave();
public static IDrawingObject Create(string data) => new DrawingObjectBoat(data.CreateDrawningBoat());
}
}

42
Sailboat/ExtentionBoat.cs Normal file
View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat
{
internal static class ExtentionBoat
{
private static readonly char _separatorForObject = ':';
public static DrawingBoat CreateDrawningBoat(this string info)
{
string[] strs = info.Split(_separatorForObject);
if (strs.Length == 3)
{
return new DrawingBoat(Convert.ToInt32(strs[0]),
Convert.ToInt32(strs[1]), Color.FromName(strs[2]));
}
if (strs.Length == 6)
{
return new DrawingSailboat(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 DrawingBoat drawingBoat)
{
var boat = drawingBoat.Boat;
var str = $"{boat.Speed}{_separatorForObject}{boat.Weight}{_separatorForObject}{boat.BodyColor.Name}";
if (boat is not Sailboat sailboat)
{
return str;
}
return $"{str}{_separatorForObject}{sailboat.EdgeColor.Name}{_separatorForObject}{sailboat.Sail}{_separatorForObject}{sailboat.ExtendedBody}";
}
}
}

View File

@ -46,9 +46,16 @@ namespace Sailboat
this.maskedTextBoxPosition = new System.Windows.Forms.MaskedTextBox();
this.btn_add_boat = 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.groupBoxTools.SuspendLayout();
this.groupBoxMaps.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit();
this.menuStrip.SuspendLayout();
this.SuspendLayout();
//
// groupBoxTools
@ -64,9 +71,9 @@ namespace Sailboat
this.groupBoxTools.Controls.Add(this.maskedTextBoxPosition);
this.groupBoxTools.Controls.Add(this.btn_add_boat);
this.groupBoxTools.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBoxTools.Location = new System.Drawing.Point(707, 0);
this.groupBoxTools.Location = new System.Drawing.Point(707, 28);
this.groupBoxTools.Name = "groupBoxTools";
this.groupBoxTools.Size = new System.Drawing.Size(250, 609);
this.groupBoxTools.Size = new System.Drawing.Size(250, 581);
this.groupBoxTools.TabIndex = 0;
this.groupBoxTools.TabStop = false;
this.groupBoxTools.Text = "Инструменты";
@ -138,7 +145,7 @@ namespace Sailboat
this.btn_left.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btn_left.BackgroundImage = global::Sailboat.Properties.Resources.left;
this.btn_left.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.btn_left.Location = new System.Drawing.Point(19, 552);
this.btn_left.Location = new System.Drawing.Point(19, 524);
this.btn_left.Name = "btn_left";
this.btn_left.Size = new System.Drawing.Size(70, 40);
this.btn_left.TabIndex = 11;
@ -150,7 +157,7 @@ namespace Sailboat
this.btn_up.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btn_up.BackgroundImage = global::Sailboat.Properties.Resources.up;
this.btn_up.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.btn_up.Location = new System.Drawing.Point(95, 506);
this.btn_up.Location = new System.Drawing.Point(95, 478);
this.btn_up.Name = "btn_up";
this.btn_up.Size = new System.Drawing.Size(75, 40);
this.btn_up.TabIndex = 10;
@ -162,7 +169,7 @@ namespace Sailboat
this.btn_down.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btn_down.BackgroundImage = global::Sailboat.Properties.Resources.down;
this.btn_down.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.btn_down.Location = new System.Drawing.Point(95, 552);
this.btn_down.Location = new System.Drawing.Point(95, 524);
this.btn_down.Name = "btn_down";
this.btn_down.Size = new System.Drawing.Size(75, 40);
this.btn_down.TabIndex = 9;
@ -174,7 +181,7 @@ namespace Sailboat
this.btn_right.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btn_right.BackgroundImage = global::Sailboat.Properties.Resources.right;
this.btn_right.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Zoom;
this.btn_right.Location = new System.Drawing.Point(174, 552);
this.btn_right.Location = new System.Drawing.Point(174, 524);
this.btn_right.Name = "btn_right";
this.btn_right.Size = new System.Drawing.Size(70, 40);
this.btn_right.TabIndex = 8;
@ -232,12 +239,54 @@ namespace Sailboat
// 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, 28);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(707, 609);
this.pictureBox.Size = new System.Drawing.Size(707, 581);
this.pictureBox.TabIndex = 0;
this.pictureBox.TabStop = false;
//
// menuStrip
//
this.menuStrip.ImageScalingSize = new System.Drawing.Size(20, 20);
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(957, 28);
this.menuStrip.TabIndex = 1;
this.menuStrip.Text = "menuStrip";
//
// файл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(59, 24);
this.файлToolStripMenuItem.Text = "Файл";
//
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(224, 26);
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";
//
// FormMapWithSetBoats
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
@ -245,6 +294,8 @@ namespace Sailboat
this.ClientSize = new System.Drawing.Size(957, 609);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBoxTools);
this.Controls.Add(this.menuStrip);
this.MainMenuStrip = this.menuStrip;
this.Name = "FormMapWithSetBoats";
this.Text = "FormMapWithSetBoats";
this.groupBoxTools.ResumeLayout(false);
@ -252,7 +303,10 @@ namespace Sailboat
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();
}
@ -275,5 +329,11 @@ namespace Sailboat
private System.Windows.Forms.Button btn_delete_map;
private System.Windows.Forms.ListBox listBoxMaps;
private System.Windows.Forms.Button btn_add_map;
private System.Windows.Forms.MenuStrip menuStrip;
private System.Windows.Forms.ToolStripMenuItem файлToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem SaveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem LoadToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
}
}

View File

@ -1,5 +1,6 @@
using System;
 using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using System.ComponentModel;
using System.Data;
using System.Drawing;
@ -12,16 +13,19 @@ namespace Sailboat
{
public partial class FormMapWithSetBoats : Form
{
private readonly Dictionary<string, AbstractMap> _mapsDict = new Dictionary<string, AbstractMap>() {
private readonly Dictionary<string, AbstractMap> _mapsDict = new Dictionary<string, AbstractMap>()
{
{ "Простая карта", new SimpleMap() },
{ "Водная карта", new WaterMap() }
};
private readonly MapsCollection _mapsCollection;
private ILogger _logger;
public FormMapWithSetBoats()
public FormMapWithSetBoats(ILogger<FormMapWithSetBoats> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
comboBoxMapSelector.Items.Clear();
foreach (var item in _mapsDict)
@ -66,14 +70,30 @@ namespace Sailboat
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();
var deletedBoat = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedBoat != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удалён объект {@Tanker}", deletedBoat);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogWarning("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
else
catch (BoatNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
@ -127,20 +147,24 @@ namespace Sailboat
if (comboBoxMapSelector.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("При добавлении карты {0}", comboBoxMapSelector.SelectedIndex == -1 ? "Не была выбрана карта" : "Не была названа карта");
return;
}
if (!_mapsDict.ContainsKey(comboBoxMapSelector.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Отсутствует карта с типом {0}", comboBoxMapSelector.Text);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[comboBoxMapSelector.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта: {textBoxNewMapName.Text}");
}
private void listBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation("Осуществлён переход на карту под названием {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
}
private void btn_delete_map_Click(object sender, EventArgs e)
@ -152,25 +176,73 @@ namespace Sailboat
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_logger.LogInformation("Удалена карта {0}", listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
}
}
private void InsertBoatCheck(DrawingBoat _boat)
{
if (listBoxMaps.SelectedIndex == -1)
try
{
return;
if (listBoxMaps.SelectedIndex == -1)
{
return;
}
DrawingObjectBoat boat = new(_boat);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0)
{
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Tanker}", _boat);
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
}
}
DrawingObjectBoat boat = new(_boat);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] + boat >= 0)
catch (StorageOverflowException ex)
{
MessageBox.Show("Объект добавлен");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
}
private void SaveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("Не удалось добавить объект");
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
_logger.LogInformation("Сохранение прошло успешно. Расположение файла: {0}", saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Не сохранилось:{ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Не удалось сохранить файл '{0}'. Текст ошибки: {1}", saveFileDialog.FileName, ex.Message);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
_logger.LogInformation("Загрузка данных из файла '{0}' прошла успешно", openFileDialog.FileName);
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
_logger.LogWarning("Не удалось загрузить файл '{0}'. Текст ошибки: {1}", openFileDialog.FileName, ex.Message);
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>144, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>311, 17</value>
</metadata>
</root>

View File

@ -37,5 +37,10 @@ namespace Sailboat
/// </summary>
/// <returns></returns>
(float Left, float Right, float Top, float Bottom) GetCurrentPosition();
/// <summary>
/// Получение информации по объекту
/// </summary>
string GetInfo();
}
}

View File

@ -132,5 +132,22 @@ namespace Sailboat
if (currentHeight > height) return;
}
}
public string GetData(char separatorType, char separatorData)
{
string data = $"{_map.GetType().Name}{separatorType}";
foreach (var boat in _setBoats.GetBoats())
{
data += $"{boat.GetInfo()}{separatorData}";
}
return data;
}
public void LoadData(string[] records)
{
foreach (var rec in records)
{
_setBoats.Insert(DrawingObjectBoat.Create(rec) as T);
}
}
}
}

View File

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@ -8,7 +9,7 @@ namespace Sailboat
{
internal class MapsCollection
{
readonly Dictionary<string, MapWithSetBoatsGeneric<DrawingObjectBoat, AbstractMap>> _mapStorages;
readonly Dictionary<string, MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>> _mapStorages;
public List<string> Keys => _mapStorages.Keys.ToList();
@ -16,9 +17,12 @@ namespace Sailboat
private readonly int _pictureHeight;
private readonly char separatorDict = '|';
private readonly char separatorData = ';';
public MapsCollection(int pictureWidth, int pictureHeight)
{
_mapStorages = new Dictionary<string, MapWithSetBoatsGeneric<DrawingObjectBoat, AbstractMap>>();
_mapStorages = new Dictionary<string, MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
@ -26,7 +30,7 @@ namespace Sailboat
public void AddMap(string name, AbstractMap map)
{
if (Keys.Contains(name)) return;
_mapStorages.Add(name, new MapWithSetBoatsGeneric<DrawingObjectBoat, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages.Add(name, new MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
}
public void DelMap(string name)
@ -34,7 +38,7 @@ namespace Sailboat
_mapStorages.Remove(name);
}
public MapWithSetBoatsGeneric<DrawingObjectBoat, AbstractMap> this[string ind]
public MapWithSetBoatsGeneric<IDrawingObject, AbstractMap> this[string ind]
{
get
{
@ -42,5 +46,64 @@ namespace Sailboat
return result;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
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}");
}
}
}
/// <summary>
/// Загрузка нформации по автомобилям на парковках из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader sr = new(filename))
{
string str = "";
if ((str = sr.ReadLine()) == null || !str.Contains("MapsCollection"))
{
throw new FileFormatException("Формат данных в файле не правильный");
}
_mapStorages.Clear();
while ((str = sr.ReadLine()) != null)
{
var tempElem = str.Split(separatorDict);
AbstractMap map = null;
switch (tempElem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "WaterMap":
map = new WaterMap();
break;
}
_mapStorages.Add(tempElem[0], new MapWithSetBoatsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[tempElem[0]].LoadData(tempElem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
}
}
}

View File

@ -1,7 +1,9 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
namespace Sailboat
@ -17,7 +19,30 @@ namespace Sailboat
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMapWithSetBoats());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormMapWithSetBoats>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormMapWithSetBoats>()
.AddLogging(option =>
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(path: "serilog.json")
.Build();
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

@ -6,4 +6,30 @@
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
<ItemGroup>
<None Remove="serilog.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="serilog.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" 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.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.Hosting" Version="5.0.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
</ItemGroup>
</Project>

View File

@ -28,6 +28,10 @@ namespace Sailboat
public int Insert(T boat, int position)
{
if (Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position >= _maxCount || BusyPlaces == _maxCount)
{
return -1;
@ -39,6 +43,10 @@ namespace Sailboat
public T Remove(int position)
{
if (position >= Count || position < 0)
{
throw new BoatNotFoundException(position);
}
if (position < 0 || position >= _maxCount)
{
return null;

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 Sailboat
{
[Serializable]
internal class StorageOverflowException : ApplicationException
{
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 context) : base(info, context) { }
}
}

16
Sailboat/serilog.json Normal file
View File

@ -0,0 +1,16 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log.log",
"rollingInterval": "Day"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
}
}