Click here to Skip to main content
13,044,539 members (80,076 online)
Click here to Skip to main content
Add your own
alternative version


20 bookmarked
Posted 6 Oct 2010

Binary Serialization to Isolated Storage in Silverlight - BinaryFormatter vs. sharpSerializer

, 6 Oct 2010
Rate this:
Please Sign up or sign in to vote.
How to serialize binary data to IsolatedStorage in a Silverlight client when there is no BinaryFormatter in Silverlight? Why not with sharpSerializer? - An open source XML and binary serializer for .NET and Silverlight


A Silverlight application has by default 1MB of available space in the isolated storage to store its local data. If started as an "out of browser" window, this amount increases to 25MB, even if the application has no elevated permissions. You can check the free memory amount by pressing the right mouse button on your Silverlight program, then go to the registry "Application storage" and there you see it.

Unfortunately sometimes there is more storage needed. For example - a briefcase model - a sales agent downloads data from the server, works offline with the data by a customer, and finally synchronizes the data with the server.

You can always demand more free space for the application using the method IncreaseQuotaTo() of the IsolatedStorageFile class, as described in the following article:

However increasing only the storage size is not optimal. A better solution would be saving the data more efficiently than to XML.


DataContractSerializer is a standard way of serializing business objects by a Silverlight client. But it serializes to XML which is known as a wasteful way of storing data. A better choice would be a binary serialization. But there is a problem - there is no BinaryFormatter in Silverlight at all. :-(

A third-party software is needed. Let's take for example sharpSerializer - an open source XML and binary serializer for .NET, .NET Compact and Silverlight - and compare it with BinaryFormatter from the full .NET Framework.

BinaryFormatter vs. sharpSerializer

As I said before - there is no BinaryFormatter in Silverlight. To get some results anyway, I checked the serialization speed and output file size of BinaryFormatter from the full version of .NET Framework and compared these values with the results of sharpSerializer v.2.6.

Serialized was an array of 10.000 elements of type RootContainer - a very sophisticated sample class from the HelloWorldDemo of sharpSerializer. I had to mark the RootContainer and all of its subclasses with [Serializable] as it's demanded by BinaryFormatter to work. Btw, SharpSerializer needs no additional attributes in serialized objects, nor any type definitions in its Serialize() method, as i.e. XmlSerializer needs.

Below you see the main body of the RootContainer. To see all of its subclasses, refer to the source code of sharpSerializer (There is another article describing serialization of weird classes like the RootContainer to XML - XML Serialization of Generic Dictionary, Multidimensional Array, and Inherited Type, with sharpSerializer .NET).

// This is an example from the
// Please download the full source code with HelloWorld demo to see more details.
public class RootContainer
    public SByte SimpleSByte { get; set; }
    public int SimpleInt { get; set; }
    public Single SimpleSingle { get; set; }
    public double SimpleDouble { get; set; }
    public DateTime SimpleDateTime { get; set; }
    public TimeSpan SimpleTimeSpan { get; set; }

    /// Every enumeration is simple type
    public SimpleEnum SimpleEnum { get; set; }

    /// Enumeration with FlagsAttribute is SimpleType.
    /// It is correct serialized if the result of the flag combination 
    /// has unique int value,
    /// i.e. Flag1 = 2, Flag2 = 4, Flag3 = 8 ...
    public FlagEnum FlagsEnum { get; set; }

    /// Decimal is 16 bytes long
    public decimal SimpleDecimal { get; set; }
    public string SimpleString { get; set; }
    public string EmptyString { get; set; }

    /// Structures are handled as objects during serialization
    /// They are serialized as ComplexProperty
    public AdvancedStruct AdvancedStruct { get; set; }

    /// One dimensional array of simple type.
    /// It is serialized as SingleDimensionalArrayProperty
    public string[] SingleArray { get; set; }

    /// Multidimensional array of simple type.
    /// Is is serialized as MultiDimensionalArrayProperty
    public string[,] DoubleArray { get; set; }

    /// Single array of derived objects.
    /// This is polymorphic collection - Items derive from the interface
    public IComplexObject[] PolymorphicSingleArray { get; set; }

    /// Generic list is serialized as a collection.
    /// It is serialized as CollectionProperty
    public IList<string> GenericList { get; set; }

    /// Generic Dictionary of simple types.
    /// Is is serialized as DictionaryProperty
    public IDictionary<int, string> GenericDictionary { get; set; }

    /// Generic dictionary where values are inherited from the value type
    public IDictionary<int, 
	IComplexObject> GenericDictionaryOfPolymorphicValues { get; set; }

    /// Polymorphic property. Object instance derives from the property type
    /// Is serialized as ComplexProperty
    public IComplexObject ComplexObject { get; set; }

    /// Collection where item values are
    /// derived from the collection item type
    public ComplexObjectPolymorphicCollection ComplexObjectCollection { get; set; }

    /// Dictionary where values are derived
    /// from the predefined dictionary value type
    public ComplexObjectPolymorphicDictionary ComplexObjectDictionary { get; set; }

    /// List items are derived from the generic attribute.
    /// This is polymorphic attribute.
    public IList<IComplexObject> GenericListOfComplexObjects { get; set; }

    /// Generic object with polymorphic attribute.
    /// It is serialized as ComplexProperty
    public GenericObject<IComplexObject> GenericObjectOfComplexObject { get; set; }

    /// Multidimensional array of generic object with polymorphic attribute
    public GenericObject<IComplexObject>[,] 
	MultiArrayOfGenericObjectWithPolymorphicArgument { get; set; }

    /// Array of objects where every item can be of other type
    /// It is serialized as SingleDimensionalArrayProperty
    public object[] SingleArrayOfObjects { get; set; }

For testing purposes, I made a small benchmark console program to measure the serialization and deserialization time and to store the serialization results as files - to compare their sizes.

The "Main" method produces 10.000 elements of the RootContainer and invokes single test methods:

static void Main(string[] args)
    // create 10.000 items
    RootContainer[] containerArray = createContainerArray(10000);

    // Serialization tests
    serializeWithBinaryFormatter(containerArray, "BinaryFormatter.bin");
	BinarySerializationMode.Burst, "sharpSerializerBurst.bin");
	BinarySerializationMode.SizeOptimized, "sharpSerializerOptimized.bin");
    serializeWithXmlSharpSerializer(containerArray, "sharpSerializer.xml");

    // Deserialization tests

The following method uses BinaryFormatter for the serialization. Note! Stopwatch is the most adequate class in .NET to measure time.

private static void serializeWithBinaryFormatter
	(RootContainer[] containerArray, string shortFilename)
    // convert short filename to full filename
    string filename = getFilename(shortFilename);

    // creating a stream, as BinaryFormatter can not serialize directly to a file
    using (var stream = new FileStream(filename, FileMode.Create))
        var formatter = new BinaryFormatter();

        // Stopwatch <span lang="de">as a stopper is enough accurate</span>
        Stopwatch watch = new Stopwatch();
        Console.WriteLine("Starting serialization with BinaryFormatter");

        // Serializing
        formatter.Serialize(stream, containerArray);

		("Stopped after {0}ms", watch.ElapsedMilliseconds));

To serialize the test object with sharpSerializer, I created the following method. Btw, SharpSerializer has much easier syntax than BinaryFormatter.

private static void serializeWithSharpSerializer
    (RootContainer[] containerArray, BinarySerializationMode mode, string shortFilename)
    string filename = getFilename(shortFilename);

    // create sharpSerializer with an overloaded constructor
    var serializer = new SharpSerializer(mode)

    Stopwatch watch = new Stopwatch();
    Console.WriteLine(string.Format("Starting serialization with SharpSerializer ({0})", 
		Enum.GetName(typeof(BinarySerializationMode), mode)));

    // Serializing
    serializer.Serialize(containerArray, filename);

    Console.WriteLine(string.Format("Stopped after {0}ms", watch.ElapsedMilliseconds));

Serialization and deserialization times on the program screen:

Serialization and deserialization times

Serialization and deserialization results in a table (For serializing of other objects, the results and their proportions can vary):

SerializerSerialization time [s]File size [MB]Deserialization time [s]
.NET BinaryFormatter2.119.37.9
sharpSerializer - binary (Burst)
sharpSerializer - binary (SizeOptimized)
sharpSerializer - XML3.786.017.6

The fastest serialization of 2.1s offers BinaryFormatter, but its file size of 19.3MB is twice as big as produces sharpSerializer in its binary SizeOptimized mode (you can find more about binary modes of sharpSerializer in the tutorial on the project page).

The deserialization time of BinaryFormatter is over 3 times longer than the best time 2.6s of sharpSerializer.

Result Analysis

Server Side

Where the full .NET Framework is available, you have a choice between BinaryFormatter and sharpSerializer to make a binary serialization. If you write data only once and read it multiple times (i.e. photo gallery or an mp3 music store) - then sharpSerializer is a better choice than the built-in BinaryFormatter. It stores 80% slower but reads 300% faster then BinaryFormatter. Not to mention the file size which is 50% smaller if serialized with sharpSerializer.

Silverlight Client Side

In Silverlight, there is no choice if you want to use binary serialization. As there is no BinaryFormatter in Silverlight, the only solution is sharpSerializer.

Advantages of sharpSerializer

  • Very easy syntax
  • No need to mark the serialized object with additional attributes
  • No need to declare serialized types in the Serialize() method
  • Small size of the produced file
  • Fast deserialization of objects
  • Common algorithm and serialization compatibility between .NET Full, .NET Compact and Silverlight
  • Open Source and free for any purpose

Disadvantages of sharpSerializer

  • Only public properties are serialized
  • Only objects with standard constructor are deserialized
  • XML and binary format is not compatible with other .NET standards


Among many advantages and good benchmarks, there are also some disadvantages of sharpSerializer. It depends on the context, if the disadvantages are a stone in the shoe.

As I use sharpSerializer mostly to store my own business objects, there is no problem for me to provide a standard constructor for every object. There is also no problem in using only public properties to store the object's state.

If there are complicated third-party classes to serialize, they should be converted with an adapter pattern into simple ones. The adapter pattern simplifies the output and decreases its size in most cases, as only needed properties are serialized.

sharpSerializer is no more Beta, its current version is 2.6. It works stable and reliable.

One of the future milestones of sharpSerializer is data compression. Actually there are problems with finding an open source substitute for DeflateStream for Silverlight as GZipStream and DeflateStream are not supported in Silverlight 4 and earlier versions. After the data compression is implemented, the list with advantages of sharpSerializer can be extended with a point "very, very small size of the produced file". :-)

From the Author

There is another article about XML serialization with sharpSerializer:

Of course, you are encouraged to make your own tests with sharpSerializer Framework. If you like this article, please rate it, if not - tell me why in the comment field below. ;-)


  • October 6, 2010 - First release


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


About the Author

Pawel idzikowski
Software Developer (Senior) Polenter - Software Solutions
Germany Germany
I'm C# developer from Cologne, Germany. Here I owe a small software company. My hobby is general optimization - natural talent of all lazy people Wink | ;-)

You may also be interested in...

Comments and Discussions

Questionhelp me ,please.
huzhenglin3-Oct-14 0:27
memberhuzhenglin3-Oct-14 0:27 
var serializer = new SharpSerializer();
System.Windows.Shapes.Path path = new System.Windows.Shapes.Path() { Data = new LineGeometry { StartPoint = new Point(0, 0), EndPoint = new Point(100, 100) } };
serializer.Serialize(path, filename);
var fakeObj = serializer.Deserialize(filename);//throw exception here,why?


AnswerRe: help me ,please.
Pawel idzikowski3-Oct-14 2:01
memberPawel idzikowski3-Oct-14 2:01 
At the first sight the point does not have a default constructor. Please refer to the following article for more info:
How to serialize data effectively? Custom serialization of Bitmap, Cursor, Icon, Font, and other objects without a default constructor with sharpSerializer[^]
QuestionAlternative to Reflection
kiquenet.com21-Oct-13 20:37
memberkiquenet.com21-Oct-13 20:37 
A fast alternative to reflection for creating objects and accesing properties and fields[^]

GeneralOne more question
Dewey18-Nov-10 9:17
memberDewey18-Nov-10 9:17 
To send binary data to the server, I need to convert the class to binary, but there appears to be no method that serializes to a byte array.

How can you get the byte array directly?
GeneralRe: One more question - some success
Dewey18-Nov-10 9:38
memberDewey18-Nov-10 9:38 
I tried this

<br />
var ser = new Polenter.Serialization.SharpSerializer(true);<br />
System.IO.MemoryStream ms = new System.IO.MemoryStream();<br />
ser.Serialize(MyClass, ms);<br />
byte[] ba = ms.ToArray();<br />
// Now pretending to send the byte array to the server, and upon receiving<br />
object newClass = ser.Deserialize(new System.IO.MemoryStream(ba)); // DIES here<br />

GeneralRe: One more question - some success
Pawel idzikowski18-Nov-10 10:13
memberPawel idzikowski18-Nov-10 10:13 
You need to serialize your class including AssemblyVersion, Culture and PublicKeyToken.
As Default they will not be included in the type name. (it looks clean in xml, but the drawback is as you see, sorry)

// This class is serialized
var myClass = new MyClass() {Age = 42, Name = "koko"};
// binary settings with defining AssemblyVersion, Culture and PublicKeyToken
var settings = new Polenter.Serialization.SharpSerializerBinarySettings();
settings.IncludeAssemblyVersionInTypeName = true;
settings.IncludeCultureInTypeName = true;
settings.IncludePublicKeyTokenInTypeName = true;
//the rest as in your example
var ser = new Polenter.Serialization.SharpSerializer(settings);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ser.Serialize(myClass, ms);
byte[] ba = ms.ToArray();
MyClass newClass = (MyClass)ser.Deserialize(new System.IO.MemoryStream(ba));

There is no problem with your example in the full .NET Framework.
AFAIK It concerns only serialization in silverlight.
GeneralRe: One more question - some success
Dewey18-Nov-10 12:28
memberDewey18-Nov-10 12:28 
This works, but the deserialized object's fields are empty.

Does this only work with properties?
GeneralRe: One more question - Complete success
Dewey18-Nov-10 12:40
memberDewey18-Nov-10 12:40 
Yes, I changed to properties { get; set; }, and it works great.

Thanks for your help!
GeneralSend binary to server
Dewey17-Nov-10 21:08
memberDewey17-Nov-10 21:08 
Is it possible to binary serialize a class in Silverlight, and send it to the server to be deserialized the clase in the full .net framework on the server?
GeneralRe: Send binary to server
Pawel idzikowski18-Nov-10 6:24
memberPawel idzikowski18-Nov-10 6:24 
Yes, it's possible Wink | ;-)
GeneralRe: Send binary to server
Dewey18-Nov-10 9:02
memberDewey18-Nov-10 9:02 
NewsBusiness Applications Guru Max Dolgicer Speaks at India's Most Influential Business Technology Event
swagat barman24-Oct-10 19:51
memberswagat barman24-Oct-10 19:51 
Max Dolgicer has more than 25 years of management and technical experience in development and support of Business applications, software products and systems internals. An internationally recognized expert, Max is Technical Director and principal at International System Group, (ISG) Inc a leading consulting firm that specializes in design, development and integration of large-scale distributed applications using leading edge Middleware technologies. Max is coming to Business Technology Sumit 2010 ( to speak about all things SOA, on 12 November at the NIHANS Convention Center in Bangalore. At the summit, Max covers the following sessions:

* Managing the SOA Evolution:
once a company has completed initial SOA projects, the number of deployed services increases such that the key question no longer is how to build services, but rather how to efficiently govern the development and operation of services on an enterprise scale. The focus of SOA shifts to reusability, securing how a growing number of clients access the services, and assuring that Service Level Agreements (SLAs) are met, to name just a few issues. At this point companies run the danger that a "free for all" environment proliferates, and the benefits of SOA cannot be realized. The key is to introduce SOA governance before services spin out of control. Managing the evolution of SOA into the cloud with the correct governance is the next challenge. This keynote will address: typical categories of SOA projects, how SOA Maturity Models and governance relate, and how SOA governance needs to be extended when we move applications into the cloud

* A ROI Calculator for SOA: let the Numbers Do the Talking: there are many pro and very few con arguments from an engineering perspective that make us believe that SOA is a superior approach for most application development and integration projects. However, nowadays we typically won't get away with brilliant technical arguments to justify the transition to SOA. In most cases we will have to convince the CFO that there is a positive bottom line result. This presentation outlines a ROI model for application development based on service reusability in a SOA. It describes how the cost effect of reuse can be calculated during the development and the maintenance cycle of a portfolio of service oriented business applications. The model is based on metrics that have been widely accepted throughout the IT industry. The model will then be illustrated by a project where multiple business applications have been developed within a SOA that employs a foundation of reusable services. This presentation will show an overview of a project that is used as an example, a popular ROI model that is the basis for the ROI calculation, and the application of the model to determine concrete monetary savings.

* Defining a SOA Roadmap Based on SOA Maturity Model: once a company has completed initial SOA projects, the number of deployed services increases and the key question no longer is how to build services, but rather how to efficiently manage the development and operation of services on an enterprise scale. What is needed is a concise roadmap that guides the evolution of SOA such that IT can deliver the right value at the right time to the business. This roadmap has to address multiple dimensions of IT: architecture, development processes, applications, information, etc. This presentation will outline a model against which the degree of service oriented maturity of an organization can be assessed, and a process (i.e. the roadmap) for assessing the current and desired degree of service maturity of an organization and for developing a plan for how to get to the target state. This presentation will show: what SOA Maturity Models exist today?, walkthrough of the levels and key elements of each level, developing a custom SOA Roadmap and project example for mapping a Maturity Model to a Roadmap.

* Service Oriented Integration (SOI):
doing Integration the Right Way: IT managers have been under increasing pressure to migrate a portfolio of independent “stovepipe” applications to an integrated set of business services that can be aligned with changing business requirements and support new business processes faster and with reduced cost. Today, corporations have to choose from a number of integration products (e.g. Enterprise Service Buses) that have quite different capabilities, never mind different architectures and standards. This seminar starts with a comparison of SOA and event based architectures and then outlines the key issues and guidelines that architects should consider when defining an integration architecture based on services. The key point of the seminar is a case study that illustrates how SOA concepts have been applied in a real project. It explains the key architectural and design decisions that produced an integration architecture and a set of services that were reused beyond one particular project. This presentation will show: drivers for Service Oriented Integration (SOI), comparing SOA to Event-Driven Architecture (EDA), how to evolve from Enterprise Application Integration (EAI) to SOA/EDA to SOI, and applying SOI in a project example.

Max is a contributing editor for Application Development Trends magazine and recognized instructor and presents extensively at major industry conferences including Gartner's Web Service and Application Integration conferences, Sys-Con's Web Services, XMLOne, XMLDevCon, JavaDevCon, e-Business Integration, Java Expo, Component Development, GIGA's Middleware Choices, and Comdex.

Follow the summit on Twitter, here: and LinkedIn:

Saltmarch Media
Ph: +91 80 4005 1000
GeneralSilverlight Serializer performance in your test harness
michael_john_talbot9-Oct-10 1:47
membermichael_john_talbot9-Oct-10 1:47 
I thought I'd run your test for my SilverlightSerializer class and see if I got similar results. SilverlightSerializer is a reflection based serializer with a compact binary output - it hence has similar limitations to other reflection based serializers.

The results look pretty good:

Starting serialization with BinaryFormatter
Stopped after 2828ms
Starting serialization with SilverlightSerializer

Stopped after 2986ms

Starting serialization with SharpSerializer (Burst)
Stopped after 4737ms
Starting serialization with SharpSerializer (SizeOptimized)
Stopped after 5336ms
Starting serialization with SharpSerializer XML
Stopped after 6055ms
Starting deserialization with BinaryFormatter
Stopped after 8841ms
Starting deserialization with SilverlightSerializer

Stopped after 2068ms

Starting deserialization with SharpSerializer (Burst)
Stopped after 12275ms
Starting deserialization with SharpSerializer (SizeOptimized)
Stopped after 3596ms
Starting deserialization with SharpSerializer XML
Stopped after 21845ms

The file size produced is 6MB. I would normally use SharpZipLib to compress this further, obviously that's a trade off of time versus size and usually depends on whether you are sending serialized objects across the wire.

If I run SharpZip on the byte array before writing it to the file the time to serialize increases to 4096ms but the file size drops to a tiny 30k!!

You can find the details of the serializer here: Silverlight Serializer[^]. I had to use .NET4 as a target platform.

modified on Saturday, October 9, 2010 8:09 AM

GeneralRe: Silverlight Serializer performance in your test harness
Pawel idzikowski9-Oct-10 3:15
memberPawel idzikowski9-Oct-10 3:15 
hi Mike, however sharpSerializer in my results is better than in yours, but your SilverlightSerializer kicks the ass!
I have compared the outputs, because i thought, your class is a fake which makes doNothing 10000 times Smile | :) but it really works.
There are only two things to fix:
- deserialized property SimpleDecimal of type decimal is 0, should be 17.123
- in the SingleArrayOfObjects the fourth element is Int32 with a value of 2, it should be of type HelloWorldApp.BusinessObjects.SimpleEnum with a value of Three

After these fixes You're the best Cry | :((

Starting serialization with BinaryFormatter
Stopped after 2059ms

Starting serialization with SilverlightSerializer
Stopped after 2106ms
Starting serialization with SharpSerializer (Burst)
Stopped after 2978ms
Starting serialization with SharpSerializer (SizeOptimized)
Stopped after 3757ms
Starting serialization with SharpSerializer XML
Stopped after 3798ms

Starting deserialization with BinaryFormatter
Stopped after 7821ms
Starting deserialization with SilverlightSerializer
Stopped after 1557ms

Starting deserialization with SharpSerializer (Burst)
Stopped after 10080ms
Starting deserialization with SharpSerializer (SizeOptimized)
Stopped after 2589ms
Starting deserialization with SharpSerializer XML
Stopped after 16572ms
GeneralRe: Silverlight Serializer performance in your test harness
michael_john_talbot9-Oct-10 3:32
membermichael_john_talbot9-Oct-10 3:32 
Ah, I ran the test to see if something didn't work, but didn't then do a good enough job of identiying a fault! Thanks for that - I'll get on it!

Not sure if this is affecting your stuff, but caching the PropertyInfos etc was the big performance improvement for me...
GeneralRe: Silverlight Serializer performance in your test harness
michael_john_talbot9-Oct-10 6:02
membermichael_john_talbot9-Oct-10 6:02 
Right, found and fixed those two faults! Wasn't parsing my Enums properly (worked ok if you weren't storing them in an object of course!) and totally missed Decimal Smile | :)
GeneralRe: Silverlight Serializer performance in your test harness
Pawel idzikowski9-Oct-10 10:07
memberPawel idzikowski9-Oct-10 10:07 
I give up. there is type caching in my framework but further caching is not possible unless I refactor the whole system. In your Serializer there are only two layers - reading and object creating. in mine there are three - reading, creating internal properties, and creating objects from these properties. it's easier to read for a newbie but it's just heavier. checksum control is so easy but genial and this amazing ThreadStaticAttribute, You've used an alien technology... OMG | :OMG:
GeneralRe: Silverlight Serializer performance in your test harness
michael_john_talbot9-Oct-10 11:25
membermichael_john_talbot9-Oct-10 11:25 
Yeah, ThreadStatic was a real boon - I was desperately trying to work out how to use Thread Local Storage (which was necessary, but messy), then I spotted they'd built it right in!
GeneralRe: Silverlight Serializer performance in your test harness
michael_john_talbot5-Aug-11 10:28
membermichael_john_talbot5-Aug-11 10:28 
Finally managed to post my updated version of SilverlightSerializer which has much improved performance due to dynamic generic delegates that work almost as fast as using the native calls.[^]
General[Serializable] and [ExcludeFromSerialization]
Paulo Zemek7-Oct-10 5:25
memberPaulo Zemek7-Oct-10 5:25 
I saw in the article the thing about [Serializable] and, seeing the[^] I saw the ExcludeFromSerialization attribute.

Well, I must say that the [Serializable] attribute is needed for security. What happens if you serialize a ReaderWriterLock, deserializes it and then tries to use it? That will be a problem with any object that holds unmanaged resources.

And, the ExcludeFromSerialization attribute is redundant. There is already the NonSerialized attribute.
GeneralRe: [Serializable] and [ExcludeFromSerialization]
Pawel idzikowski7-Oct-10 9:41
memberPawel idzikowski7-Oct-10 9:41 
hi Paulo,

I have never thought of serializing of ReaderWriterLock - it can't work anyway. Sometimes i get feedback, that sharpSerializer can't serialize whole Windows Forms or other Controls. It shouldn't. The main goal of sharpSerializer is serializing of business objects. Business objects should not have any logic, only state. You can call them entities, models, etc. Their state should be serialized/hibernated not behavior.

You're right, sharpSerializer isn't secure. Serialized stream could be easily tampered, safe objects could be replaced with the bad ones and then deserialized. Safe serialization is not a goal of sharpSerializer either. If you need secure serialization you have to wrap the serialized stream in a secure envelope. One of the future milestones is implementing of encryption, signing or checksum control to ease this process.

NonSerialized attribute - it's associated with the binary serialization. It could mistake the user. I needed an attribute which is neutral for XML and binary. XML and binary use the same algorithm, only different output. That's why I took something new. The other thing - Silverlight supports no BinaryFormatter, and my assumption - NonSerializedAttribute could be not supported either as redundant.

Thanks for your deep analysis and comment
GeneralRe: [Serializable] and [ExcludeFromSerialization]
Paulo Zemek7-Oct-10 12:58
memberPaulo Zemek7-Oct-10 12:58 
Maybe I was not clear enough. When I talked about security, I was not meaning any type of encryption.
I mean that, even if the [Serializable] attribute is annoying, it exists for a reason. The .Net team could've created all objects serializable by default, only making objects non serializable if explicity set as non-serializable or if they contained non-serializable references, but they chose the "explicit" path. So, if you don't know, your object is not serializable.

I know that marking all your objects as [Serializable] can be annoying, but that's the .Net standard, and it avoids users serializing objects like the ReaderWriterLockSlim, because it is not marked as Serializable. That's why I used that object as example. I don't expect you to serialize a ReaderWriterLockSlim but, if you try, what should happen? In .Net standard, an exception should be thrown, because the object is not serializable.

As for the NonSerialized attribute, I don't know if you can use the original attribute or not, but I think that, if possible, is good to use the already existing one, or at least try to use the same name, to keep the standard.
GeneralRe: [Serializable] and [ExcludeFromSerialization]
Pawel idzikowski7-Oct-10 19:59
memberPawel idzikowski7-Oct-10 19:59 
Paulo Zemek wrote:
marking all your objects as [Serializable] (...) avoids users serializing objects like the ReaderWriterLockSlim

it's like a driving a car, you can throttle gas for all cars not to exceed an allowed speed, but you can trust, a driver drives as quick as it's allowed at the moment. In this case I have choosen the second case.

As for the NonSerialized attribute (...) I think that, if possible, is good to use the already existing one

Yes, me too. But [NonSerialized] or [XmlIgnore]? Which one is better? That's why I choosed a brand new attribute. If it's not optimal, you can override the default PropertyProvider using your custom rules.

QuestionCould you briefly detail how it works internally?
I'm Chris7-Oct-10 4:45
memberI'm Chris7-Oct-10 4:45 
Could you give some insight about how your lib works? I had a look at your website but it doesn't give much more. And I'm a bit lazy about reading the code Sniff | :^) ...

I assume you use reflection to access the properties of the object to serialize, right? If so, I'm surprised you don't suffer more in terms of delay... And, still, if so, does your framework cache the object's "definition" so that, if it has to serialize another instance of the same class, it doesn't need to use reflection again?

(for info, we've built as well a custom serialization framework, with a slightly different goal in mind. It goes much faster and produces much more optimized serialzed bits, but at the prices of defining custom Serialize method for each class we want to really optimize - for other class, we rely on reflection and/or the framework serialization).


Chris - Infrastructure and Security Supervision, Event Correlation

AnswerRe: Could you briefly detail how it works internally?
Pawel idzikowski7-Oct-10 5:18
memberPawel idzikowski7-Oct-10 5:18 
hi Chris, only between us "lazy boys"Wink | ;-) - yes, it uses reflection and the types are cached during building of Property classes.

Of course the framework could be faster if not the reflection. the price of building custom serializers was to high for me. I prefer a simple "fire & forget" solution. If the system stutters, I buy more memory or better cpu Wink | ;-)

See the classes PropertyFactory, PropertyProvider, TypeInfo to see how the reflection works.

To see how custom writer is build - first take a look at the BurstBinaryWriter, then on the SizeOptimizedBinaryWriter and then write your own writer by making an instance of IBinaryWriter and passing it to the constructor of BinaryPropertySerializer.

GeneralMy vote of 5
Dave Cross6-Oct-10 21:44
memberDave Cross6-Oct-10 21:44 
Well crafted, lots of references, topical and useful subject.
GeneralRe: My vote of 5
Pawel idzikowski6-Oct-10 23:34
memberPawel idzikowski6-Oct-10 23:34 
hi Dave, thanks for your support!

GeneralMy vote of 5
Michal Stehlik6-Oct-10 7:39
memberMichal Stehlik6-Oct-10 7:39 
Very nice, this is what I want, but Smile | :) what about memory usage, there are several trial tools for measure memory usage (e.g. dotTrace 3.5 Memory). Please just put some memory statistic, because sometimes speed is not only one condition to use library. Anyway, very interesting reading, Thanx
GeneralRe: My vote of 5
Pawel idzikowski6-Oct-10 8:23
memberPawel idzikowski6-Oct-10 8:23 
hi Michal, thanks for your vote and nice words. My sensitivity about memory consumption ist something of binary. If everything works - is 1 and I trust, that the Garbage Collection do the rest, if OutOfMemoryException occures is 0 Smile | :)

I'll try the dotTrace but as a newbie in profiling, I don't know if my interpretation would be right.

GeneralOther Options
Jeremy Likness6-Oct-10 7:33
memberJeremy Likness6-Oct-10 7:33 
You can also serialize directly using the BinaryWriter, you just have to supply your own methods for serializing the parts. I wrote an open source project that uses binary serialization to create an object-oriented database - it supports binary serialization of most parts out of the box, and others you can supply an interface to provide hints. It's at:
Jeremy Likness (@JeremyLikness)
Blog: C#er : IMage

GeneralRe: Other Options
Pawel idzikowski6-Oct-10 8:45
memberPawel idzikowski6-Oct-10 8:45 
hi Jeremy, I've seen your project and my first impression - your site looks very tidy and the best is - it has documentation - a thing which not every project has Smile | :)

Reading it I assume, your framework is very lightweight, just something for WP7. But tell me, if I need a "custom serializer" for your framework to serialize the RootContainer (an example from this article) - how much effort would be needed, how many lines of code to make it? Then we could make another article comparing Sterling with SharpSerializer Wink | ;-)

thanks for your comment
GeneralRe: Other Options
Jeremy Likness6-Oct-10 8:54
memberJeremy Likness6-Oct-10 8:54 
It's actually both for Windows Phone 7 and Silverlight. The idea was to keep it lightweight but extensible, and the difference between a straight serializer and this is the emphasis on the ability to generate keys and indexes to build a relational object-oriented database.

The custom serializer only needs to be in place to serialize things it doesn't know about.

So let's say you have


Etc. In this case, you're fine. Sterling knows how to recurse subclasses and serialize their properties.

If, however, you had

struct something

Or were using a construct that is a value type in the framework that is not directly supported by the binary writer, you'd want to write a serializer for it. The serializer is by type, so again, if your Rootcontainer has 500 items that are ints, doubles, etc, and nested classes, but then 1 struct type called "foo" then you would just register a serializer for "foo" and be done - and the serializer is passed the binary stream for you to write to however you like.

The reference application on the Silverlight side is the best way to see this - it takes awhile to spin some CSV data into the local database but then demonstrates the querying/etc.
Jeremy Likness (@JeremyLikness)
Blog: C#er : IMage

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 7 Oct 2010
Article Copyright 2010 by Pawel idzikowski
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid