Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

New, Open, Save, Save As,   Serializable

Posted on 2009-07-06
2
Medium Priority
?
298 Views
Last Modified: 2012-05-07
I am not sure how to do a menu that works so it serialize my object.
(the menu is created so it how it all should be working I cant get to work correct)

Please check my code below and tell me how to do it correct.

What I like is to take my object and be able to save it, Save As, Open it and create a new.
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;
            }
        }
 
        private void exportToXMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
 
        }
 
 
 
 
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Object obj = animalManager;
            binaryFileSerialize(obj, Convert.ToString(Environment.SpecialFolder.MyDocuments));
            //binaryArraySerialize(obj);
 
 
        }
 
 
        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();
            }
        }
 
 
 
 
 
        public static T binaryFileDeSerialize<T> (string filePath)
        {
            FileStream fileStream = null;
            Object obj;
            
            try
            {
                if (File.Exists(filePath) == false)
                    throw new FileNotFoundException("The file" + " was not found. ", filePath);
 
                fileStream = new FileStream(filePath, FileMode. Open);
                BinaryFormatter b = new BinaryFormatter();
                obj = b.Deserialize(fileStream);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (fileStream != null)
                fileStream. Close();
            }
            
            return (T)obj;
        
        }
 
 
        public static byte[] binaryArraySerialize(Object obj)
        {
            byte[] serializedObject;
            MemoryStream ms = new MemoryStream();
            BinaryFormatter b = new BinaryFormatter();
            b.Serialize(ms, obj);
            ms.Seek(0, 0);
            serializedObject = ms.ToArray();
            ms.Close();
            return serializedObject;
        }
 
 
        public static T binaryArrayDeSerialize<T> (byte[] serializedObject)
        {
            MemoryStream ms = new MemoryStream();
            ms.Write(serializedObject,0, serializedObject.Length);
            ms.Seek(0, 0);
            BinaryFormatter b = new BinaryFormatter();
            Object obj = b.Deserialize(ms);
            ms.Close();
            return (T)obj;
        }

Open in new window

0
Comment
Question by:Mickeys
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 12

Expert Comment

by:ShazbotOK
ID: 24788927
1) Is an error being thrown - if yes what is the error?
2) What are your serializing?  I do not see that code....
0
 

Accepted Solution

by:
Mickeys earned 0 total points
ID: 24791908
no error. I just wanna know how to do it.

All I manged to do is open a window telling where to save the stuff. But I dont know how to save it.

I have included my hole FORM code

This is what I want to save and be able to open and load again: AnimalManager animalManager = new AnimalManager();
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;
            speedLabel.Visible = false;
            speedTextBox.Visible = 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";
 
            if (sortComboBox.SelectedItem.ToString() == "Horse")
            {
                speedLabel.Visible = true;
                speedTextBox.Visible = true;
            }
 
            else
            {
                speedLabel.Visible = false;
                speedTextBox.Visible = false;
            }
        }
 
 
        /// <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 PlantRadioButton_CheckedChanged(object sender, EventArgs e)
        {
            sortComboBox.DataSource = Enum.GetValues(typeof(PlantDjur));
        }
 
 
        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));
            //binaryArraySerialize(obj);
 
 
        }
 
 
        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();
            }
        }
 
 
 
 
 
        public static T binaryFileDeSerialize<T> (string filePath)
        {
            FileStream fileStream = null;
            Object obj;
            
            try
            {
                if (File.Exists(filePath) == false)
                    throw new FileNotFoundException("The file" + " was not found. ", filePath);
 
                fileStream = new FileStream(filePath, FileMode. Open);
                BinaryFormatter b = new BinaryFormatter();
                obj = b.Deserialize(fileStream);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (fileStream != null)
                fileStream. Close();
            }
            
            return (T)obj;
        
        }
 
 
        public static byte[] binaryArraySerialize(Object obj)
        {
            byte[] serializedObject;
            MemoryStream ms = new MemoryStream();
            BinaryFormatter b = new BinaryFormatter();
            b.Serialize(ms, obj);
            ms.Seek(0, 0);
            serializedObject = ms.ToArray();
            ms.Close();
            return serializedObject;
        }
 
 
        public static T binaryArrayDeSerialize<T> (byte[] serializedObject)
        {
            MemoryStream ms = new MemoryStream();
            ms.Write(serializedObject,0, serializedObject.Length);
            ms.Seek(0, 0);
            BinaryFormatter b = new BinaryFormatter();
            Object obj = b.Deserialize(ms);
            ms.Close();
            return (T)obj;
        }
 
 
        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;
            }
        }
 
        private void exportToXMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
 
        }
 
 
 
    }
}

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question