Solved

ASP.NET - object serialization/deserialization

Posted on 2010-08-23
8
634 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
  • 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:sedgwick
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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 42

Expert Comment

by:sedgwick
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 500 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
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…
Windows 10 is mostly good. However the one thing that annoys me is how many clicks you have to do to dial a VPN connection. You have to go to settings from the start menu, (2 clicks), Network and Internet (1 click), Click VPN (another click) then fi…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

813 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now