Готовая 7 лабораторная работа

This commit is contained in:
Stranni15k 2022-12-22 23:10:46 +04:00
parent e3b123b725
commit b54ee7b861
10 changed files with 242 additions and 84 deletions

View File

@ -9,8 +9,20 @@
</PropertyGroup>
<ItemGroup>
<None Include="ElectricLocomotive.csproj" />
<None Include="ElectricLocomotive.csproj.user" />
<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="NLog.Extensions.Logging" Version="5.2.0" />
<PackageReference Include="Serilog" Version="2.12.1-dev-01594" />
<PackageReference Include="Serilog.Extensions.Logging" Version="3.1.1-dev-10301" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.5.0-dev-00359" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.1-dev-00947" />
<PackageReference Include="Serilog.Sinks.InfluxDBv2" Version="1.0.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
</ItemGroup>
<ItemGroup>

View File

@ -59,9 +59,9 @@
this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pictureBox1.Location = new System.Drawing.Point(0, 0);
this.pictureBox1.Location = new System.Drawing.Point(0, 27);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(808, 721);
this.pictureBox1.Size = new System.Drawing.Size(808, 694);
this.pictureBox1.TabIndex = 10;
this.pictureBox1.TabStop = false;
//
@ -265,6 +265,7 @@
this.openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
this.saveFileDialog.Filter = "txt file | *.txt";
//
// FormMapWithSetLocomotive

View File

@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
@ -20,9 +21,11 @@ namespace ElectricLocomotive
{"Карта с кустами",new BushesMap() }
};
private readonly MapsCollection _mapsCollection;
public FormMapWithSetLocomotive()
private readonly ILogger _logger;
public FormMapWithSetLocomotive(ILogger<FormMapWithSetLocomotive> logger)
{
InitializeComponent();
_logger = logger;
_mapsCollection = new MapsCollection(pictureBox1.Width, pictureBox1.Height);
comboBoxSelectorMap.Items.Clear();
foreach (var elem in _mapDict)
@ -81,23 +84,36 @@ namespace ElectricLocomotive
FormLocmotiveConfig.AddEvent(new(AddLocomotive));
FormLocmotiveConfig.Show();
}
public void AddLocomotive(DrawningLocomotive aircraft)
public void AddLocomotive(DrawningLocomotive locomotive)
{
try
{
if (ListBoxMaps.SelectedIndex == -1)
{
return;
}
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectLocomotive(aircraft) != -1)
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] + new DrawningObjectLocomotive(locomotive) != -1)
{
MessageBox.Show("Object is added");
MessageBox.Show("Объект добавлен");
_logger.LogInformation("Добавлен объект {@Locomotive}", locomotive);
pictureBox1.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
MessageBox.Show("Unable to add object");
MessageBox.Show("Не удалось добавить объект");
_logger.LogInformation("Не удалось добавить объект");
}
}
catch (StorageOverflowException ex)
{
_logger.LogWarning("Ошибка, переполнение хранилища :{0}", ex.Message);
MessageBox.Show($"Ошибка хранилище переполнено: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (ArgumentException ex)
{
_logger.LogWarning("Ошибка добавления: {0}. Объект: {@Locomotive}", ex.Message, locomotive);
MessageBox.Show(ex.Message, "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ButtonRemoveLocomotive_Click(object sender, EventArgs e)
{
@ -114,16 +130,32 @@ namespace ElectricLocomotive
return;
}
int pos = Convert.ToInt32(maskedTextBoxPosition.Text);
if (_mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos != null)
try
{
var deletedLocomotive = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty] - pos;
if (deletedLocomotive != null)
{
MessageBox.Show("Объект удален");
_logger.LogInformation("Из текущей карты удалён объект {@Locomotive}", deletedLocomotive);
pictureBox1.Image = _mapsCollection[ListBoxMaps.SelectedItem?.ToString() ?? string.Empty].ShowSet();
}
else
{
_logger.LogInformation("Не удалось удалить объект по позиции {0}. Объект равен null", pos);
MessageBox.Show("Не удалось удалить объект");
}
}
catch (LocomotiveNotFoundException ex)
{
_logger.LogWarning("Ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Ошибка удаления: {ex.Message}");
}
catch (Exception ex)
{
_logger.LogWarning("Неизвестная ошибка удаления: {0}", ex.Message);
MessageBox.Show($"Неизвестная ошибка: {ex.Message}");
}
}
private void ButtonShowStorage_Click(object sender, EventArgs e)
{
if (ListBoxMaps.SelectedIndex == -1)
@ -168,18 +200,23 @@ namespace ElectricLocomotive
}
private void ButtonAddMap_Click(object sender, EventArgs e)
{
if (comboBoxSelectorMap.SelectedIndex == -1 || string.IsNullOrEmpty(textBoxNewMapName.Text))
if (comboBoxSelectorMap.SelectedIndex == -1 ||
string.IsNullOrEmpty(textBoxNewMapName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (!_mapDict.ContainsKey(comboBoxSelectorMap.Text))
{
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show("Нет такой карты", "Ошибка", MessageBoxButtons.OK,
MessageBoxIcon.Error);
return;
}
_mapsCollection.AddMap(textBoxNewMapName.Text, _mapDict[comboBoxSelectorMap.Text]);
_mapsCollection.AddMap(textBoxNewMapName.Text,
_mapDict[comboBoxSelectorMap.Text]);
ReloadMaps();
_logger.LogInformation($"Добавлена карта {textBoxNewMapName.Text}");
}
private void ListBoxMaps_SelectedIndexChanged(object sender, EventArgs e)
{
@ -202,14 +239,15 @@ namespace ElectricLocomotive
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.SaveData(saveFileDialog.FileName))
try
{
_mapsCollection.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат",
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
@ -219,14 +257,17 @@ namespace ElectricLocomotive
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_mapsCollection.LoadData(openFileDialog.FileName))
try
{
_mapsCollection.LoadData(openFileDialog.FileName);
ReloadMaps();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show("Данные загружены успешно!", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation($"{openFileDialog.FileName} загружено.");
}
else
catch (Exception ex)
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show($"Что-то пошло не так: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning($"Не удалось загрузить: {openFileDialog.FileName} | {ex.Message}.");
}
}
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ElectricLocomotive
{
[Serializable]
internal class LocomotiveNotFoundException : ApplicationException
{
public LocomotiveNotFoundException(int i) : base($"Не найден объект по позиции{ i}") { }
public LocomotiveNotFoundException() : base() { }
public LocomotiveNotFoundException(string message) : base(message) { }
public LocomotiveNotFoundException(string message, Exception exception) : base(message, exception) { }
protected LocomotiveNotFoundException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}
}

View File

@ -118,7 +118,7 @@
foreach (var HardLocomotive in _setLocomotive.GetLocomotive())
{
(float Left, float Top, float Right, float Bottom) = HardLocomotive.GetCurrentPosition();
HardLocomotive.SetObject(ColumnIndex * _placeSizeWidth, RowIndex * _placeSizeHeight + (_placeSizeHeight - (int)(Bottom - Top) - 70), _pictureWidth, _pictureHeight);
HardLocomotive.SetObject(ColumnIndex * _placeSizeWidth, RowIndex * _placeSizeHeight + (_placeSizeHeight - (int)(Bottom - Top) - 60), _pictureWidth, _pictureHeight);
HardLocomotive.DrawningObject(g);
if (ColumnIndex == xNumOfPlaces - 1)
{

View File

@ -43,66 +43,71 @@ namespace ElectricLocomotive
return null;
}
}
private static void WriteToFile(string text, FileStream stream)
{
byte[] info = new UTF8Encoding(true).GetBytes(text);
stream.Write(info, 0, info.Length);
}
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter fs = new StreamWriter(filename))
using (FileStream fs = new(filename, FileMode.Create))
{
fs.Write($"MapsCollection{Environment.NewLine}");
WriteToFile($"MapsCollection{Environment.NewLine}", fs);
foreach (var storage in _mapStorages)
{
fs.Write($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict, separatorData)}{Environment.NewLine}");
WriteToFile($"{storage.Key}{separatorDict}{storage.Value.GetData(separatorDict,separatorData)}{Environment.NewLine}", fs);
}
}
return true;
}
public bool LoadData(string filename)
public void LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
throw new Exception("Файл не найден");
}
string str = "";
using (StreamReader fs = new StreamReader(filename))
string bufferTextFromFile = "";
using (FileStream fs = new(filename, FileMode.Open))
{
str = fs.ReadLine();
if (!str.Contains("MapsCollection"))
byte[] b = new byte[fs.Length];
UTF8Encoding temp = new(true);
while (fs.Read(b, 0, b.Length) > 0)
{
bufferTextFromFile += temp.GetString(b);
}
}
var strs = bufferTextFromFile.Split(new char[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries);
if (!strs[0].Contains("MapsCollection"))
{
//если нет такой записи, то это не те данные
return false;
throw new Exception("Формат данных в файле не правильный");
}
//очищаем записи
_mapStorages.Clear();
while ((str = fs.ReadLine()) != null)
for (int i = 1; i < strs.Length; ++i)
{
var elem = str.Split(separatorDict);
var elem = strs[i].Split(separatorDict);
AbstractMap map = null;
switch (elem[1])
{
case "SimpleMap":
map = new SimpleMap();
break;
case "BushesMap":
map = new BushesMap();
break;
case "FieldMap":
map = new FieldMap();
break;
case "BushesMap":
map = new BushesMap();
break;
}
_mapStorages.Add(elem[0], new MapWithSetLocomotivGeneric<IDrawningObject, AbstractMap>(_pictureWidth, _pictureHeight, map));
_mapStorages[elem[0]].LoadData(elem[2].Split(separatorData, StringSplitOptions.RemoveEmptyEntries));
}
}
return true;
}
}
}

View File

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

View File

@ -19,33 +19,33 @@ namespace ElectricLocomotive
}
public int Insert(T locomotive)
{
if (_places.Count > _maxCount)
{
return -1;
}
// вставка в начало набора
return Insert(locomotive, 0);
}
public int Insert(T locomotive, int position)
{
if (position >= _maxCount || position < 0) return -1;
if (Count == _maxCount)
{
throw new StorageOverflowException(_maxCount);
}
if (position < 0 || position > _maxCount) return -1;
_places.Insert(position, locomotive);
return position;
}
public T Remove(int position)
{
// проверка позиции
if (position >= _maxCount || position < 0) return null;
// удаление объекта из массива, присовив элементу массива значение null
T temp = _places[position];
if (position >= Count || position < 0)
{
throw new LocomotiveNotFoundException(position);
}
T ship = _places[position];
_places.RemoveAt(position);
return temp;
return ship;
}
public T this[int position]
{
get
{
if (position >= _places.Count || position < 0)
if (position >= Count || position < 0)
{
return null;
}
@ -53,7 +53,7 @@ namespace ElectricLocomotive
}
set
{
if (position >= _places.Count || position < 0)
if (position >= Count || position < 0)
{
return;
}

View File

@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
namespace ElectricLocomotive
{
[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) { }
}
}

View File

@ -0,0 +1,20 @@
{
"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": "Information",
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "log.log",
"rollingInterval": "Day",
"outputTemplate": "[{Timestamp:HH:mm:ss.fff}]{Level:u4}: {Message:lj}{NewLine}{Exception}"
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
"Properties": {
"Application": "Locomotive"
}
}
}