Nevaeva K. A. LabWork07 #7

Closed
ksenia_nevaeva wants to merge 3 commits from Lab_7 into Lab_6
11 changed files with 212 additions and 36 deletions

View File

@ -8,6 +8,30 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<None Remove="appsettings.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<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.Enrichers.Environment" Version="2.2.0" />
<PackageReference Include="Serilog.Enrichers.Thread" Version="3.1.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>

View File

@ -72,7 +72,7 @@
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Right;
this.groupBox1.Location = new System.Drawing.Point(553, 33);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(300, 654);
this.groupBox1.Size = new System.Drawing.Size(300, 709);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
@ -154,7 +154,7 @@
this.buttonUp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonUp.BackgroundImage = global::ContainerShip.Properties.Resources.upArrow;
this.buttonUp.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonUp.Location = new System.Drawing.Point(131, 536);
this.buttonUp.Location = new System.Drawing.Point(131, 591);
this.buttonUp.Name = "buttonUp";
this.buttonUp.Size = new System.Drawing.Size(50, 50);
this.buttonUp.TabIndex = 9;
@ -166,7 +166,7 @@
this.buttonRight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonRight.BackgroundImage = global::ContainerShip.Properties.Resources.LeftArrow;
this.buttonRight.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonRight.Location = new System.Drawing.Point(187, 592);
this.buttonRight.Location = new System.Drawing.Point(187, 647);
this.buttonRight.Name = "buttonRight";
this.buttonRight.Size = new System.Drawing.Size(50, 50);
this.buttonRight.TabIndex = 8;
@ -178,7 +178,7 @@
this.buttonDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonDown.BackgroundImage = global::ContainerShip.Properties.Resources.DownArrow;
this.buttonDown.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonDown.Location = new System.Drawing.Point(131, 592);
this.buttonDown.Location = new System.Drawing.Point(131, 647);
this.buttonDown.Name = "buttonDown";
this.buttonDown.Size = new System.Drawing.Size(50, 50);
this.buttonDown.TabIndex = 7;
@ -190,7 +190,7 @@
this.buttonLeft.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.buttonLeft.BackgroundImage = global::ContainerShip.Properties.Resources.RightArrow;
this.buttonLeft.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.buttonLeft.Location = new System.Drawing.Point(75, 592);
this.buttonLeft.Location = new System.Drawing.Point(75, 647);
this.buttonLeft.Name = "buttonLeft";
this.buttonLeft.Size = new System.Drawing.Size(50, 50);
this.buttonLeft.TabIndex = 6;
@ -240,7 +240,7 @@
this.pictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBox.Location = new System.Drawing.Point(0, 33);
this.pictureBox.Name = "pictureBox";
this.pictureBox.Size = new System.Drawing.Size(553, 654);
this.pictureBox.Size = new System.Drawing.Size(553, 709);
this.pictureBox.TabIndex = 1;
this.pictureBox.TabStop = false;
//
@ -267,14 +267,14 @@
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(270, 34);
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(212, 34);
this.SaveToolStripMenuItem.Text = "Сохранение";
this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click);
//
// LoadToolStripMenuItem
//
this.LoadToolStripMenuItem.Name = "LoadToolStripMenuItem";
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(270, 34);
this.LoadToolStripMenuItem.Size = new System.Drawing.Size(212, 34);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
@ -291,7 +291,7 @@
//
this.AutoScaleDimensions = new System.Drawing.SizeF(10F, 25F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(853, 687);
this.ClientSize = new System.Drawing.Size(853, 742);
this.Controls.Add(this.pictureBox);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.menuStrip);

View File

@ -8,6 +8,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.DataFormats;
using Microsoft.Extensions.Logging;
namespace ContainerShip
{
@ -28,11 +29,18 @@ namespace ContainerShip
/// <summary>
/// Конструктор
/// </summary>
public FormMapWithSetShips()
/// /// <summary>
/// Логер
/// </summary>
private readonly ILogger _logger;
private Action<DrawingShip> addShipAction;
public FormMapWithSetShips(ILogger<FormMapWithSetShips> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox.Width, pictureBox.Height);
ComboBoxSelectorMap.Items.Clear();
addShipAction = addShip;
foreach (var elem in _mapsDict)
{
ComboBoxSelectorMap.Items.Add(elem.Key);
@ -60,6 +68,30 @@ namespace ContainerShip
listBoxMaps.SelectedIndex = index;
}
}
private void addShip(DrawingShip ship)
{
try
{
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].add(new DrawingObjectShip(ship));
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Добавлен объект {ship}");
}
catch(ArgumentNullException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch(StorageOverflowException ex)
{
MessageBox.Show(ex.Message);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}", "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
}
/// <summary>
/// Добавление объекта
/// </summary>
@ -72,9 +104,7 @@ namespace ContainerShip
return;
}
var formShipConfig = new FormShipConfig();
formShipConfig.AddEvent(new Action<DrawingShip>(ship => {
_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].add(new DrawingObjectShip(ship));
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();}));
formShipConfig.AddEvent(addShipAction);
formShipConfig.Show();
}
/// <summary>
@ -97,14 +127,22 @@ namespace ContainerShip
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
IDrawingObject drawingObject = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
MessageBox.Show("Объект удален");
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Удален объект {drawingObject}");
}
else
catch (ShipNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show($"Ошибка удаления: {ex.Message}");
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
_logger.LogWarning($"Ошибка: {ex.Message}");
}
}
/// <summary>
@ -179,6 +217,7 @@ namespace ContainerShip
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapsDict[ComboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
/// <summary>
/// Выбор карты
@ -188,6 +227,7 @@ namespace ContainerShip
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox.Image = _mapsCollection[listBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
_logger.LogInformation($"Выбрана карта {listBoxMaps.SelectedItem?.ToString() ?? string.Empty}");
}
/// <summary>
/// Удаление карты
@ -200,11 +240,12 @@ namespace ContainerShip
{
return;
}
string deletedMapName = listBoxMaps.SelectedItem?.ToString();
if (MessageBox.Show($"Удалить карту {listBoxMaps.SelectedItem}?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_mapsCollection.DelMap(listBoxMaps.SelectedItem?.ToString() ?? string.Empty);
ReloadMaps();
_logger.LogInformation($"Удалена карта {deletedMapName}");
}
}
@ -212,13 +253,15 @@ namespace ContainerShip
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"Данные сохранены в файле {saveFileDialog.FileName}");
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
@ -227,14 +270,27 @@ namespace ContainerShip
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
ReloadMaps();
_logger.LogInformation($"Данные загружены из файла {openFileDialog.FileName}");
}
else
catch (FileFormatException ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch (FileNotFoundException ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Ошибка: {ex.Message}");
}
}
}

View File

@ -66,4 +66,7 @@
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>357, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>25</value>
</metadata>
</root>

View File

@ -71,7 +71,7 @@ namespace ContainerShip
foreach (var ship in _setShips.GetShips())
{
return _map.CreateMap(_pictureWidth, _pictureHeight, ship);
}
}
return new(_pictureWidth, _pictureHeight);
}
public string GetData(char separatorType, char separatorData)

View File

@ -104,7 +104,7 @@ namespace ContainerShip
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
@ -119,19 +119,17 @@ namespace ContainerShip
sw.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}", sw);
}
}
return true;
}
/// <summary>
/// Загрузка нформации по автомобилям на парковках из файла
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не найден");
}
using (FileStream fs = new(filename, FileMode.Open))
using (StreamReader sr = new StreamReader(fs))
@ -139,7 +137,10 @@ namespace ContainerShip
string line;
line = sr.ReadLine();
line.Trim();
if (line != "MapsCollection") return false;
if (line != "MapsCollection")
{
throw new FileFormatException("Неправильный формат данных в файле");
}
_mapStorages.Clear();
while ((line = sr.ReadLine()) != null)
{
@ -158,7 +159,6 @@ namespace ContainerShip
_mapStorages.Add(elem[0], new MapWithSetShipsGeneric<IDrawingObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
return true;
}
}
}

View File

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

View File

@ -44,8 +44,14 @@ namespace ContainerShip
/// <returns></returns>
public int Insert(T ship, int position)
{
if (position < 0 || position >= _maxCount) return -1;
if (_places.Count + 1 >= _maxCount) return -1;
if(position < 0 || position >= _maxCount)
{
throw new ShipNotFoundException(position);
}
if ( _places.Count >= _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
_places.Add(ship);
return position;
}
@ -55,10 +61,10 @@ namespace ContainerShip
/// <param name="position"></param>
/// <returns></returns>
public T Remove(int position)
{
{
if (position < 0 || position >= _maxCount)
{
return null;
throw new ShipNotFoundException(position);
}
T ship = _places[position];
_places.RemoveAt(position);

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 ContainerShip
{
[Serializable]
internal class ShipNotFoundException : ApplicationException
{
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 ContainerShip
{
[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 contex) : base(info, contex) { }
}
}

View File

@ -0,0 +1,24 @@
{
"exclude": [
"/bin",
"/bower_components",
"/jspm_packages",
"/node_modules",
"/obj",
"/platforms"
],
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Debug",
"WriteTo": [
{
"Name": "File",
"Args": { "path": "Logs/log.txt" }
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Sample"
}
}
}