Сделанная 7 лаба

This commit is contained in:
Табеев Александр 2023-12-19 17:48:36 +04:00
parent d24e418a8a
commit e2c34a5257
11 changed files with 216 additions and 54 deletions

View File

@ -8,6 +8,38 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Diagnostics" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.FileProviders.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="8.0.0" />
<PackageReference Include="NLog" Version="5.2.7" />
<PackageReference Include="NLog.Config" Version="4.7.15" />
<PackageReference Include="NLog.Extensions.Logging" Version="5.3.7" />
<PackageReference Include="NLog.Schema" Version="5.2.7" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.3.7" />
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Serilog.Formatting.Compact" Version="2.0.0" />
<PackageReference Include="Serilog.Settings.AppSettings" Version="2.2.2" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.Debug" Version="2.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\Resources.Designer.cs">
<DesignTime>True</DesignTime>
@ -23,4 +55,10 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Update="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>

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

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 AntiAircraftGun.Exceptions
{
[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

@ -53,9 +53,9 @@
//
// pictureBoxCollection
//
this.pictureBoxCollection.Location = new System.Drawing.Point(12, 89);
this.pictureBoxCollection.Location = new System.Drawing.Point(12, 27);
this.pictureBoxCollection.Name = "pictureBoxCollection";
this.pictureBoxCollection.Size = new System.Drawing.Size(634, 354);
this.pictureBoxCollection.Size = new System.Drawing.Size(797, 517);
this.pictureBoxCollection.TabIndex = 0;
this.pictureBoxCollection.TabStop = false;
//
@ -66,7 +66,7 @@
this.groupBox1.Controls.Add(this.ButtonAddAircraftGun);
this.groupBox1.Controls.Add(this.ButtonRemoveAircraftGun);
this.groupBox1.Controls.Add(this.ButtonRefreshCollection);
this.groupBox1.Location = new System.Drawing.Point(658, 6);
this.groupBox1.Location = new System.Drawing.Point(815, 37);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(236, 437);
this.groupBox1.TabIndex = 1;
@ -79,7 +79,7 @@
this.groupBox2.Controls.Add(this.textBoxStorageName);
this.groupBox2.Controls.Add(this.ButtonAddObject);
this.groupBox2.Controls.Add(this.ButtonDelObject);
this.groupBox2.Location = new System.Drawing.Point(19, 28);
this.groupBox2.Location = new System.Drawing.Point(21, 22);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(209, 222);
this.groupBox2.TabIndex = 6;
@ -166,7 +166,7 @@
this.файлToolStripMenuItem});
this.menuStrip.Location = new System.Drawing.Point(0, 0);
this.menuStrip.Name = "menuStrip";
this.menuStrip.Size = new System.Drawing.Size(906, 24);
this.menuStrip.Size = new System.Drawing.Size(1063, 24);
this.menuStrip.TabIndex = 2;
this.menuStrip.Text = "menuStrip1";
//
@ -182,14 +182,14 @@
// SaveToolStripMenuItem
//
this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem";
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(180, 22);
this.SaveToolStripMenuItem.Size = new System.Drawing.Size(141, 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.Size = new System.Drawing.Size(141, 22);
this.LoadToolStripMenuItem.Text = "Загрузка";
this.LoadToolStripMenuItem.Click += new System.EventHandler(this.LoadToolStripMenuItem_Click);
//
@ -206,7 +206,7 @@
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(906, 450);
this.ClientSize = new System.Drawing.Size(1063, 556);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.pictureBoxCollection);
this.Controls.Add(this.menuStrip);

View File

@ -1,4 +1,5 @@
using AntiAircraftGun.DrawningObjects;
using AntiAircraftGun.Exceptions;
using AntiAircraftGun.Generics;
using AntiAircraftGun.MovementStrategy;
using System;
@ -10,17 +11,22 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Extensions.Logging;
using System.Xml.Linq;
namespace AntiAircraftGun
{
public partial class FormAircraftGunCollection : Form
{
private readonly AntiAircraftGunsGenericStorage _storage;
//private readonly AntiAircraftGunsGenericCollection<DrawningAircraftGun, DrawningObjectAircraftGun> _aircraftguns;
public FormAircraftGunCollection()
private readonly ILogger _logger;
public FormAircraftGunCollection(ILogger<FormAircraftGunCollection> logger)
{
InitializeComponent();
_storage = new AntiAircraftGunsGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
_logger = logger;
}
// Заполнение listBoxObjects
private void ReloadObjects()
@ -65,6 +71,7 @@ namespace AntiAircraftGun
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? String.Empty];
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (obj == null)
{
return;
@ -74,15 +81,26 @@ namespace AntiAircraftGun
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (obj - pos != null)
try
{
MessageBox.Show("Объект удалён");
pictureBoxCollection.Image = obj.ShowAntiAircraftGuns();
if (obj - pos != null)
{
MessageBox.Show("Объект удалён");
pictureBoxCollection.Image = obj.ShowAntiAircraftGuns();
_logger.LogInformation($"Из набора {name} удален объект");
}
else
{
MessageBox.Show("Не удалось удалить объект");
_logger.LogWarning("Не удалось удалить объект");
}
}
else
catch(AircraftGunNotFoundException ex)
{
MessageBox.Show("Не удалось удалить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message}. Не удалось удалить объект");
}
}
private void AddAircraftGun(DrawningAircraftGun aircraftGun)
@ -94,18 +112,29 @@ namespace AntiAircraftGun
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (obj == null)
{
return;
}
if (obj + aircraftGun)
try
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowAntiAircraftGuns();
if (obj + aircraftGun)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = obj.ShowAntiAircraftGuns();
_logger.LogInformation($"В набор {name} добавлен объект");
}
else
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning("Не удалось добавить объект");
}
}
else
catch(StorageOverflowException ex)
{
MessageBox.Show("Не удалось добавить объект");
MessageBox.Show(ex.Message);
_logger.LogWarning($"{ex.Message}. Не удалось добавить объект");
}
}
// Добавление объекта в набор
@ -130,13 +159,16 @@ namespace AntiAircraftGun
{
if (listBoxStorages.SelectedIndex == -1)
{
_logger.LogWarning($"Удаление невыбранного набора");
return;
}
if (MessageBox.Show($"удалить объект {listBoxStorages.SelectedItem}?", "удаление", MessageBoxButtons.YesNo,
string name = listBoxStorages.SelectedItem.ToString() ?? string.Empty;
if (MessageBox.Show($"удалить объект {name}?", "удаление", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
_logger.LogInformation($"Удален набор: {name}");
}
}
@ -146,10 +178,12 @@ namespace AntiAircraftGun
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполены", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка. Не все данные заполнены");
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
_logger.LogInformation($"Добавлен набор: {textBoxStorageName.Text}");
}
// Выбор набора
private void listBoxStorages_SelectedIndexChanged(object sender, EventArgs e)
@ -162,13 +196,15 @@ namespace AntiAircraftGun
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.SaveData(saveFileDialog.FileName))
try
{
_storage.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Сохранение");
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
catch (Exception ex) {
MessageBox.Show($"Не сохранилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка сохранения");
}
}
}
@ -178,15 +214,17 @@ namespace AntiAircraftGun
{
if(openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storage.LoadData(openFileDialog.FileName))
try
{
_storage.LoadData(openFileDialog.FileName);
ReloadObjects();
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
_logger.LogInformation("Загрузка");
}
else
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex) {
MessageBox.Show($"Не загрузилось: {ex.Message}", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogWarning("Ошибка загрузки");
}
}
}
}

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>272, 18</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

@ -44,15 +44,11 @@ namespace AntiAircraftGun.Generics
}
// Перегрузка оператора вычитания
public static bool operator -(AntiAircraftGunsGenericCollection<T, U> collect, int pos)
public static T? operator -(AntiAircraftGunsGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection[pos];
if (obj == null)
{
return false;
}
collect._collection.Remove(pos);
return true;
return obj;
}
// Получение объекта IMoveableObject

View File

@ -86,7 +86,7 @@ namespace AntiAircraftGun.Generics
}
if (data.Length == 0)
{
return false;
throw new Exception("Невалидная операция, нет данных для сохранения");
}
using StreamWriter fs = new StreamWriter(filename);
@ -100,24 +100,23 @@ namespace AntiAircraftGun.Generics
{
if (!File.Exists(filename))
{
return false;
throw new FileNotFoundException("Файл не найден");
}
using (StreamReader fs = new StreamReader(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
throw new NullReferenceException("Нет данных для загрузки");
}
if (!str.StartsWith("AircraftStorage"))
{
return false;
throw new FormatException("Неверный формат данных");
}
_aircraftgunStorages.Clear();
while ((str = fs.ReadLine()) != null)
{
if (str.Length == 0)
{
return false;
}
string[] record = str.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 2)
{
@ -133,7 +132,7 @@ namespace AntiAircraftGun.Generics
{
if (!(collection + aircraftgun))
{
return false;
throw new ApplicationException("Ошибка добавления в коллекцию");
}
}
}

View File

@ -6,6 +6,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AntiAircraftGun.Exceptions;
namespace AntiAircraftGun.Generics
{
@ -39,13 +40,13 @@ namespace AntiAircraftGun.Generics
{
if (position < 0 || position >= _maxCount)
{
return false;
throw new AircraftGunNotFoundException(position);
}
if (Count >= _maxCount)
{
return false;
throw new StorageOverflowException(_maxCount);
}
_places.Insert(0, antiaircraftgun);
_places.Insert(position, antiaircraftgun);
return true;
}
@ -56,11 +57,11 @@ namespace AntiAircraftGun.Generics
{
return false;
}
if (position >= Count)
if (_places[position] == null)
{
return false;
throw new AircraftGunNotFoundException(position);
}
_places.RemoveAt(position);
_places[position] = null;
return true;
}
@ -69,7 +70,7 @@ namespace AntiAircraftGun.Generics
{
get
{
if (position < 0 || position >= _maxCount)
if (position < 0 || position >= Count)
{
return null;
}
@ -77,7 +78,7 @@ namespace AntiAircraftGun.Generics
}
set
{
if (position < 0 || position >= _maxCount)
if (position < 0 || position >= Count)
{
return;
}

View File

@ -1,3 +1,11 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;
using System;
using System.IO;
using System.Windows.Forms;
namespace AntiAircraftGun
{
internal static class Program
@ -11,7 +19,28 @@ namespace AntiAircraftGun
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FormAircraftGunCollection());
var services = new ServiceCollection();
ConfigureServices(services);
using (ServiceProvider serviceProvider = services.BuildServiceProvider())
{
Application.Run(serviceProvider.GetRequiredService<FormAircraftGunCollection>());
}
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton<FormAircraftGunCollection>().AddLogging(option =>
{
string[] path = Directory.GetCurrentDirectory().Split("\\");
string appPath = "";
for(int i = 0; i < path.Length - 3; i++)
{
appPath += path[i] + "\\";
}
var configuration = new ConfigurationBuilder().AddJsonFile($"{appPath}appsettings.json").Build();
var logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
option.SetMinimumLevel(LogLevel.Information);
option.AddSerilog(logger);
});
}
}
}

View File

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