Archive

Posts Tagged ‘Serialization’

Binary Serialization – Controlling it manually

March 28, 2010 Leave a comment

Hi all, Just a quick post on how to control serialization manually. If you need full control of the process implement ISerializable. In the GetObjectData method add the field / properties ect you want to the dictionary then create a constructor to pull them out again.

using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace ISerializableDemo
{

    [Serializable]
    public class Customer : ISerializable
    {
        private readonly string name;
        private readonly string address;

        public Customer(string name, string address)
        {
            this.name = name;
            this.address = address;
        }

        protected Customer(SerializationInfo info, StreamingContext context)
        {
            this.name = info.GetString("Name");
            this.address = info.GetString("Address");
        }

        public string Address
        {
            get { return address; }
        }

        public string Name
        {
            get { return name; }
        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Name",name);
            info.AddValue("Address",address);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            
            Customer c1 = new Customer("Blair","25 Test Avenue Australia");
            
            MemoryStream stream = new MemoryStream();

            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, c1);

            stream.Position = 0;
            Customer c2 = (Customer) formatter.Deserialize(stream);

            Console.WriteLine(c2.Name + " - " + c2.Address);
            Console.ReadKey();

        }
    }
}
Hope this helps.
Blair….
Categories: Development Tags: , , ,

Binary Serialization

March 23, 2010 Leave a comment

Just the facts:

  • Serializes all fields unless otherwise specified
  • Only serializes fields
  • Serializes both private and public fields
  • Requires types be annotated with [Serializable]
  • If fields are not serializable an exception is thrown
  • You can further control serialization and stop fields from being serialized by using [NonSerialized] attribute on the field.
  • Versioning is not great
  • Great from serializing object graphs
  • Very fast

We are going to cover the basics and will add future posts to cover more detailed information.

Here is some code for discussion.

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace BinarySerialization
{

    [Serializable]
    public class Student
    {

        private readonly int id;
        private readonly string name;
        private readonly DateTime birthdate;
        private readonly IList<Course> courses;
       
        [NonSerialized]
        private int age;

        public Student(int id, string name, DateTime birthdate)
        {
            this.id = id;
            this.name = name;
            this.birthdate = birthdate;
            this.age = CalculateAge(birthdate);
            this.courses = new List<Course>();
        }

        private static int CalculateAge(DateTime _birthdate)
        {
            return (DateTime.Now - _birthdate).Days / 365;
        }

        [OnDeserialized]
        public void OnDeserialized(StreamingContext context)
        {
            this.age = CalculateAge(birthdate);
        }

        public int Age
        {
            get { return age; }
        }

        public DateTime Birthdate
        {
            get { return birthdate; }
        }

        public int Id
        {
            get { return id; }
        }

        public string Name
        {
            get { return name; }
        }

        public void AddCourse(Course c)
        {
            this.courses.Add(c);
        }

        public int CoursesTaken
        {
            get
            {
                return this.courses.Count;
            }
        }
    }

    [Serializable]
    public class Course
    {
        private readonly string name;

        public Course(string name)
        {
            this.name = name;
        }

        public string Name
        {
            get { return name; }
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                Student studentToSerialize = new Student(1, "Blair Davidson", new DateTime(1981,6,14));
                studentToSerialize.AddCourse(new Course("Maths"));

                Console.WriteLine("Id: {0}, Name:{1}, Age: {2} Courses Taken: {3}", studentToSerialize.Id,
                                  studentToSerialize.Name, studentToSerialize.Age,
                                  studentToSerialize.CoursesTaken);

                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(memoryStream, studentToSerialize);

                memoryStream.Position = 0;
                Student deSerializedStudent = (Student)formatter.Deserialize(memoryStream);

                Console.WriteLine("Id: {0}, Name:{1}, Age: {2} Courses Taken: {3}", deSerializedStudent.Id,
                                 deSerializedStudent.Name, deSerializedStudent.Age,
                                 deSerializedStudent.CoursesTaken);

            }

            Console.ReadKey();
        }
    }
}

You can also see that age is not serialized as it is a calculated field. We also use the Deserialized event and recalculate the age when we deserialize the object.

I will be covering more shortly.

Blair…

Categories: Development Tags: , , ,