?
Solved

ASP.NET - object serialization/deserialization

Posted on 2010-08-23
8
Medium Priority
?
664 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: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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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 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

Basic Security of Your VPC

So, you’ve got this shiny new VPC and a fancy new application configured on your EC2 servers ready to go. This application is only accessible from your computer, which is great for security, but you need your users to be able to access it! So, what’s the easiest way to do this?

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…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Suggested Courses

743 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