Home > Just Blog'ing, Tips-n-Tricks > Binary Serialization with Micro Framework

Binary Serialization with Micro Framework

November 17th, 2008 Elze Leave a comment Go to comments

Today I came acros this  post on the GHI Electronics forum:

I’m developing my first application with EM, but sometimes i switch from happyness  Grin to sadness  Cry, this is why:
- Read/Write method in FileStream class of EMLibrary accept only bytes array, but what if I have to write/read int/float/long arrays ?
In C++ it easy: fwrite(&AnyKindOfData, DataLenght, Elements), 
InsertValueIntoArray and ExtractValueFromArray of Utility class work only for unsigned types but not for float, and of course it is less that the best way to do this job, some idea ?

You can use binary serialization for this. As not much information is available on the web about this I’ll try to shed some light on the subject.

What is serialization?

When you "Serialize" an object you make a full description of it so that it can be restored later. In this description all fields of the object are stored (Even private, protected and internal fields). With this description you can regenerate the object later. You could’t compare it to the transporter in the Star Trek TV series. When you here "Beam me up Scotty!" the person on the far far away planet get beamed up atom by atom and then rebuild on the ship. 

When I search on google I find System.Xml.Serialization and BinaryFormatter(), will this work?

I can be short.. No, XML serialization is not available on the Micro Framework and Binary serialization goes different then on the desktop and compact .NET versions.

How can I serialize then?

Through the Reflection class. This class is used to get information of classes and objects in C#. With .NET Micro Framework this class has two extra methods: Reflection.Serialize() and Reflection.Deserialize(). These methodes handle the serialization. The binary serialized byte array that’s generated can be stored in a file, send trough a network, with RF, etc.. One drawback is that it’s not compatible with the desktop and compact .NET versions of binary serialized objects. 

Example program

To help you on you’re way I made an simple program that stores an String array and displays it on a text control. 

Reflection.Serialize has trouble storing arrays. We can bypase this by making a Serializable class that contains a String[] field. Creating a Serializable class is easy, just create a class as you would normaly do and add "[Serializable]" before it. All basic classes in C# are made Serializable so you can use it on most objects. The source for the Serializable class is displayed below:
 

/// <summary>
/// Simple Serializable class to showcase Reflection.Serialize
///
/// Were using this class becouse Reflection.Serialize doesn’t
/// handle String[] objects. If you want to make you’re class
/// serializable make sure you give it the "Serializable" attribute
/// like I did below.
/// </summary>
[Serializable]
public class SerializeMe
{
        /// <summary>
        /// This variabele stores the String[] array passed at
        /// construction.
        /// </summary>
        private String[] Content;

        /// <summary>
        /// Return the String[] array glued together.
        /// </summary>
        /// <returns>String</returns>
        public String Out()
        {
                String ret = "";

                foreach (String s in this.Content)
                {
                        ret += s;
                }

                return ret;
        }

        /// <summary>
        /// Constructor
        /// </summary>
        public SerializeMe(String[] Content)
        {
                // Store Text array
                this.Content = Content;
        }

}

 

Now we can do some serialization. For this example project I simply use the standard program that’s generated when you create a Window Program for Micro Framework.

 

// This is the object to serialize
SerializeMe SerializeMeObject = new SerializeMe(new String[] { "One", "Two", "Three" });

Here the object is created that we want to serialize. The SerializeMe.Content field now holds the String[] "One","Two","Three".

 

// Now serialize it
byte[] Serialized = Reflection.Serialize(SerializeMeObject, typeof(SerializeMe));
  

Here the object is created using Reflection.Serialize(). The first parameter is the object you want to serialize. The second parameter indicates the type of object that’s serialized. You have to give the exact type! E.g. if you want to serialize a Canvas control you can’t pass it’s base class Panel. The function returns a byte array. This array you can send, save or anything other you want to do with it.
 

// Get size of serialized SerializeMe object
String ObjectSize = Serialized.Length.ToString();

// Now restore object,
SerializeMe newSerializeMeObject = (SerializeMe)Reflection.Deserialize(Serialized, typeof(SerializeMe));

  

 

Here the size of the serialized object is stored in a string and finaly the object is recreated. This is done with Reflection.Deserialize(). The first parameter is the byte array thats generated with Reflection.Serialize(). The second parameter is the type that must be deserialized. It returns the deserialized object. You have to cast the result to let C# know the object that is returned is indeed a SerializeMe object.
 

Download example program

This concludes my description of serialization on the .NET Micro Framework. Serialization is more than I described above. But that goes beond the scope of this article. You can read more about this subject in the book from Jens Kühner called "Expert .NET Micro Framework" (I’m not affiliated with him it’s just a good book).

The full Visual Studio 2008 solution can be downloaded here: MF_SerializeExample.zip

Enjoy!

 

 

 

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • NuJIJ
  • Technorati
  • Yahoo! Bookmarks
  1. Wertugo
    October 11th, 2010 at 19:00 | #1

    In my one project, i need communicate desctop-win32 full .net framework, win-mobile cf 3.5 .net framework and .Net Micro Framework device. Applications data – Serialize Data from Micro Framework. But Full, Compact Framework BinarySerializer is different that Serializer in Micro Framework. I used Microsoft source code from Microsoft.SPOT.Debugger.DLL.

    It place in Micro Framework Porting Kit 4.0, path:
    …MicroFrameworkPK_v4_0\Framework\Debugger\BinaryFormatter.cs

  1. No trackbacks yet.