Solved

ASP.NET - object serialization/deserialization

Posted on 2010-08-23
8
629 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
 
LVL 42

Expert Comment

by:sedgwick
Comment Utility
change:formatter.Serialize(stream, new List(history.ToArray()));to:formatter.Serialize(stream, new List(history));
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:josephdaviskcrm
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

763 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

12 Experts available now in Live!

Get 1:1 Help Now