[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

ASP.NET - object serialization/deserialization

Posted on 2010-08-23
8
Medium Priority
?
675 Views
Last Modified: 2012-05-10
I've got the following code which is taking an object called 'history' of type Stack<String>, serializing it and placing it into a hidden textbox on a page.

            IFormatter formatter = new BinaryFormatter();
            Stream stream = new MemoryStream();
            formatter.Serialize(stream, history);
            stream.Position = 0;
            StreamReader reader = new StreamReader(stream);
            txtHistorySerialized.Text = reader.ReadToEnd();

The page is then posted to another page where the following code is being used to attempt to deserialize that object back into a Stack<String> so that it can be utilized.

            Stack<string> hist;
            if (Request["history"] != null)
            {
                String str = Request["history"].ToString();
                byte[] byteArray = Encoding.ASCII.GetBytes(str);
                MemoryStream stream = new MemoryStream(byteArray);
                IFormatter formatter = new BinaryFormatter();
                hist = formatter.Deserialize(stream) as Stack<string>;
            }

However, when the program execution comes to the line where the deserialize method is called, it throws an exception saying:

The input stream is not a valid binary format. The starting contents (in bytes) are: 01-3F-3F-3F-3F-01-0C-02-49-53-79-73-74-65-6D-2C-20 ...

Can anyone help me out on this and let me know where I'm messing up?

Thanks
0
Comment
Question by:josephdaviskcrm
[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
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33501863
Hi,

You are saving your serialized data in txtHistorySerialized and while on deserialization you are trying to deserialize data of history from line String str =  Request["history"].ToString(); & that is why you are getting error The input stream is  not a valid binary format.

Regards,
VSS
0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33501877
Hi,

You need to use the binary data in txtHistorySerialized. I think then after it would work fine.

Regards,
VSS
0
 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 33501884
need a little tweak: IFormatter formatter = new BinaryFormatter();            Stream stream = new MemoryStream();            formatter.Serialize(stream, new List(history.ToArray()));            stream.Position = 0;            StreamReader reader = new StreamReader(stream);            txtHistorySerialized.Text = reader.ReadToEnd();Stack hist;            if (Request["history"] != null)            {                String str = Request["history"].ToString();                byte[] byteArray = Encoding.ASCII.GetBytes(str);                MemoryStream stream = new MemoryStream(byteArray);                IFormatter formatter = new BinaryFormatter();                hist = new Stack((IEnumerable)formatter.Deserialize(stream));            }
0
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!

 
LVL 42

Expert Comment

by:Meir Rivkin
ID: 33501895
change:formatter.Serialize(stream, new List(history.ToArray()));to:formatter.Serialize(stream, new List(history));
0
 

Author Comment

by:josephdaviskcrm
ID: 33502817
sedgwick,
I'm still getting the same error I was before when I use your code.

vs00saini,
Your statement about needing to use binary data sounds great but I don't know how to do that.
0
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 2000 total points
ID: 33503875
The problem is stemming from the way you are writing the data out in the first place. Simply trying to convert binary to a string and back again is going to cause all sorts of problems.

If you convert to a Base64 string on the way out then it will be a lot easier to read back:
/*
 *   write out
 */
Stack<string> stack = new Stack<string>();
stack.Push("Hello world");

IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, stack);

stream.Position = 0;
txtHistorySerialized.Text = Convert.ToBase64String(stream.GetBuffer());    // conver to Base64

/*
 *   Read back
 */
string source = Request["history"];
byte[] data = Convert.FromBase64String(source);

IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
MemoryStream ms = new MemoryStream(data);

Stack<string> history = (Stack<string>)formatter.Deserialize(ms);

Open in new window

0
 
LVL 16

Expert Comment

by:Vikram Singh Saini
ID: 33506987
Hi,

What I have learnt from programming till date about Serialization is that to Deserialize an object you should have the object of same type for which you have done serialization.

So here is the code for which you can test the code given here. The code is been developed in Window app but it can be converted into Web Application with little modification.

I have used two buttons on Form.

Please see the code attach.

Regards,
VSS

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;

namespace ee_DataSerialization
{
    public partial class Form1 : Form
    {
        Stack<string> history;
        Stream stream;
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            history = new Stack<string>();
            history.Push("Hello");           

            IFormatter formatter = new BinaryFormatter();
            stream = new MemoryStream();
            formatter.Serialize(stream, history);           
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Stack<string> hist;
            if (history!= null)
            {
                IFormatter formatter = new BinaryFormatter();
                stream.Position = 0;
                hist = formatter.Deserialize(stream) as Stack<string>;
                richTextBox1.Text = hist.Pop().ToString();
            }
        }
    }
}

Open in new window

0
 

Author Closing Comment

by:josephdaviskcrm
ID: 33522059
The conversion to base64 string and back again was all I needed to do to make my code work perfectly.  Thanks for this.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

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

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …

650 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