Welcome to Dream.In.Code
Become a C# Expert!

Join 136,928 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,838 people online right now. Registration is fast and FREE... Join Now!




Serial/deserializing

 
Reply to this topicStart new topic

Serial/deserializing, For whole classes?

Sharkadder
3 Apr, 2008 - 12:49 PM
Post #1

New D.I.C Head
*

Joined: 17 Mar, 2008
Posts: 36


My Contributions
Hi, i have recently been trying to get to grips with object serialization within C#. I thought i had cracked something when i managed to serialize/deserialize a string. I rread up on this topic alot and couldn't get my head around it really.

Anyways i now need to move onto the next step which is to serialize a whole class. This i am unsure of and would like a pointer in the right direction.

As mentioned above i have serialized/deserized a string so i know of the functions but abit lost when it comes to classes.

Heres what i have so far:

When you press save from the menu:

CODE
Stream mystream;
            mystream = File.OpenWrite( Application.StartupPath + "\\" + this.textBox1.Text);
            if (mystream != null)
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(mystream, this.textBox1.Text);
                mystream.Close();



When you press open from the menu:

CODE
            OpenFileDialog open = new OpenFileDialog();

            if (open.ShowDialog() == DialogResult.OK)
            {
                filename = open.FileName;
                Stream mystream = open.OpenFile();
                if (mystream != null)
                {
                    IFormatter formatter = new BinaryFormatter();

                    // get string from file
                    text1 = formatter.Deserialize(mystream).ToString();

                    // put it in a new child window
                    Form2 f = new Form2();
                    f.Controls["textBox1"].Text = text1;
                    f.MdiParent = this;
                    f.Show();

                    mystream.Close();
                    this.Refresh();




Basically what is happening is when you save the file i.e. the value from the text box it serializes it and creates a binary file with the value inside. when you loads the file up it deserializes it and puts the value in the text box.

now my question is, how do i set this up for a class/object? I am wanting to create a class which will hold all the data, once i press file and save it will get the data from the class/object and then save it, when i press file and open it will put the data back into the class or object, that will then put it in the relevent part of a form called form2.

thanks, i have kinda got it working, i just need to know how i'd set it up for objects/classes, it has confused me abit :S, as i say i looked on some example websites and it was totally the wrong thing, was different way to how i've known people to do it.

thanks
User is offlineProfile CardPM
+Quote Post

baavgai
RE: Serial/deserializing
3 Apr, 2008 - 02:05 PM
Post #2

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,042



Thanked: 106 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions
First, rather than serializing in binary, look into XML Serialization. It offers a few advantages. One is you can easily check if it's storing what you example. The other is it's easy to remote with http. Refer to the link for custom class example.

Also, look into DataSets and data binding. You can represent pretty much any kind of data within the structure of a dataset. DataSets already implement most serializing interfaces and Microsoft favors them for binding data to controls in forms.

Hope this helps.

User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Serial/deserializing
3 Apr, 2008 - 02:19 PM
Post #3

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,231



Thanked: 220 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
But if you choose to just do basic binary serialization for simplicity sake here is a great example for you...

csharp


// Lets first define who SharkAdder truly is... he is a 65 year old 173cm tall shark
// It can also tell you its name!

// Notice that we put this attribute on top telling C# that this bad boy shark knows how to serialize
[Serializable]
public class SharkAdder
{
int height = 173;
int age = 65; // Old man
String name = "SharkAdder";

public String GetName()
{
return name;
}

}

// This is a button event to serialize our class with.
private void serialize_Click(object sender, EventArgs e)
{
// Create an instance of your object (in this case "you")
SharkAdder DaShark = new SharkAdder();

try
{
// Lets create your home, the open ocean. Ahhh yes nice lovely ocean. Whoa, there is nemo!
// We shall call this ocean sharkadder ocean
Stream ocean = File.Open("c:\\sharkadder.dat", FileMode.Create);

// Let the ocean know that we are going to serialize you binary style
BinaryFormatter b = new BinaryFormatter();

// Serialize you into the ocean. Free willy!
b.Serialize(ocean, DaShark);
ocean.Close();
}
catch (Exception ex)
{
// Just in case the ocean doesn't like you
MessageBox.Show(ex.ToString());
}
}

private void deserialize_Click(object sender, EventArgs e)
{
// Lets create your clone (straight out of the movie the 6th day)
SharkAdder ReturnofDaShark = new SharkAdder();

// Lets open up your ocean and find you (come home lassie!)
Stream ocean = File.Open("c:\\sharkadder.dat",FileMode.Open);

// Tell that big bad ocean that you only do it binary style
BinaryFormatter b = new BinaryFormatter();

// program the clone to be an instance of you and that you can be found in the ocean
ReturnofDaShark = (SharkAdder)b.Deserialize(ocean);

// Announce your return because now the clone thinks it is you, deserialized!
MessageBox.Show(ReturnofDaShark.GetName() + " is back!");

ocean.Close();
}


So now you have two buttons. One that can take your object and serialize it to a file and place that file into the c:\ root folder as "sharkadder.dat" and the second which can open that file deserialize the object back into a copy of the SharkAdder object exactly in the same state as it was when it was serialized.

Hopefully that helps you out!

"At DIC we be shark handling code ninjas... sorry for Capty he lost his arm to a really nasty sharkadder once." decap.gif
User is online!Profile CardPM
+Quote Post

Sharkadder
RE: Serial/deserializing
3 Apr, 2008 - 03:27 PM
Post #4

New D.I.C Head
*

Joined: 17 Mar, 2008
Posts: 36


My Contributions
wooow thats for the swift reply, i will check that out tomorrow and let you know how i get on, thanks

the bit i am stuck on and STILL cannot get my head around is the saving part.

I have an mdi container, when i press file and new it brings up a new form yeah, i type some value into the text box and hopefully something simular to this will serialize it. What i don't get is how i get the value from the text box to the appropiate string in my serialized class.

Likewise when i load new data up again, the thing i don't seem to take in is, when i press file and open, i select my file and press ok, how do i get all the variable/string/int values to go into the appropiate place within the class, and then further into my textbox?

Once i got this sorted i am away, thanks for the example by the way, just need to figure out how i can communicate with the elements in my form from the values in the class
User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Serial/deserializing
3 Apr, 2008 - 03:49 PM
Post #5

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,231



Thanked: 220 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
That is the beauty of serialization... you don't need to keep track of where the data from the class goes. In addition to saving the data in the object it saves "HOW" that data is arranged. When you deserialize it then brings in all the info and uses it to build the object. C# takes care of what type member variables are, their scope etc. That data is carried along in the encrypted string of data.

All you need to worry about is that what data is in an object prior to saving (btw, saving can be thought of as taking a snapshot of your class, putting it into a serialized string of data and simply written out to file) because when you deserialize it will be in the exact same state as it was when you serialized it to file.

Think of it as a filing cabinet with 3 drawers. Lets say you have some papers on programming in the first drawer, some papers on how to build ricin for your terrorist plot in your second drawer, and some papers on how to make grilled cheese in the third drawer.

When you serialize the cabinet not only does the info in the papers get sent to file, but you are also serializing information to say that programming papers belong in drawer 1, ricin in drawer2, and grilled cheese in drawer 3 along with that the cabinet is made of metal, is 5 feet high and has a lock on it.

When you load it up, it loads up all the data that tells C# I need to build a 3 drawer metal cabinet 5 feet high with a lock and that programming papers go in drawer 1, ricin in drawer 2, and grilled cheese in drawer 3.

smile.gif
User is online!Profile CardPM
+Quote Post

Sharkadder
RE: Serial/deserializing
4 Apr, 2008 - 05:31 AM
Post #6

New D.I.C Head
*

Joined: 17 Mar, 2008
Posts: 36


My Contributions
still confused dude, this is what i have done so far.

I created a class called SharkAdder as you mentioned and put in them 2 values.

The thing is i have a textbox within form2, what i need is when i press ok is for the value to get displayed within a label in form3, i only want it serializing when i press file and save. I can now set that up as i have figured the code out. How the hell do i get the value from the textbox into label in form3?

Once done i can then press file and save from in form3 and then serialize the class.

Or even better still how do i get the input from the textbox into a string in the class SharkAdder and then use this to put the value into a label on form3?

I tried saying label1.text = class1.height but it says it's not accessable due to protection levels but the string in the class is public :S.

Can you try clearing that one up for me? maybe i will be able to really know what i am doing then.

p.s. i just tried serializing with the file sharkadder.dat and it saves the file where it is meant to, when i deserialize the file yeah it brings the message up. but what i need is the value from the textbox putting back in once i deserialize.



This post has been edited by Sharkadder: 4 Apr, 2008 - 06:43 AM
User is offlineProfile CardPM
+Quote Post

baavgai
RE: Serial/deserializing
4 Apr, 2008 - 07:41 AM
Post #7

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,042



Thanked: 106 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions
Do you really need to save object data into a file, or do you need to share data between objects? It's starting to sound a lot like the latter.

The best way to share data between objects is to simply pass it around. Like your example, label1 on a form instance is private, so objects of other classes can't access it. You either make lable1 public or, the preferred method, create a public property or method in to object to allow data to be shared.

User is offlineProfile CardPM
+Quote Post

Sharkadder
RE: Serial/deserializing
4 Apr, 2008 - 08:54 AM
Post #8

New D.I.C Head
*

Joined: 17 Mar, 2008
Posts: 36


My Contributions
well i tried making lable1 in form3 equal the value from the textbox1 in form2. i made the textbox public so i can see it in other places but it wouldn't let me.

What i still need to know is how i get the value from the textbox into the class, i have got the serialization and deserilization sorted for reading/writing to a binary file but what i don't know is how to add new data to it by doing what i am trying to do.

The thing is when you load a serialised file up instead of it loading form2 up where you type in data, it will load form3 up which is for display, so it is like this:

form1 = mdi container
form2 = data edit form
form3 = display results from class

come the end of it i save the file through the file ----> save within form3

that will serialize everything and i deserialize when i press file and open, form 3 will then load displaying the values. But as i say the problem i am having now is getting new data from form2 into the class before i serialize. So when i deserialize textbox1 will have the value inside it

This post has been edited by Sharkadder: 4 Apr, 2008 - 08:58 AM
User is offlineProfile CardPM
+Quote Post

Sharkadder
RE: Serial/deserializing
5 Apr, 2008 - 03:37 PM
Post #9

New D.I.C Head
*

Joined: 17 Mar, 2008
Posts: 36


My Contributions
Sorted it, this is what i did:

After i created a new instance of the class, i told the string "name" to equal the textbox value, so that when i deserialized and say textbox1.text = myinstance.name it would equal that value.

turns out i just needed to know where about's to put hte code, i thought that was all i needed to do.

Not sure if i can get away with doing it this way though as i'm sure i've always been told to use a class itself for the serialization and not the form. But anyways it is now working for serialize/deserialize from binary file.

many thanks for all the help people, if it turns out what i have done isn't good enough i will let people know, but as for now this problem is solved.
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/3/08 10:28PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month