Click here to Skip to main content
15,867,308 members
Articles / Web Development / XHTML

HTTP Binary Serialization through ASP.NET without WCF

Rate me:
Please Sign up or sign in to vote.
5.00/5 (11 votes)
15 Aug 2009CPOL3 min read 55.9K   346   39   11
Shows how to serialize an object using binary serialization without using WCF.

Introduction

While developing client/server applications, you often need to send an object to your client. The easiest way for us programmers to work with an object would be to get the whole object from the server, not just some properties.

One way to do this is to use WCF or Web Services, which give you a whole set of tools, like serialization to accomplish this task, but these set of technologies often bring a lot of overhead and complexities to your project, that often you would not want if what you're doing is just sending and receiving one or more objects.

Faced with this dilemma, I spent some time looking for a solution to this; my goal was to find a very easy, simple, and clean way to create an object on the server, serialize it, and send it back to the client. Security and interoperability were not a concern at this point, but they could be implemented later. The constraints for this were that it had to be fast and it had to work through the basic HTTP protocol.

My solution was to create an ASP.NET page that reads the query string to determine what object to return, creates the object, serializes it to binary, and returns it as a binary attachment to the client. The client downloads this file using the WebClient() class and deserializes it back to the object.

Both the server and the client share a class library containing the common object. At first, I implemented this using XML serialization, but found that it is quite slow, but it could also be used if you require interoperability.

Background

Bear in mind that this is not the only way to do this; you probably can do it with WCF using a custom binding or using MTOM, but I found in my experience that these methods were too involved and added unnecessary complexity for simple projects.

Using the Code

On the web server page load, we include code to check which object the client is requesting, and return the serialized object as a binary attachment.

C#
protected void Page_Load(object sender, EventArgs e)
{
    // Check which object the client wants
    if (Request.QueryString["op"] == "getdata")
    {
        // Create a new instance of the sample data object
        var data = new SampleData();
        data.moreData = 34343;
        data.otherData = true;
        data.SomeData = "fewoifjweofjwepo";
        // Set content type and header
        // octet-stream allow us to send binary data
        // the file name here is irrelevant as it is 
        // not actually used by the client.
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", 
                             "attachment; filename=sampleData.bin");
        // Serialzie the object and write it to the response stream
        var binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(Response.OutputStream, data);
        // Its important to end the response, overwise the other page content
        // would be sent to the client.
        Response.End();
    }

On the client, we create the request to the server using a query string, and deserialize the response.

C#
// Create the url for the service, this could be stored in a configuration file
string url = "http://localhost/BinaryServiceSample/Default.aspx?op=getdata";
// Download the data to a byte array
// This data contains the actual object
var client = new WebClient();
byte[] result = client.DownloadData(url);
// Create a memory stream to stored the object
var mem = new MemoryStream(result);
var binaryFormatter = new BinaryFormatter();
var data = (SampleData)binaryFormatter.Deserialize(mem);
mem.Close();
// Write object to the console
Console.Write(data.ToString());
Console.ReadLine();

Points of Interest

  • Although binary serialization may "feel" more comfortable, it may not be compatible across different platforms.
  • Serializing objects using binary serialization is way faster than XML.
  • This code does not include any error handling, this is something that could be easily incorporated into it. I did not include it to make it more clear and simple.
  • One way to add security is to encrypt the actual bytes before sending them to the client; this, of course, would make interoperability very difficult.
  • Additional transport speed could be obtained by compressing the bytes before sending them; I know ICSharpCode.SharpZipLib.dll can compress in memory bytes, and it is free, but you could also do it with the .NET Framework by implementing HTTP compression and embedding it into your code - check out this article for an example: http://www.codeproject.com/Articles/38067/Compress-Response.aspx.
  • Serializing an object like this seems to give me more control over how things are done without adding too much complexity.

I would like to receive comments, suggestions, and constructive criticism about this, if you have any, or any improvements, please let me know so I can include them.

Thanks to Andre Sanches for his contributions to this article.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer NeoDeck Software
Puerto Rico Puerto Rico
I've been programming since I was 10 years old, and I consider it my passion. I founded NeoDeck Software a small development company in 2002, and we've been in business developing various applications, concentrating in medical software.

My programming experience ranges from VB6, C#, VB.NET and Objective-C.
I have experience in SQL Server, ASP.NET, WCF, WPF, Blend, Silverlight, SQLite, iPhone and XCode.

I'm a Microsoft Certified Professional and have a Bachelors Degree in Computer Science.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey16-Apr-12 3:28
professionalManoj Kumar Choubey16-Apr-12 3:28 
GeneralMy vote of 5 Pin
Kanasz Robert12-Nov-10 0:30
professionalKanasz Robert12-Nov-10 0:30 
GeneralThanks Pin
Ziad J.khan3-Nov-09 20:19
professionalZiad J.khan3-Nov-09 20:19 
GeneralSuggestion Pin
jackmos19-Aug-09 2:56
professionaljackmos19-Aug-09 2:56 
GeneralRe: Suggestion Pin
Ricardo Pineda Then24-Aug-09 12:18
Ricardo Pineda Then24-Aug-09 12:18 
Hi, thanks for your suggestion!, can you provide a sample of how you would use HttpHandler in the code?
GeneralRe: Suggestion Pin
jackmos24-Aug-09 12:34
professionaljackmos24-Aug-09 12:34 
GeneralMy 2 cents Pin
Andre Sanches (alvs)13-Aug-09 12:18
Andre Sanches (alvs)13-Aug-09 12:18 
GeneralRe: My 2 cents Pin
Ricardo Pineda Then14-Aug-09 11:08
Ricardo Pineda Then14-Aug-09 11:08 
Question17 and have bachelor degree? Pin
Andre Sanches (alvs)12-Aug-09 12:09
Andre Sanches (alvs)12-Aug-09 12:09 
AnswerRe: 17 and have bachelor degree? Pin
Ricardo Pineda Then13-Aug-09 11:12
Ricardo Pineda Then13-Aug-09 11:12 
GeneralRe: 17 and have bachelor degree? Pin
Andre Sanches (alvs)13-Aug-09 12:00
Andre Sanches (alvs)13-Aug-09 12:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.