[Serializable]

I am trying to create my project to [Serializable] but I dont know if I am doing the right thing.

on all my classes I have added above my class.....  [Serializable]

then in my form I am trying to save it. See code below.

If I choose from my menu Save it jumps to.....saveToolStripMenuItem
here I send  my animalManager object into binaryFileSerialize
but here it throws a catch:

System.Runtime.Serialization.SerializationException was unhandled
  Message="Type 'Animals.AnimalManager' in Assembly 'Animals, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable."
  Source="mscorlib"
  StackTrace:
       at System.Runtime.Serialization.FormatterServices.InternalGetSerializableMembers(RuntimeType type)
       at System.Runtime.Serialization.FormatterServices.GetSerializableMembers(Type type, StreamingContext context)
       at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitMemberInfo()
       at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.InitSerialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
       at System.Runtime.Serialization.Formatters.Binary.WriteObjectInfo.Serialize(Object obj, ISurrogateSelector surrogateSelector, StreamingContext context, SerObjectInfoInit serObjectInfoInit, IFormatterConverter converter, ObjectWriter objectWriter)
       at System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize(Object graph, Header[] inHeaders, __BinaryWriter serWriter, Boolean fCheck)
       at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph, Header[] headers, Boolean fCheck)
       at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize(Stream serializationStream, Object graph).............
     
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Animals;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
 
 
namespace Modul1_Malmoe
{
    [Serializable]
    public partial class Animal : Form
    {       
       AnimalManager animalManager = new AnimalManager();
 
 
        /// <summary>
        /// 
        /// </summary>
        public Animal()
        {
            InitializeComponent();
            
        }
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            housingCombobox.DataSource = Enum.GetValues(typeof(HousingType));
            sortComboBox.DataSource = Enum.GetValues(typeof(MeatDjur));
            nrOfLegsTextBox.Text = "4";
            nrOfItems.Text = Convert.ToString(animalManager.Counter);
            changeButton.Enabled = false;
            deleteButton.Enabled = false;
        }
 
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Add_Click(object sender, EventArgs e)
        {
            if (nickNameTextBox.Text.Trim() == String.Empty)
            {
                MessageBox.Show("Please write something in Nick Name before adding", "Information");
            }
 
            else
            {
                string text = sortComboBox.SelectedItem.ToString();
                animalManager.AddNewAnimal(text, nickNameTextBox.Text, (HousingType)housingCombobox.SelectedIndex);
                nrOfItems.Text = Convert.ToString(animalManager.Counter);
                Updater();
            }
        }
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sortComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (sortComboBox.SelectedItem.ToString() == "Dog" ||
                sortComboBox.SelectedItem.ToString() == "Giraffe" ||
                sortComboBox.SelectedItem.ToString() == "Wolf" ||
                sortComboBox.SelectedItem.ToString() == "Horse")
                nrOfLegsTextBox.Text = "4";
 
            else if (sortComboBox.SelectedItem.ToString() == "Duck")
                nrOfLegsTextBox.Text = "2";
        }
 
 
        /// <summary>
        /// 
        /// </summary>
        private void Updater()
        {
            AnimalDataGridView.DataSource = null;
            AnimalDataGridView.AutoGenerateColumns = true;
            AnimalDataGridView.DataSource = animalManager.AnimalList;
            nickNameTextBox.Text = "";
            nrOfItems.Text = Convert.ToString(animalManager.Counter);            
            if (animalManager.AnimalList.Count > 0)
            {
                deleteButton.Enabled = true;
                addButton.Enabled = true;
            }
 
            else
            {
                deleteButton.Enabled = false;
                changeButton.Enabled = false;
                addButton.Enabled = true;
            }
         }
 
 
 
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void selectedRowsButton_Click(object sender, DataGridViewCellEventArgs e)
        {
            if (MessageBox.Show("Fill in the correct values and press change to save it", "Change", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                addButton.Enabled = false;
                Int32 selected = AnimalDataGridView.CurrentRow.Index;
                nickNameTextBox.Text = animalManager.AnimalList[selected].Name;
                nrOfLegsTextBox.Text = Convert.ToString(animalManager.AnimalList[selected].NumberOfLegs);
                
                int nFoundEl = -1;
                for (int i = 0; i < housingCombobox.Items.Count; i++) 
                {
                    if (housingCombobox.Items[i].ToString().Equals(animalManager.AnimalList[selected].Housing.ToString())) 
                        nFoundEl = i; 
 
                    if (nFoundEl >= 0) 
                    { 
                        housingCombobox.SelectedIndex = nFoundEl; 
                    } //end if
                } //end for
 
                Type t = animalManager.AnimalList[selected].GetType();
                nFoundEl = -1;
                for (int i = 0; i < sortComboBox.Items.Count; i++)
                {
                    if (sortComboBox.Items[i].ToString().Equals(t.Name))
                        nFoundEl = i;
 
                    if (nFoundEl >= 0)
                    {
                        sortComboBox.SelectedIndex = nFoundEl;
                    } //end if
                } //end for
 
                changeButton.Enabled = true;
            } //end if 
 
                      
        } //end selectedRowsButton_Click
 
 
 
 
 
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exitButton_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
 
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Really delete?", "Confirm delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                Int32 selected = AnimalDataGridView.CurrentRow.Index;
                animalManager.AnimalList.RemoveAt(selected);                
                animalManager.Counter--;
                Updater();
                changeButton.Enabled = false;
            } 
        }
 
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void resetButton_Click(object sender, EventArgs e)
        {
            housingCombobox.DataSource = Enum.GetValues(typeof(HousingType));
 
            if(meatRadioButton.Checked)                
                sortComboBox.DataSource = Enum.GetValues(typeof(MeatDjur));
 
            else
                sortComboBox.DataSource = Enum.GetValues(typeof(PlantDjur));
 
            nrOfLegsTextBox.Text = "4";
            nrOfItems.Text = Convert.ToString(animalManager.Counter);
            
            nickNameTextBox.Text = "";
 
            if (animalManager.AnimalList.Count > 0)
            {
                deleteButton.Enabled = true;
                addButton.Enabled = true;
            }
 
            else
            {
                deleteButton.Enabled = false;
                changeButton.Enabled = false;
                addButton.Enabled = true;
            }
        }
 
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void changeButton_Click(object sender, EventArgs e)
        {
 
            Int32 selected = AnimalDataGridView.CurrentRow.Index;
            animalManager.AnimalList.RemoveAt(selected);
            animalManager.Counter--;
            Add_Click(this, EventArgs.Empty);
            resetButton_Click(this, EventArgs.Empty);
            MessageBox.Show("Saved", "Saved");
            changeButton.Enabled = false;
            
        }
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void meatRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            sortComboBox.DataSource = Enum.GetValues(typeof(MeatDjur));
        }
 
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PlantRdioButton_CheckedChanged(object sender, EventArgs e)
        {
            sortComboBox.DataSource = Enum.GetValues(typeof(PlantDjur));
        }
 
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
 
        }
 
        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
 
        }
 
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
 
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Object obj = animalManager;
            binaryFileSerialize(obj, Convert.ToString(Environment.SpecialFolder.MyDocuments));
            
 
 
        }
 
 
        public static void binaryFileSerialize(Object obj, string filePath)
        {
            FileStream fileStream = null;
            
             
            try
            {
                fileStream = new FileStream(filePath,  FileMode.Create);
                BinaryFormatter b =  new BinaryFormatter();
                b.Serialize(fileStream, obj);
            }
 
            catch
            {
                throw;
            }
            finally
            {
                if (fileStream != null)
                fileStream.Close();
            }
        }
 
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
 
        }
 
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string nameOfFile = "";
            OpenFileDialog openExtensFile = new OpenFileDialog();
            openExtensFile.Title = "C#";
            openExtensFile.InitialDirectory = @"c:\";
            openExtensFile.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
            openExtensFile.FilterIndex = 2;
            openExtensFile.RestoreDirectory = true;
            if (openExtensFile.ShowDialog() == DialogResult.OK)
            {
                //nameOfFile = fdlg.FileName ; 
            } 
        }
 
        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog(); 
            saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments); 
            saveFileDialog1.Filter = "Your extension here (*.EXT)|*.ext|All Files (*.*)|*.*" ; 
            saveFileDialog1.FilterIndex = 1; if(saveFileDialog1.ShowDialog() == DialogResult.OK) 
            {         
                Console.WriteLine(saveFileDialog1.FileName);//Do what you want here
                //this.textBox1.Text = saveFileDialog.FileName;
            }
        }
 
 
 
    }
}
 
 
............................................................................................................
 
 
 
using System;
using System.Collections.Generic;
using System.Text;
 
namespace Animals
{
    [Serializable]
    public class AnimalManager
    {
        private int count = 0;
        private List<Animal> animalList = new List<Animal>();     
 
 
        /// <summary>
        /// 
        /// </summary>
        public AnimalManager()
        {
        }
 
 
        /// <summary>
        /// 
        /// </summary>
        public int Counter
        {
            get { return count; }
            set { count = value; }
        }
 
 
 
        /// <summary>
        /// 
        /// </summary>
        public List<Animal> AnimalList
        {
            get { return animalList; }
            set { animalList = value; }
        }
 
 
 
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="animal"></param>
        /// <param name="searchedType"></param>
        /// <returns></returns>
        public int Search<T>(List<Animal> animal, Type searchedType)
          where T : class
        {
            int count = 0;
 
            List<String> ids = new List<String>();
            Type typ = typeof(Animal);
 
            for (int i = 0; i < animal.Count; i++)
            {
 
                if (searchedType.IsAssignableFrom(animal[i].GetType()))
                {
                    typ = animal[i].GetType();
                    ids.Add(animal[i].ID);
                    count++;
                }
            }
             
            ids.Sort();
 
            int counter = 1;
            for (int i = 0; i < animal.Count; i++)
            {
                int m = 0;
                foreach (string j in ids)
                {
                    
                    int temp = Convert.ToInt32(ids[m].Substring(4));
                    m++;
                    if (counter != temp)
                     break;
                 counter++;
                 
                }
               
            }
 
           return counter;
 
}  
 
 
         
 
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="j"></param>
        /// <param name="typ"></param>
        /// <returns></returns>
        public bool Exists(String ids, int j, Type typ)
        {
            String nr = "";
            j++;
            if (typ.Name.Equals("Dog"))
            {
                if (j < 10)
                    nr = "ID:D00" + Convert.ToString((j));
 
                else if (j < 100)
                    nr = "ID:D0" + Convert.ToString((j));
 
                else
                    nr = "ID:D" + Convert.ToString((j));
 
 
                if (nr.Equals(ids))
                {
                    return true;
                }
            }
            return false;
        }
 
       
        /// <summary>
        /// 
        /// </summary>
        /// <param name="text"></param>
        /// <param name="nickName"></param>
        /// <param name="housing"></param>
        public void AddNewAnimal(String text, String nickName, HousingType housing)
        {
            if (text == "Dog")
            {
                //int test = Exists<Animal>(animalList, 
                int dogCount = Search<Animal>(animalList, typeof(Dog)); 
 
                string id;
 
                if (dogCount < 10)
                    id = "ID:D00" + Convert.ToString(dogCount);
 
                else if (dogCount < 100)
                    id = "ID:D0" + Convert.ToString(dogCount);
 
                else
                    id = "ID:D" + Convert.ToString(dogCount);
 
                Dog dog = new Dog(nickName, id, housing);
                animalList.Add(dog);
                Counter++;
 
            }
 
            else if (text == "Giraffe")
            {                
                int giraffeCount = Search<Animal>(animalList, typeof(Giraffe));
                string id;
                if (giraffeCount < 10)
                    id = "ID:G00" + Convert.ToString(giraffeCount);
 
                else if (giraffeCount < 100)
                    id = "ID:G0" + Convert.ToString(giraffeCount);
 
                else
                    id = "ID:G" + Convert.ToString(giraffeCount);
 
                Giraffe giraffe = new Giraffe(nickName, id, housing);
                animalList.Add(giraffe);
                Counter++;
            }
 
            else if (text == "Wolf")
            {
                int wolfCount = Search<Animal>(animalList, typeof(Wolf));
                string id;
                if (wolfCount < 10)
                    id = "ID:W00" + Convert.ToString(wolfCount);
 
                else if (wolfCount < 100)
                    id = "ID:W0" + Convert.ToString(wolfCount);
 
                else
                    id = "ID:W" + Convert.ToString(wolfCount);
 
                Wolf wolf = new Wolf(nickName, id, housing);
                animalList.Add(wolf);
                Counter++;
            }
 
            else if (text == "Horse")
            {
                int horseCount = Search<Animal>(animalList, typeof(Horse));
                string id;
                if (horseCount < 10)
                    id = "ID:H00" + Convert.ToString(horseCount);
 
                else if (horseCount < 100)
                    id = "ID:H0" + Convert.ToString(horseCount);
 
                else
                    id = "ID:H" + Convert.ToString(horseCount);
 
                Horse horse = new Horse(nickName, id, housing);
                animalList.Add(horse);
                Counter++;
            }
 
            else if (text == "Duck")
            {
                int duckCount = Search<Animal>(animalList, typeof(Duck));
                string id;
                if (duckCount < 10)
                    id = "ID:U00" + Convert.ToString(duckCount);
 
                else if (duckCount < 100)
                    id = "ID:U0" + Convert.ToString(duckCount);
 
                else
                    id = "ID:U" + Convert.ToString(duckCount);
 
                Duck duck = new Duck(nickName, id, housing);
                animalList.Add(duck);
                Counter++;
            }
 
            //else
              //  MessageBox.Show("Något gick fel (Form1, button1_Click()", "Information");             
        }
 
 
        /// <summary>
        /// 
        /// </summary>
        public void TestFood()
        {
            //MessageBox.Show(AnimalList[0].eat("Grass"), "Information");  //ÖRK
            //MessageBox.Show(AnimalList[0].eat("Cats"), "Information");  //GOTT
        }
    }
}

Open in new window

MickeysAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

käµfm³d 👽Commented:
Have you tried putting a [Serializable] immediately above line 19?
    public partial class Animal : Form
    {
       [Serializable]
       AnimalManager animalManager = new AnimalManager();

Open in new window

0
Richard LeeSoftware EnthusiastCommented:
You will need to make the AnimalManager serializable by doing the following:
[Serializable]
public class AnimalManager
{
   public AnimalManager() {}
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
MickeysAuthor Commented:
kaufmed: That wont work (error)

DaTribe. As you can see in my code above......it is as you say.
0
ShazbotOKCommented:
You cannot serialize the inherited class object "Form" you will need to create a serializable class object that does not inherit from Form
0
MickeysAuthor Commented:
I found the error. I had my abstract class as serialzied. That is not allowed. But at least you tried. :-)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.