Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Laba7 Sokolova #8

Open
wants to merge 3 commits into
base: laba6
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions App.config
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>

<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="logfile" xsi:type="File" fileName="D://file.txt" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
</nlog>
</configuration>
8 changes: 6 additions & 2 deletions Dock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public Dock(int sizes, int pictureWidth, int pictureHeight)
{
if (p._places.Count == p._maxCount)
{
return -1;
throw new DockOverflowException();
}
for (int i = 0; i < p._maxCount; i++)
{
Expand Down Expand Up @@ -94,7 +94,7 @@ public Dock(int sizes, int pictureWidth, int pictureHeight)
p._places.Remove(index);
return car;
}
return null;
throw new DockNotFoundException(index);
}
/// <summary>
/// Метод проверки заполнености парковочного места (ячейки массива)
Expand Down Expand Up @@ -160,6 +160,10 @@ public T this[int ind]
_places[ind].SetPosition(5 + ind / 5 * _placeSizeWidth + 5, ind % 5 *
_placeSizeHeight + 57, PictureWidth, PictureHeight);
}
else
{
throw new DockOccupiedPlaceException(ind);
}
}
}
}
Expand Down
17 changes: 17 additions & 0 deletions DockNotFoundException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsCars
{
/// <summary>
/// Класс-ошибка "Если не найден корабль по определенному месту"
/// </summary>
class DockNotFoundException : Exception
{
public DockNotFoundException(int i) : base("Не найден корабль по месту " + i)
{ }
}
}
17 changes: 17 additions & 0 deletions DockOccupiedPlaceException .cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsCars
{
/// <summary>
/// Класс-ошибка "Если место, на которое хотим поставить корабль, уже занято"
/// </summary>
class DockOccupiedPlaceException : Exception
{
public DockOccupiedPlaceException(int i) : base("На месте " + i + " уже стоит корабль")
{ }
}
}
17 changes: 17 additions & 0 deletions DockOverflowException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsCars
{
/// <summary>
/// Класс-ошибка "Если в доке уже заняты все места"
/// </summary>
class DockOverflowException : Exception
{
public DockOverflowException() : base("В доке нет свободных мест")
{ }
}
}
1 change: 0 additions & 1 deletion FormDock.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

87 changes: 60 additions & 27 deletions FormDock.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using NLog;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
Expand Down Expand Up @@ -26,12 +27,17 @@ public partial class FormDock : Form
/// Количество уровней-парковок
/// </summary>
private const int countLevel = 5;


/// <summary>
/// Логгер
/// </summary>
private Logger logger;

public FormDock()
{
InitializeComponent();


logger = LogManager.GetCurrentClassLogger();
dock = new MultiLevelDock(countLevel, pictureBoxDock.Width,
pictureBoxDock.Height);
//заполнение listBox
Expand Down Expand Up @@ -68,25 +74,35 @@ private void buttonTakeShip_Click(object sender, EventArgs e)
{
if (maskedTextBox.Text != "")
{
var ship = dock[listBoxLevels.SelectedIndex] -
Convert.ToInt32(maskedTextBox.Text);
if (ship != null)
try
{
var ship = dock[listBoxLevels.SelectedIndex] -
Convert.ToInt32(maskedTextBox.Text);

Bitmap bmp = new Bitmap(pictureBoxTakeShip.Width,
pictureBoxTakeShip.Height);
Graphics gr = Graphics.FromImage(bmp);
ship.SetPosition(15, 75, pictureBoxTakeShip.Width,
pictureBoxTakeShip.Height);
ship.DrawShip(gr);
pictureBoxTakeShip.Image = bmp;


Draw();
}
else
catch (DockNotFoundException ex)
{
MessageBox.Show(ex.Message, "Не найдено", MessageBoxButtons.OK,
MessageBoxIcon.Error);
Bitmap bmp = new Bitmap(pictureBoxTakeShip.Width,
pictureBoxTakeShip.Height);
pictureBoxTakeShip.Height);
pictureBoxTakeShip.Image = bmp;
}
Draw();
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Неизвестная ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
Expand Down Expand Up @@ -118,14 +134,23 @@ private void AddShip(IShip ship)
{
if (ship != null && listBoxLevels.SelectedIndex > -1)
{
int place = dock[listBoxLevels.SelectedIndex] + ship;
if (place > -1)
try
{
int place = dock[listBoxLevels.SelectedIndex] + ship;
logger.Info("Добавлен корабль " + ship.ToString() + " на место " + place);

Draw();

}
catch (DockOverflowException ex)
{
MessageBox.Show(ex.Message, "Переполнение", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
catch (Exception ex)
{
MessageBox.Show("Корабль не удалось пришвартовать");
MessageBox.Show(ex.Message, "Неизвестная ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
Expand All @@ -136,20 +161,22 @@ private void AddShip(IShip ship)
/// <param name="e"></param>
private void сохранитьToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (dock.SaveData(saveFileDialog.FileName))
try
{
dock.SaveData(saveFileDialog.FileName);
MessageBox.Show("Сохранение прошло успешно", "Результат",
MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBoxButtons.OK, MessageBoxIcon.Information);
logger.Info("Сохранено в файл " + saveFileDialog.FileName);
}
else
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Error);

MessageBox.Show(ex.Message + ex.StackTrace, "Неизвестная ошибка при сохранении",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

}

/// <summary>
Expand All @@ -159,21 +186,27 @@ private void сохранитьToolStripMenuItem_Click(object sender, EventArgs
/// <param name="e"></param>
private void загрузитьToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (dock.LoadData(openFileDialog.FileName))
try
{
dock.LoadData(openFileDialog.FileName);
MessageBox.Show("Загрузили", "Результат", MessageBoxButtons.OK,
MessageBoxIcon.Information);
MessageBoxIcon.Information);
logger.Info("Загружено из файла " + openFileDialog.FileName);
}
else
catch (DockOccupiedPlaceException ex)
{
MessageBox.Show("Не загрузили", "Результат", MessageBoxButtons.OK,
MessageBox.Show(ex.Message, "Занятое место", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Неизвестная ошибка при загрузке",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Draw();
}

}
}
}
}
18 changes: 9 additions & 9 deletions MultiLevelDock.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public Dock<IShip> this[int ind]
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns></returns>
public bool SaveData(string filename)
public void SaveData(string filename)
{
if (File.Exists(filename))
{
Expand All @@ -82,10 +82,11 @@ public bool SaveData(string filename)
WriteToFile("Level" + Environment.NewLine, fs);
for (int i = 0; i < countPlaces; i++)
{
var ship = level[i];
if (ship != null)
try
{
//если место не пустое
var ship = level[i];
if (ship == null)
continue;
//Записываем тип корабля
if (ship.GetType().Name == "Ship")
{
Expand All @@ -98,11 +99,11 @@ public bool SaveData(string filename)
//Записываемые параметры
WriteToFile(ship + Environment.NewLine, fs);
}
finally { }
}
}
}
}
return true;
}
/// <summary>
/// Метод записи информации в файл
Expand All @@ -119,11 +120,11 @@ private void WriteToFile(string text, FileStream stream)
/// </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();
}
string bufferTextFromFile = "";
using (FileStream fs = new FileStream(filename, FileMode.Open))
Expand Down Expand Up @@ -153,7 +154,7 @@ public bool LoadData(string filename)
else
{
//если нет такой записи, то это не те данные
return false;
throw new Exception("Неверный формат файла");
}
int counter = -1;
IShip ship = null;
Expand Down Expand Up @@ -182,7 +183,6 @@ public bool LoadData(string filename)
}
parkingStages[counter][Convert.ToInt32(strs[i].Split(':')[0])] = ship;
}
return true;
}
}
}
Expand Down
12 changes: 12 additions & 0 deletions WindowsFormsShip.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,16 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>packages\NLog.4.5.11\lib\net45\NLog.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Transactions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
Expand All @@ -48,6 +56,9 @@
<Compile Include="Boat.cs" />
<Compile Include="Direction.cs" />
<Compile Include="Dock.cs" />
<Compile Include="DockNotFoundException.cs" />
<Compile Include="DockOccupiedPlaceException .cs" />
<Compile Include="DockOverflowException.cs" />
<Compile Include="FormDock.cs">
<SubType>Form</SubType>
</Compile>
Expand Down Expand Up @@ -91,6 +102,7 @@
<DependentUpon>Resources.resx</DependentUpon>
<DesignTime>True</DesignTime>
</Compile>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
Expand Down
4 changes: 4 additions & 0 deletions packages.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NLog" version="4.5.11" targetFramework="net461" />
</packages>