T
Tony Johansson
Hello!
I'm not so sure about what should belong to the PL and what should belong to
the BL.
Can somebody give any comment about this GUI class if anytning should be
moved to the business layed(BL)
which is AnimalManager in my case ?
I have also another component called Utilities where for example
Serialization classes is located.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using AnimalsLibrary.Categories;
using AnimalsLibrary.Housing;
using AnimalsLibrary.Foods;
using AnimalsLibrary.Mammals;
using AnimalsLibrary.Birds;
using AnimalsLibrary.Insects;
using AnimalsLibrary.Marines;
using AnimalsLibrary.Reptiles;
using AnimalsLibrary;
using UtilitiesLibrary;
using System.Text.RegularExpressions;
namespace Test
{
/// <summary>
/// Representerar klassen som är gränsnittet och kommunikationen mot
användaren
/// </summary>
public partial class MainFrameForm : Form
{
const int DisplayHeaderWidth = -2;
const int DisplayWide = 180;
const int DisplayMediumWide = 120;
const string XMLFile = "SerializedData.XML";
const int MaxNrOfTeeth = 50;
const int MaxNrWingSpan = 200;
const int MaxBuzzFrequency = 10000;
const int MaxDiveDepth = 4000;
const int MaxLength = 800;
private string chosenFileName = string.Empty;
private FoodManager foodManager = new FoodManager();
private AnimalManager animalManager = new AnimalManager();
private int[] categoryInfo = new
int[Enum.GetValues(typeof(CategoryType)).Length];
private Animal selectedAnimal;
private string[] title = {"WingSpan:", "BuzzFrequency:",
"NoOfTeeth:","DiveDepth:","Length:"};
/// <summary>
/// C-tor that perform some initialize
/// </summary>
public MainFrameForm()
{
InitializeComponent();
InitializeGUI();
InitListView();
}
/// <summary>
/// Some specific initialize
/// </summary>
private void InitializeGUI()
{
btnAddFood.Enabled = false;
btnDeleteFood.Enabled = false;
ClearExtraCategoryField();
txtName.Text = string.Empty;
txtTeeth.Text = string.Empty;
txtAge.Text = string.Empty;
InitEaterType();
InitGenderType();
InitCategoryType();
InitAnimalType();
InitHousingType();
InitFoodItems();
selectedAnimal = null;
}
private void ClearExtraCategoryField()
{
txtTeeth.Text = string.Empty;
txtWingSpan.Text = string.Empty;
txtBuzzFrequency.Text = string.Empty;
txtDiveDepth.Text = string.Empty;
txtLength.Text = string.Empty;
}
/// <summary>
/// Initialize ListView header
/// </summary>
private void InitListView()
{
listViewAnimals.MultiSelect = false;
listViewAnimals.Scrollable = true;
listViewAnimals.ShowItemToolTips = true;
ColumnHeader colHead;
colHead = new ColumnHeader();
colHead.Width = DisplayHeaderWidth;
colHead.Text = "ID";
this.listViewAnimals.Columns.Add(colHead);
colHead = new ColumnHeader();
colHead.Width = DisplayMediumWide;
colHead.Text = "Name";
this.listViewAnimals.Columns.Add(colHead);
colHead = new ColumnHeader();
colHead.Width = DisplayHeaderWidth;
colHead.Text = "Age";
this.listViewAnimals.Columns.Add(colHead);
colHead = new ColumnHeader();
colHead.Width = DisplayHeaderWidth;
colHead.Text = "Gender";
this.listViewAnimals.Columns.Add(colHead);
colHead = new ColumnHeader();
colHead.Width = DisplayWide;
colHead.Text = "Food items";
this.listViewAnimals.Columns.Add(colHead);
colHead = new ColumnHeader();
colHead.Width = DisplayHeaderWidth;
colHead.Text = "Extra data";
this.listViewAnimals.Columns.Add(colHead);
}
/// <summary>
/// Initialize all the Food and add to the FoodManager class
/// </summary>
private void InitFoodItems()
{
checkedListBox.Items.Clear();
foodManager.Reset();
foodManager.Add(new FoodItem(FoodItemNames.MixedFood.ToString(),
"carrots", "beef", "milk"));
foodManager.Add(new FoodItem(FoodItemNames.Vegeterian.ToString(),
"cauliflower", "celery", "broccoli","fruits",
"leaves", "roots","seeds"));
foodManager.Add(new FoodItem(FoodItemNames.Meat.ToString(),
"chicken","pig", "bird"));
foreach (FoodItem foodItem in foodManager.GetFoodItemList())
{
checkedListBox.Items.Add(foodItem);
}
}
/// <summary>
/// Initialize the eater listBox
/// </summary>
private void InitAnimalType()
{
lstAnimalType.Items.Clear();
}
/// <summary>
/// Initialize the eater listBox
/// </summary>
private void InitEaterType()
{
lstEaterType.Items.Clear();
lstEaterType.Items.AddRange(Enum.GetNames(typeof(EaterType)));
}
/// <summary>
/// Initialize the Gender ListBox
/// </summary>
private void InitGenderType()
{
lstGender.Items.Clear();
lstGender.Items.AddRange(Enum.GetNames(typeof(GenderType)));
}
/// <summary>
/// Initialize the category ListBox
/// </summary>
private void InitCategoryType()
{
lstCategory.Items.Clear();
lstCategory.Items.AddRange(Enum.GetNames(typeof(CategoryType)));
}
/// <summary>
/// Initialize the Housing ListBox
/// </summary>
private void InitHousingType()
{
cboHousing.Items.Clear();
cboHousing.Items.AddRange(Enum.GetNames(typeof(HousingType)));
cboHousing.SelectedIndex = 0;
}
//Update the GUI ListView by fetching the whole animal collection.
//Loop through all animals and update the ListView
private void UpdateGUI()
{
ListViewItem lvi;
ListViewItem.ListViewSubItem lvsi;
listViewAnimals.Items.Clear();
listViewAnimals.BeginUpdate();
//Loop through all the animals
foreach (Animal animal in animalManager.Animals.ToArray())
{
//Update the ID
lvi = new ListViewItem();
lvi.Text = animal.ID;
//Update name
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = animal.Name;
lvi.SubItems.Add(lvsi);
//Update age
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = animal.Age.ToString();
lvi.SubItems.Add(lvsi);
//Update gender
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = animal.Gender.ToString();
lvi.SubItems.Add(lvsi);
//Update FoodItem
lvsi = new ListViewItem.ListViewSubItem();
foreach (FoodItem foodItem in animal.FoodMenyList)
{
lvsi.Text += foodItem + " ";
}
lvi.SubItems.Add(lvsi);
//Update Extra category info
lvsi = new ListViewItem.ListViewSubItem();
int index = (int)(CategoryType)Enum.Parse(typeof(CategoryType),
animal.Category.ToString());
lvsi.Text = title[index] + animal.CategoryInfo.ToString();
lvi.SubItems.Add(lvsi);
listViewAnimals.Items.Add(lvi);
}
listViewAnimals.EndUpdate();
}
//validate the input that the user has provided.
//If all validation is OK return true.
//If some validation is not ok return false
//1. Valid if Age >= 0
//2. Valid if Name != string.Empty
//3. Valid if a selection has been made in CategoryListBox
//4. Valid if a selection has been made in AnimalListBox
//5. Valid if a selection has been made in EaterTypeListBox
//6. Valid if a selection has been made in GenderListBox
private bool ValidateInput()
{
int age;
txtName.Text = txtName.Text.Trim();
txtAge.Text = txtAge.Text.Trim();
//validate age
if (!int.TryParse(txtAge.Text, out age) || age < 0)
{
MessageBox.Show("Age is mandatory and numeric");
return false;
}
//Validate name
if (txtName.Text == string.Empty)
{
MessageBox.Show("Name is mandatory input");
return false;
}
//check that a selection has been made in the Category ListBox
if (lstCategory.SelectedIndex == -1)
{
MessageBox.Show("You must select a category");
return false;
}
//check that a selection has been made in the Animal type ListBox
if (lstAnimalType.SelectedIndex == -1)
{
MessageBox.Show("You must select an animalType");
return false;
}
//check that a selection has been made in the Eater ListBox
if (lstEaterType.SelectedIndex == -1)
{
MessageBox.Show("You must select which type of EaterType this
animal is");
return false;
}
//check that a selection has been made in the Gender ListBox
if (lstGender.SelectedIndex == -1)
{
MessageBox.Show("You must select what gender it is");
return false;
}
//check that at least one FoodItem must have been selected
if (checkedListBox.CheckedItems.Count == 0)
{
MessageBox.Show("You must select at least one food Item that is
suitable for selected animal");
return false;
}
//Alla extra kategori fält optional och kan således lämnas blanka
//Om ett värde anges är formatet for NoOfTeeth mellan >0 &&
<=MaxNrOfTeeth
if (txtTeeth.Enabled == true &&
!CheckExtraCategoryInfo(txtTeeth.Text.Trim(), "NoOfTeeth must be between 1
and " + MaxNrOfTeeth, MaxNrOfTeeth))
return false;
//Alla extra kategori fält optional och kan således lämnas blanka
//Om ett värde anges är formatet för WingSpan mellan >0 &&
<=MaxNrWingSpan
if (txtWingSpan.Enabled == true &&
!CheckExtraCategoryInfo(txtWingSpan.Text.Trim(), "Wingspan must be between 1
and " + MaxNrWingSpan, MaxNrWingSpan))
return false;
//Alla extra kategori fält optional och kan således lämnas blanka
//Om ett värde anges är formatet for BuzzFrequency mellan >0 &&
<=MaxBuzzFrequency
if (txtBuzzFrequency.Enabled == true &&
!CheckExtraCategoryInfo(txtBuzzFrequency.Text.Trim(), "BuzzFrequency must be
between 1 and " + MaxBuzzFrequency, MaxBuzzFrequency))
return false;
//Alla extra kategori fält optional och kan således lämnas blanka
//Om ett värde anges är formatet for DiveDepth mellan >0 &&
<=MaxDiveDepth
if (txtDiveDepth.Enabled == true &&
!CheckExtraCategoryInfo(txtDiveDepth.Text.Trim(), "DiveDepth must be between
1 and " + MaxDiveDepth, MaxDiveDepth))
return false;
//Alla extra kategori fält optional och kan således lämnas blanka
//Om ett värde anges är formatet for Length mellan >0 &&
<=MaxLength
if (txtLength.Enabled == true &&
!CheckExtraCategoryInfo(txtLength.Text.Trim(), "Length must be between 1 and
" + MaxLength, MaxLength))
return false;
return true;
}
/// <summary>
/// This is the method that check if extra CategoryInfo is correct.
/// If text is empty then a warning message is given just to remind
you if you have
/// forgotten to fill in the CategoryInfo
/// If text != "" then it must be > 0
/// </summary>
/// <param name="text"></param>
/// <param name="warningMessage"></param>
/// <param name="errmsg"></param>
/// <returns></returns>
private bool CheckExtraCategoryInfo(string text, string errMsg, int
MaxLimit)
{
int temp = 0;
if (text == string.Empty)
return true;
if (int.TryParse(text, out temp))
{
if (temp <= 0 || temp > MaxLimit)
{
MessageBox.Show(errMsg);
return false;
}
else
{
return true;
}
}
else
{
MessageBox.Show(errMsg);
return false;
}
}
/// <summary>
/// Rensa AnimalType ListBox samt hämta alla djurtyper för vald djur
kategori
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LstCategory_SelectedIndexChanged(object sender, EventArgs
e)
{
lstAnimalType.Items.Clear();
lstAnimalType.Items.AddRange(new
Category().GetMyValues(lstCategory.Text).ToArray());
}
/// <summary>
/// The Add button has been activated the following is done
// 1.Validate the user input. If error give error message and return
// 2.Read from the GUI controller put into local object
// 3.Call the Add method in animalManager along with the animal data
// 4.Update GUI so the new added animal is displayed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnAddAnimal_Click(object sender, EventArgs e)
{
if (!ValidateInput())
return;
CategoryType category =
(CategoryType)Enum.Parse(typeof(CategoryType), lstCategory.Text);
EaterType eater = (EaterType)Enum.Parse(typeof(EaterType),
lstEaterType.Text);
GenderType gender = (GenderType)Enum.Parse(typeof(GenderType),
lstGender.Text);
HousingType housing = (HousingType)Enum.Parse(typeof(HousingType),
cboHousing.Text);
if (txtWingSpan.Text != string.Empty)
categoryInfo[(int)CategoryType.Bird] =
int.Parse(txtWingSpan.Text);
if (txtBuzzFrequency.Text != string.Empty)
categoryInfo[(int)CategoryType.Insect] =
int.Parse(txtBuzzFrequency.Text);
if (txtTeeth.Text != string.Empty)
categoryInfo[(int)CategoryType.Mammal] =
int.Parse(txtTeeth.Text);
if (txtDiveDepth.Text != string.Empty)
categoryInfo[(int)CategoryType.Marine] =
int.Parse(txtDiveDepth.Text);
if (txtLength.Text != string.Empty)
categoryInfo[(int)CategoryType.Reptile] =
int.Parse(txtLength.Text);
List<FoodItem> foodMenuList = new List<FoodItem>();
//Fetch all FoodItem from the CheckedListBox
foreach (FoodItem itemChecked in checkedListBox.CheckedItems)
{
if (!itemChecked.IsGoodFor(eater))
MessageBox.Show(eater + " Tycker inte om: " +
itemChecked.Name + " och får således svälta");
else
foodMenuList.Add(itemChecked);
}
try
{
animalManager.DataSaved = false;
animalManager.Add(category, lstAnimalType.Text, txtName.Text,
double.Parse(txtAge.Text.Trim()), gender,
housing, eater, false, foodMenuList,
categoryInfo);
UpdateGUI();
InitializeGUI();
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// The Change button has been activated do the following.
// 1.Validate the user input. if error give error message and return
// 2.Use fetched animal CurrentAnimalChange
// 3.Read from the GUI controller and put into the fetched animal
object
// 4.Replace the fetched object in the animal collection
// 5.Update GUI so the changed animal object is shown
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnAnimalChange_Click(object sender, EventArgs e)
{
if (selectedAnimal == null)
{
MessageBox.Show("You must click a row in ListView before
Changing");
return;
}
if (txtName.Text.Trim() != selectedAnimal.Name ||
selectedAnimal.Category.ToString() != lstCategory.Text ||
selectedAnimal.GetType().Name != lstAnimalType.Text)
{
MessageBox.Show("Name,Category and AnimalType must be the same
when you are going to change");
return;
}
if (!ValidateInput())
return;
//No need to update Category,AnimalType and Name in the thisAnimal
object because these
//are the same as those in the GUI
selectedAnimal.Housing =
(HousingType)Enum.Parse(typeof(HousingType), cboHousing.Text);
selectedAnimal.Age = double.Parse(txtAge.Text.Trim());
selectedAnimal.Eater = (EaterType)Enum.Parse(typeof(EaterType),
lstEaterType.Text);
selectedAnimal.Gender = (GenderType)Enum.Parse(typeof(GenderType),
lstGender.Text);
if (txtWingSpan.Text != string.Empty)
selectedAnimal.CategoryInfo = int.Parse(txtWingSpan.Text);
if (txtBuzzFrequency.Text != string.Empty)
selectedAnimal.CategoryInfo = int.Parse(txtBuzzFrequency.Text);
if (txtTeeth.Text != string.Empty)
selectedAnimal.CategoryInfo = int.Parse(txtTeeth.Text);
if (txtDiveDepth.Text != string.Empty)
selectedAnimal.CategoryInfo = int.Parse(txtDiveDepth.Text);
if (txtLength.Text != string.Empty)
selectedAnimal.CategoryInfo = int.Parse(txtLength.Text);
List<FoodItem> foodMenuList = new List<FoodItem>();
foreach (FoodItem itemChecked in checkedListBox.CheckedItems)
{
foodMenuList.Add(itemChecked);
}
selectedAnimal.SetFoodItemList = foodMenuList;
try
{
animalManager.DataSaved = false;
animalManager.Replace(selectedAnimal);
UpdateGUI();
InitializeGUI();
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 1.Make sure that you have selected from
ListView(CurrentAnimalChange != null)
// 2.If any of these (Name,category and AnimalType) are changed then
no delete is allowed
// 3.Delate animal from the collection
// 4.Update GUI so that you can see that the removed animal object
is no longer there
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnAnimalDelete_Click(object sender, EventArgs e)
{
if (selectedAnimal == null)
{
MessageBox.Show("You must click a row in ListView before
Deleting");
return;
}
if (txtName.Text.Trim() != selectedAnimal.Name ||
selectedAnimal.Category.ToString() != lstCategory.Text ||
selectedAnimal.GetType().Name != lstAnimalType.Text)
{
MessageBox.Show("Name,Category and AnimalType must be the same
when you are going to delete");
return;
}
string delInfo = "Do you really want to delete " +
lstAnimalType.Text + " " + txtName.Text;
DialogResult response = MessageBox.Show(this, delInfo,
"Continue Delete?", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (response == DialogResult.Yes)
{
if (!animalManager.Delete(selectedAnimal))
{
animalManager.DataSaved = false;
UpdateGUI();
InitializeGUI();
}
else
{
MessageBox.Show("The passed animal was not found in the
collection");
}
}
}
/// <summary>
/// Visa en bild på detta djur typ.
/// Om det inte finns någon bild på detta djur erhålles ett meddelande
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LstAnimalType_SelectedIndexChanged(object sender,
EventArgs e)
{
picAnimal.SizeMode =
System.Windows.Forms.PictureBoxSizeMode.StretchImage;
string imagePath = Path.Combine(Environment.CurrentDirectory,
@"..\..\Pictures\" + lstAnimalType.Text + ".jpg");
if (File.Exists(imagePath))
picAnimal.Image = new Bitmap(imagePath);
else
MessageBox.Show("The image file " + imagePath + " was not
found");
}
/// <summary>
/// Update Animal Specification with data from the Animal object by
using the ID as key
/// </summary>
private void FillAnimalSpecification()
{
txtName.Text = selectedAnimal.Name;
txtAge.Text = selectedAnimal.Age.ToString();
cboHousing.Text = selectedAnimal.Housing.ToString();
lstGender.SelectedIndex =
(int)(GenderType)Enum.Parse(typeof(GenderType),
selectedAnimal.Gender.ToString());
lstEaterType.SelectedIndex =
(int)(EaterType)Enum.Parse(typeof(EaterType),
selectedAnimal.Eater.ToString());
lstCategory.SelectedIndex =
(int)(CategoryType)Enum.Parse(typeof(CategoryType),
selectedAnimal.Category.ToString());
ClearExtraCategoryField();
switch (selectedAnimal.Category)
{
case CategoryType.Bird:
lstAnimalType.SelectedIndex =
(int)(BirdSpices)Enum.Parse(typeof(BirdSpices),
selectedAnimal.GetType().Name);
txtWingSpan.Text = selectedAnimal.CategoryInfo.ToString();
break;
case CategoryType.Insect:
lstAnimalType.SelectedIndex =
(int)(InsectSpecies)Enum.Parse(typeof(InsectSpecies),
selectedAnimal.GetType().Name);
txtBuzzFrequency.Text =
selectedAnimal.CategoryInfo.ToString();
break;
case CategoryType.Mammal:
lstAnimalType.SelectedIndex =
(int)(MammalSpices)Enum.Parse(typeof(MammalSpices),
selectedAnimal.GetType().Name);
txtTeeth.Text = selectedAnimal.CategoryInfo.ToString();
break;
case CategoryType.Marine:
lstAnimalType.SelectedIndex =
(int)(MarineSpices)Enum.Parse(typeof(MarineSpices),
selectedAnimal.GetType().Name);
txtDiveDepth.Text = selectedAnimal.CategoryInfo.ToString();
break;
case CategoryType.Reptile:
lstAnimalType.SelectedIndex =
(int)(ReptileSpecies)Enum.Parse(typeof(ReptileSpecies),
selectedAnimal.GetType().Name);
txtLength.Text = selectedAnimal.CategoryInfo.ToString();
break;
}
//Update the FoodItems in the GUI based on the FoodItem collection
in the animal
for (int i = 0; i < checkedListBox.Items.Count; i++) //loop through
all FoodItems in GUI
{
string foodName = ((FoodItem)checkedListBox.Items).Name;
//Check if this FoodItem exist for this animal. If Yes then
check item
if (selectedAnimal.ExistFoodName(foodName))
checkedListBox.SetItemCheckState(i, CheckState.Checked);
else
checkedListBox.SetItemCheckState(i, CheckState.Unchecked);
}
}
/// <summary>
/// One double click on a row in ListView this evanhandler is called
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listViewAnimals_ItemActivate(object sender, EventArgs e)
{
ListView lw = (ListView)sender;
string id = lw.SelectedItems[0].Text;
selectedAnimal = animalManager.GetAnimalByID(id);
FillAnimalSpecification();
}
private void MenuFileOpen_Click(object sender, EventArgs e)
{
try
{
openFileDialog.AddExtension = true;
openFileDialog.DefaultExt = "Data";
openFileDialog.Title = "Open File";
openFileDialog.ValidateNames = true;
openFileDialog.InitialDirectory =
Directory.GetCurrentDirectory();
openFileDialog.Filter = "Data files (*.data)|*.data|All
Files|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
animalManager.AllAnimals =
BinarySerialization.BinaryFileDeserialize<Animal[]>(openFileDialog.FileName).ToList();
UpdateGUI();
InitializeGUI();
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void MenuFileSave_Click(object sender, EventArgs e)
{
if (animalManager.Animals.Count == 0)
return;
if (chosenFileName == string.Empty)
SaveToFile();
else
BinarySerialization.BinaryFileSerialize(animalManager.Animals.ToArray(),
chosenFileName);
}
private void SaveToFile()
{
try
{
saveFileDialog.AddExtension = true;
saveFileDialog.DefaultExt = "Data";
saveFileDialog.Title = "Save File";
saveFileDialog.ValidateNames = true;
saveFileDialog.OverwritePrompt = true;
saveFileDialog.InitialDirectory =
Directory.GetCurrentDirectory();
saveFileDialog.Filter = "Data files (*.data)|*.data|All
Files|*.*";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
chosenFileName = saveFileDialog.FileName;
BinarySerialization.BinaryFileSerialize(animalManager.Animals.ToArray(),
chosenFileName);
animalManager.DataSaved = true;
}
}
catch (IOException ex)
{
MessageBox.Show("An IOException occured " + ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("An Exception occured " + ex.Message);
}
}
private void MenuFileSaveAs_Click(object sender, EventArgs e)
{
if (animalManager.Animals.Count == 0)
return;
SaveToFile();
}
private void MenuFileNew_Click(object sender, EventArgs e)
{
//Om collection är tom gör ingenting
if (animalManager.Animals.Count == 0)
return;
//On collection inte är sparad skrävs ett svar om du ska göra reset
eller inte
if (!animalManager.DataSaved)
{
DialogResult dr = MessageBox.Show(this, "The Contents has not
been saved. Do you want to reset anyway: ", "Confirmation on resetting",
MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
Reset();
}
else
Reset();
}
private void Reset()
{
animalManager.Reset();
UpdateGUI();
InitializeGUI();
}
private void MenuFileExit_Click(object sender, EventArgs e)
{
if (ClosingCheck())
Application.Exit();
}
private void MainFrameForm_FormClosing(object sender,
FormClosingEventArgs e)
{
if (!ClosingCheck())
e.Cancel = true; //Abort the Exit and keep the application
running
}
private bool ClosingCheck()
{
//On exit check if data has been saved
if (!animalManager.DataSaved)
{
//A confirmation is required from the user because there are
data that has not been saved
DialogResult dr = MessageBox.Show(this, "The Contents has been
changed. Do you want to exit anyway: ", "Confirmation on Exit",
MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.No)
return false; //No keep the application running
}
return true; //Yes you can leave the app becuse all data has been
saved
}
private void MenuFileExportToXML_Click(object sender, EventArgs e)
{
XMLSerialization.XMLSerialize<Animal[]>(XMLFile,
animalManager.Animals.ToArray());
}
}
}
//Tony
I'm not so sure about what should belong to the PL and what should belong to
the BL.
Can somebody give any comment about this GUI class if anytning should be
moved to the business layed(BL)
which is AnimalManager in my case ?
I have also another component called Utilities where for example
Serialization classes is located.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.IO;
using System.Drawing;
using System.Windows.Forms;
using AnimalsLibrary.Categories;
using AnimalsLibrary.Housing;
using AnimalsLibrary.Foods;
using AnimalsLibrary.Mammals;
using AnimalsLibrary.Birds;
using AnimalsLibrary.Insects;
using AnimalsLibrary.Marines;
using AnimalsLibrary.Reptiles;
using AnimalsLibrary;
using UtilitiesLibrary;
using System.Text.RegularExpressions;
namespace Test
{
/// <summary>
/// Representerar klassen som är gränsnittet och kommunikationen mot
användaren
/// </summary>
public partial class MainFrameForm : Form
{
const int DisplayHeaderWidth = -2;
const int DisplayWide = 180;
const int DisplayMediumWide = 120;
const string XMLFile = "SerializedData.XML";
const int MaxNrOfTeeth = 50;
const int MaxNrWingSpan = 200;
const int MaxBuzzFrequency = 10000;
const int MaxDiveDepth = 4000;
const int MaxLength = 800;
private string chosenFileName = string.Empty;
private FoodManager foodManager = new FoodManager();
private AnimalManager animalManager = new AnimalManager();
private int[] categoryInfo = new
int[Enum.GetValues(typeof(CategoryType)).Length];
private Animal selectedAnimal;
private string[] title = {"WingSpan:", "BuzzFrequency:",
"NoOfTeeth:","DiveDepth:","Length:"};
/// <summary>
/// C-tor that perform some initialize
/// </summary>
public MainFrameForm()
{
InitializeComponent();
InitializeGUI();
InitListView();
}
/// <summary>
/// Some specific initialize
/// </summary>
private void InitializeGUI()
{
btnAddFood.Enabled = false;
btnDeleteFood.Enabled = false;
ClearExtraCategoryField();
txtName.Text = string.Empty;
txtTeeth.Text = string.Empty;
txtAge.Text = string.Empty;
InitEaterType();
InitGenderType();
InitCategoryType();
InitAnimalType();
InitHousingType();
InitFoodItems();
selectedAnimal = null;
}
private void ClearExtraCategoryField()
{
txtTeeth.Text = string.Empty;
txtWingSpan.Text = string.Empty;
txtBuzzFrequency.Text = string.Empty;
txtDiveDepth.Text = string.Empty;
txtLength.Text = string.Empty;
}
/// <summary>
/// Initialize ListView header
/// </summary>
private void InitListView()
{
listViewAnimals.MultiSelect = false;
listViewAnimals.Scrollable = true;
listViewAnimals.ShowItemToolTips = true;
ColumnHeader colHead;
colHead = new ColumnHeader();
colHead.Width = DisplayHeaderWidth;
colHead.Text = "ID";
this.listViewAnimals.Columns.Add(colHead);
colHead = new ColumnHeader();
colHead.Width = DisplayMediumWide;
colHead.Text = "Name";
this.listViewAnimals.Columns.Add(colHead);
colHead = new ColumnHeader();
colHead.Width = DisplayHeaderWidth;
colHead.Text = "Age";
this.listViewAnimals.Columns.Add(colHead);
colHead = new ColumnHeader();
colHead.Width = DisplayHeaderWidth;
colHead.Text = "Gender";
this.listViewAnimals.Columns.Add(colHead);
colHead = new ColumnHeader();
colHead.Width = DisplayWide;
colHead.Text = "Food items";
this.listViewAnimals.Columns.Add(colHead);
colHead = new ColumnHeader();
colHead.Width = DisplayHeaderWidth;
colHead.Text = "Extra data";
this.listViewAnimals.Columns.Add(colHead);
}
/// <summary>
/// Initialize all the Food and add to the FoodManager class
/// </summary>
private void InitFoodItems()
{
checkedListBox.Items.Clear();
foodManager.Reset();
foodManager.Add(new FoodItem(FoodItemNames.MixedFood.ToString(),
"carrots", "beef", "milk"));
foodManager.Add(new FoodItem(FoodItemNames.Vegeterian.ToString(),
"cauliflower", "celery", "broccoli","fruits",
"leaves", "roots","seeds"));
foodManager.Add(new FoodItem(FoodItemNames.Meat.ToString(),
"chicken","pig", "bird"));
foreach (FoodItem foodItem in foodManager.GetFoodItemList())
{
checkedListBox.Items.Add(foodItem);
}
}
/// <summary>
/// Initialize the eater listBox
/// </summary>
private void InitAnimalType()
{
lstAnimalType.Items.Clear();
}
/// <summary>
/// Initialize the eater listBox
/// </summary>
private void InitEaterType()
{
lstEaterType.Items.Clear();
lstEaterType.Items.AddRange(Enum.GetNames(typeof(EaterType)));
}
/// <summary>
/// Initialize the Gender ListBox
/// </summary>
private void InitGenderType()
{
lstGender.Items.Clear();
lstGender.Items.AddRange(Enum.GetNames(typeof(GenderType)));
}
/// <summary>
/// Initialize the category ListBox
/// </summary>
private void InitCategoryType()
{
lstCategory.Items.Clear();
lstCategory.Items.AddRange(Enum.GetNames(typeof(CategoryType)));
}
/// <summary>
/// Initialize the Housing ListBox
/// </summary>
private void InitHousingType()
{
cboHousing.Items.Clear();
cboHousing.Items.AddRange(Enum.GetNames(typeof(HousingType)));
cboHousing.SelectedIndex = 0;
}
//Update the GUI ListView by fetching the whole animal collection.
//Loop through all animals and update the ListView
private void UpdateGUI()
{
ListViewItem lvi;
ListViewItem.ListViewSubItem lvsi;
listViewAnimals.Items.Clear();
listViewAnimals.BeginUpdate();
//Loop through all the animals
foreach (Animal animal in animalManager.Animals.ToArray())
{
//Update the ID
lvi = new ListViewItem();
lvi.Text = animal.ID;
//Update name
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = animal.Name;
lvi.SubItems.Add(lvsi);
//Update age
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = animal.Age.ToString();
lvi.SubItems.Add(lvsi);
//Update gender
lvsi = new ListViewItem.ListViewSubItem();
lvsi.Text = animal.Gender.ToString();
lvi.SubItems.Add(lvsi);
//Update FoodItem
lvsi = new ListViewItem.ListViewSubItem();
foreach (FoodItem foodItem in animal.FoodMenyList)
{
lvsi.Text += foodItem + " ";
}
lvi.SubItems.Add(lvsi);
//Update Extra category info
lvsi = new ListViewItem.ListViewSubItem();
int index = (int)(CategoryType)Enum.Parse(typeof(CategoryType),
animal.Category.ToString());
lvsi.Text = title[index] + animal.CategoryInfo.ToString();
lvi.SubItems.Add(lvsi);
listViewAnimals.Items.Add(lvi);
}
listViewAnimals.EndUpdate();
}
//validate the input that the user has provided.
//If all validation is OK return true.
//If some validation is not ok return false
//1. Valid if Age >= 0
//2. Valid if Name != string.Empty
//3. Valid if a selection has been made in CategoryListBox
//4. Valid if a selection has been made in AnimalListBox
//5. Valid if a selection has been made in EaterTypeListBox
//6. Valid if a selection has been made in GenderListBox
private bool ValidateInput()
{
int age;
txtName.Text = txtName.Text.Trim();
txtAge.Text = txtAge.Text.Trim();
//validate age
if (!int.TryParse(txtAge.Text, out age) || age < 0)
{
MessageBox.Show("Age is mandatory and numeric");
return false;
}
//Validate name
if (txtName.Text == string.Empty)
{
MessageBox.Show("Name is mandatory input");
return false;
}
//check that a selection has been made in the Category ListBox
if (lstCategory.SelectedIndex == -1)
{
MessageBox.Show("You must select a category");
return false;
}
//check that a selection has been made in the Animal type ListBox
if (lstAnimalType.SelectedIndex == -1)
{
MessageBox.Show("You must select an animalType");
return false;
}
//check that a selection has been made in the Eater ListBox
if (lstEaterType.SelectedIndex == -1)
{
MessageBox.Show("You must select which type of EaterType this
animal is");
return false;
}
//check that a selection has been made in the Gender ListBox
if (lstGender.SelectedIndex == -1)
{
MessageBox.Show("You must select what gender it is");
return false;
}
//check that at least one FoodItem must have been selected
if (checkedListBox.CheckedItems.Count == 0)
{
MessageBox.Show("You must select at least one food Item that is
suitable for selected animal");
return false;
}
//Alla extra kategori fält optional och kan således lämnas blanka
//Om ett värde anges är formatet for NoOfTeeth mellan >0 &&
<=MaxNrOfTeeth
if (txtTeeth.Enabled == true &&
!CheckExtraCategoryInfo(txtTeeth.Text.Trim(), "NoOfTeeth must be between 1
and " + MaxNrOfTeeth, MaxNrOfTeeth))
return false;
//Alla extra kategori fält optional och kan således lämnas blanka
//Om ett värde anges är formatet för WingSpan mellan >0 &&
<=MaxNrWingSpan
if (txtWingSpan.Enabled == true &&
!CheckExtraCategoryInfo(txtWingSpan.Text.Trim(), "Wingspan must be between 1
and " + MaxNrWingSpan, MaxNrWingSpan))
return false;
//Alla extra kategori fält optional och kan således lämnas blanka
//Om ett värde anges är formatet for BuzzFrequency mellan >0 &&
<=MaxBuzzFrequency
if (txtBuzzFrequency.Enabled == true &&
!CheckExtraCategoryInfo(txtBuzzFrequency.Text.Trim(), "BuzzFrequency must be
between 1 and " + MaxBuzzFrequency, MaxBuzzFrequency))
return false;
//Alla extra kategori fält optional och kan således lämnas blanka
//Om ett värde anges är formatet for DiveDepth mellan >0 &&
<=MaxDiveDepth
if (txtDiveDepth.Enabled == true &&
!CheckExtraCategoryInfo(txtDiveDepth.Text.Trim(), "DiveDepth must be between
1 and " + MaxDiveDepth, MaxDiveDepth))
return false;
//Alla extra kategori fält optional och kan således lämnas blanka
//Om ett värde anges är formatet for Length mellan >0 &&
<=MaxLength
if (txtLength.Enabled == true &&
!CheckExtraCategoryInfo(txtLength.Text.Trim(), "Length must be between 1 and
" + MaxLength, MaxLength))
return false;
return true;
}
/// <summary>
/// This is the method that check if extra CategoryInfo is correct.
/// If text is empty then a warning message is given just to remind
you if you have
/// forgotten to fill in the CategoryInfo
/// If text != "" then it must be > 0
/// </summary>
/// <param name="text"></param>
/// <param name="warningMessage"></param>
/// <param name="errmsg"></param>
/// <returns></returns>
private bool CheckExtraCategoryInfo(string text, string errMsg, int
MaxLimit)
{
int temp = 0;
if (text == string.Empty)
return true;
if (int.TryParse(text, out temp))
{
if (temp <= 0 || temp > MaxLimit)
{
MessageBox.Show(errMsg);
return false;
}
else
{
return true;
}
}
else
{
MessageBox.Show(errMsg);
return false;
}
}
/// <summary>
/// Rensa AnimalType ListBox samt hämta alla djurtyper för vald djur
kategori
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LstCategory_SelectedIndexChanged(object sender, EventArgs
e)
{
lstAnimalType.Items.Clear();
lstAnimalType.Items.AddRange(new
Category().GetMyValues(lstCategory.Text).ToArray());
}
/// <summary>
/// The Add button has been activated the following is done
// 1.Validate the user input. If error give error message and return
// 2.Read from the GUI controller put into local object
// 3.Call the Add method in animalManager along with the animal data
// 4.Update GUI so the new added animal is displayed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnAddAnimal_Click(object sender, EventArgs e)
{
if (!ValidateInput())
return;
CategoryType category =
(CategoryType)Enum.Parse(typeof(CategoryType), lstCategory.Text);
EaterType eater = (EaterType)Enum.Parse(typeof(EaterType),
lstEaterType.Text);
GenderType gender = (GenderType)Enum.Parse(typeof(GenderType),
lstGender.Text);
HousingType housing = (HousingType)Enum.Parse(typeof(HousingType),
cboHousing.Text);
if (txtWingSpan.Text != string.Empty)
categoryInfo[(int)CategoryType.Bird] =
int.Parse(txtWingSpan.Text);
if (txtBuzzFrequency.Text != string.Empty)
categoryInfo[(int)CategoryType.Insect] =
int.Parse(txtBuzzFrequency.Text);
if (txtTeeth.Text != string.Empty)
categoryInfo[(int)CategoryType.Mammal] =
int.Parse(txtTeeth.Text);
if (txtDiveDepth.Text != string.Empty)
categoryInfo[(int)CategoryType.Marine] =
int.Parse(txtDiveDepth.Text);
if (txtLength.Text != string.Empty)
categoryInfo[(int)CategoryType.Reptile] =
int.Parse(txtLength.Text);
List<FoodItem> foodMenuList = new List<FoodItem>();
//Fetch all FoodItem from the CheckedListBox
foreach (FoodItem itemChecked in checkedListBox.CheckedItems)
{
if (!itemChecked.IsGoodFor(eater))
MessageBox.Show(eater + " Tycker inte om: " +
itemChecked.Name + " och får således svälta");
else
foodMenuList.Add(itemChecked);
}
try
{
animalManager.DataSaved = false;
animalManager.Add(category, lstAnimalType.Text, txtName.Text,
double.Parse(txtAge.Text.Trim()), gender,
housing, eater, false, foodMenuList,
categoryInfo);
UpdateGUI();
InitializeGUI();
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// The Change button has been activated do the following.
// 1.Validate the user input. if error give error message and return
// 2.Use fetched animal CurrentAnimalChange
// 3.Read from the GUI controller and put into the fetched animal
object
// 4.Replace the fetched object in the animal collection
// 5.Update GUI so the changed animal object is shown
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnAnimalChange_Click(object sender, EventArgs e)
{
if (selectedAnimal == null)
{
MessageBox.Show("You must click a row in ListView before
Changing");
return;
}
if (txtName.Text.Trim() != selectedAnimal.Name ||
selectedAnimal.Category.ToString() != lstCategory.Text ||
selectedAnimal.GetType().Name != lstAnimalType.Text)
{
MessageBox.Show("Name,Category and AnimalType must be the same
when you are going to change");
return;
}
if (!ValidateInput())
return;
//No need to update Category,AnimalType and Name in the thisAnimal
object because these
//are the same as those in the GUI
selectedAnimal.Housing =
(HousingType)Enum.Parse(typeof(HousingType), cboHousing.Text);
selectedAnimal.Age = double.Parse(txtAge.Text.Trim());
selectedAnimal.Eater = (EaterType)Enum.Parse(typeof(EaterType),
lstEaterType.Text);
selectedAnimal.Gender = (GenderType)Enum.Parse(typeof(GenderType),
lstGender.Text);
if (txtWingSpan.Text != string.Empty)
selectedAnimal.CategoryInfo = int.Parse(txtWingSpan.Text);
if (txtBuzzFrequency.Text != string.Empty)
selectedAnimal.CategoryInfo = int.Parse(txtBuzzFrequency.Text);
if (txtTeeth.Text != string.Empty)
selectedAnimal.CategoryInfo = int.Parse(txtTeeth.Text);
if (txtDiveDepth.Text != string.Empty)
selectedAnimal.CategoryInfo = int.Parse(txtDiveDepth.Text);
if (txtLength.Text != string.Empty)
selectedAnimal.CategoryInfo = int.Parse(txtLength.Text);
List<FoodItem> foodMenuList = new List<FoodItem>();
foreach (FoodItem itemChecked in checkedListBox.CheckedItems)
{
foodMenuList.Add(itemChecked);
}
selectedAnimal.SetFoodItemList = foodMenuList;
try
{
animalManager.DataSaved = false;
animalManager.Replace(selectedAnimal);
UpdateGUI();
InitializeGUI();
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 1.Make sure that you have selected from
ListView(CurrentAnimalChange != null)
// 2.If any of these (Name,category and AnimalType) are changed then
no delete is allowed
// 3.Delate animal from the collection
// 4.Update GUI so that you can see that the removed animal object
is no longer there
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnAnimalDelete_Click(object sender, EventArgs e)
{
if (selectedAnimal == null)
{
MessageBox.Show("You must click a row in ListView before
Deleting");
return;
}
if (txtName.Text.Trim() != selectedAnimal.Name ||
selectedAnimal.Category.ToString() != lstCategory.Text ||
selectedAnimal.GetType().Name != lstAnimalType.Text)
{
MessageBox.Show("Name,Category and AnimalType must be the same
when you are going to delete");
return;
}
string delInfo = "Do you really want to delete " +
lstAnimalType.Text + " " + txtName.Text;
DialogResult response = MessageBox.Show(this, delInfo,
"Continue Delete?", MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (response == DialogResult.Yes)
{
if (!animalManager.Delete(selectedAnimal))
{
animalManager.DataSaved = false;
UpdateGUI();
InitializeGUI();
}
else
{
MessageBox.Show("The passed animal was not found in the
collection");
}
}
}
/// <summary>
/// Visa en bild på detta djur typ.
/// Om det inte finns någon bild på detta djur erhålles ett meddelande
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void LstAnimalType_SelectedIndexChanged(object sender,
EventArgs e)
{
picAnimal.SizeMode =
System.Windows.Forms.PictureBoxSizeMode.StretchImage;
string imagePath = Path.Combine(Environment.CurrentDirectory,
@"..\..\Pictures\" + lstAnimalType.Text + ".jpg");
if (File.Exists(imagePath))
picAnimal.Image = new Bitmap(imagePath);
else
MessageBox.Show("The image file " + imagePath + " was not
found");
}
/// <summary>
/// Update Animal Specification with data from the Animal object by
using the ID as key
/// </summary>
private void FillAnimalSpecification()
{
txtName.Text = selectedAnimal.Name;
txtAge.Text = selectedAnimal.Age.ToString();
cboHousing.Text = selectedAnimal.Housing.ToString();
lstGender.SelectedIndex =
(int)(GenderType)Enum.Parse(typeof(GenderType),
selectedAnimal.Gender.ToString());
lstEaterType.SelectedIndex =
(int)(EaterType)Enum.Parse(typeof(EaterType),
selectedAnimal.Eater.ToString());
lstCategory.SelectedIndex =
(int)(CategoryType)Enum.Parse(typeof(CategoryType),
selectedAnimal.Category.ToString());
ClearExtraCategoryField();
switch (selectedAnimal.Category)
{
case CategoryType.Bird:
lstAnimalType.SelectedIndex =
(int)(BirdSpices)Enum.Parse(typeof(BirdSpices),
selectedAnimal.GetType().Name);
txtWingSpan.Text = selectedAnimal.CategoryInfo.ToString();
break;
case CategoryType.Insect:
lstAnimalType.SelectedIndex =
(int)(InsectSpecies)Enum.Parse(typeof(InsectSpecies),
selectedAnimal.GetType().Name);
txtBuzzFrequency.Text =
selectedAnimal.CategoryInfo.ToString();
break;
case CategoryType.Mammal:
lstAnimalType.SelectedIndex =
(int)(MammalSpices)Enum.Parse(typeof(MammalSpices),
selectedAnimal.GetType().Name);
txtTeeth.Text = selectedAnimal.CategoryInfo.ToString();
break;
case CategoryType.Marine:
lstAnimalType.SelectedIndex =
(int)(MarineSpices)Enum.Parse(typeof(MarineSpices),
selectedAnimal.GetType().Name);
txtDiveDepth.Text = selectedAnimal.CategoryInfo.ToString();
break;
case CategoryType.Reptile:
lstAnimalType.SelectedIndex =
(int)(ReptileSpecies)Enum.Parse(typeof(ReptileSpecies),
selectedAnimal.GetType().Name);
txtLength.Text = selectedAnimal.CategoryInfo.ToString();
break;
}
//Update the FoodItems in the GUI based on the FoodItem collection
in the animal
for (int i = 0; i < checkedListBox.Items.Count; i++) //loop through
all FoodItems in GUI
{
string foodName = ((FoodItem)checkedListBox.Items).Name;
//Check if this FoodItem exist for this animal. If Yes then
check item
if (selectedAnimal.ExistFoodName(foodName))
checkedListBox.SetItemCheckState(i, CheckState.Checked);
else
checkedListBox.SetItemCheckState(i, CheckState.Unchecked);
}
}
/// <summary>
/// One double click on a row in ListView this evanhandler is called
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void listViewAnimals_ItemActivate(object sender, EventArgs e)
{
ListView lw = (ListView)sender;
string id = lw.SelectedItems[0].Text;
selectedAnimal = animalManager.GetAnimalByID(id);
FillAnimalSpecification();
}
private void MenuFileOpen_Click(object sender, EventArgs e)
{
try
{
openFileDialog.AddExtension = true;
openFileDialog.DefaultExt = "Data";
openFileDialog.Title = "Open File";
openFileDialog.ValidateNames = true;
openFileDialog.InitialDirectory =
Directory.GetCurrentDirectory();
openFileDialog.Filter = "Data files (*.data)|*.data|All
Files|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
animalManager.AllAnimals =
BinarySerialization.BinaryFileDeserialize<Animal[]>(openFileDialog.FileName).ToList();
UpdateGUI();
InitializeGUI();
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void MenuFileSave_Click(object sender, EventArgs e)
{
if (animalManager.Animals.Count == 0)
return;
if (chosenFileName == string.Empty)
SaveToFile();
else
BinarySerialization.BinaryFileSerialize(animalManager.Animals.ToArray(),
chosenFileName);
}
private void SaveToFile()
{
try
{
saveFileDialog.AddExtension = true;
saveFileDialog.DefaultExt = "Data";
saveFileDialog.Title = "Save File";
saveFileDialog.ValidateNames = true;
saveFileDialog.OverwritePrompt = true;
saveFileDialog.InitialDirectory =
Directory.GetCurrentDirectory();
saveFileDialog.Filter = "Data files (*.data)|*.data|All
Files|*.*";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
chosenFileName = saveFileDialog.FileName;
BinarySerialization.BinaryFileSerialize(animalManager.Animals.ToArray(),
chosenFileName);
animalManager.DataSaved = true;
}
}
catch (IOException ex)
{
MessageBox.Show("An IOException occured " + ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("An Exception occured " + ex.Message);
}
}
private void MenuFileSaveAs_Click(object sender, EventArgs e)
{
if (animalManager.Animals.Count == 0)
return;
SaveToFile();
}
private void MenuFileNew_Click(object sender, EventArgs e)
{
//Om collection är tom gör ingenting
if (animalManager.Animals.Count == 0)
return;
//On collection inte är sparad skrävs ett svar om du ska göra reset
eller inte
if (!animalManager.DataSaved)
{
DialogResult dr = MessageBox.Show(this, "The Contents has not
been saved. Do you want to reset anyway: ", "Confirmation on resetting",
MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
Reset();
}
else
Reset();
}
private void Reset()
{
animalManager.Reset();
UpdateGUI();
InitializeGUI();
}
private void MenuFileExit_Click(object sender, EventArgs e)
{
if (ClosingCheck())
Application.Exit();
}
private void MainFrameForm_FormClosing(object sender,
FormClosingEventArgs e)
{
if (!ClosingCheck())
e.Cancel = true; //Abort the Exit and keep the application
running
}
private bool ClosingCheck()
{
//On exit check if data has been saved
if (!animalManager.DataSaved)
{
//A confirmation is required from the user because there are
data that has not been saved
DialogResult dr = MessageBox.Show(this, "The Contents has been
changed. Do you want to exit anyway: ", "Confirmation on Exit",
MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.No)
return false; //No keep the application running
}
return true; //Yes you can leave the app becuse all data has been
saved
}
private void MenuFileExportToXML_Click(object sender, EventArgs e)
{
XMLSerialization.XMLSerialize<Animal[]>(XMLFile,
animalManager.Animals.ToArray());
}
}
}
//Tony