Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Posts Tagged ‘serialize’

Serialize and Zip in one step

Posted by JP on January 1, 2011

Once in a while it is needed that we need to serialize a particular object and zip it.  Here I am combining both the operations into one method.  The associated unit tests are also provided.

Source

public class SerializeNZip
{
    public void SerializeAndZip(object obj, string zipFileName)
    {
        XmlSerializer serializer = new XmlSerializer(obj.GetType());
        MemoryStream stream = new MemoryStream();
        serializer.Serialize(stream, obj);
        stream.Position = 0;

        FileStream fileStream = File.Create(zipFileName);
        GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Compress);

        byte[] buffer = new byte[4096];
        int numRead;
        while ((numRead = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            gzipStream.Write(buffer, 0, numRead);
        }

        gzipStream.Dispose();
        fileStream.Dispose();
    }

    public T UnzipAndDeserialize<T>(string zipFileName)
    {
        FileStream compressedStream = new FileInfo(zipFileName).OpenRead();
        MemoryStream destinationStream = new MemoryStream();
        GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress);
        byte[] buffer = new byte[4096];

        int numRead;

        while ((numRead = gzipStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            destinationStream.Capacity += numRead;
            destinationStream.Write(buffer, 0, numRead);
        }

        gzipStream.Dispose();
        compressedStream.Dispose();

        destinationStream.Position = 0;

        XmlSerializer deserializer = new XmlSerializer(typeof(T));
        T result = (T)deserializer.Deserialize(destinationStream);

        return result;
    }
}

Invoking

[TestMethod()]
public void UnzipAndDeserialize_List_Test()
{
    SerializeNZip target = new SerializeNZip();
    List<Person> list = new List<Person>();
    list.Add(new Person() { Id = 1, Name = "TestName1" });
    list.Add(new Person() { Id = 2, Name = "TestName2" });

    target.SerializeAndZip(list, "c:\\ser2.zip");

    List<Person> actual = target.UnzipAndDeserialize<List<Person>>("c:\\ser2.zip");

    Assert.IsNotNull(actual);
    Assert.AreEqual(2, actual.Count);
    Assert.AreEqual(1, actual[0].Id);
    Assert.AreEqual(2, actual[1].Id);
    Assert.AreEqual("TestName1", actual[0].Name);
    Assert.AreEqual("TestName2", actual[1].Name);
}

public class Person
{
    public int Id
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }
}

Advertisements

Posted in C# | Tagged: , , , | Leave a Comment »

How to Serialize a non-serializable class in .Net?

Posted by JP on October 13, 2010

Although we can use BinarySerializer to serialize objects, the constraint is that we have to mark the class as [Serializable].

This could not be feasible as we have to deal with different kinds of objects which contains other types.

The Solution

Use XmlSerializer for the purpose.

  private void Button_Click(object sender, EventArgs e)

        {

            Book book = new Book();

            book.Title = "Rich Dad Poor Dad";

            book.ReleaseDate = new DateTime(2000, 1, 1);

            book.Author = new Author() { Name = "Robert Kiyosaki", Email = "rkiyosaki@richdad.com" };

 

            book.AuthorList = new List<Author>();

            book.AuthorList.Add(book.Author);

            book.AuthorList.Add(book.Author);

 

            book.Price = 6.9f;

 

            List<Book> books = new List<Book>() { book, book };

 

            // Serialize

            SerializeToXML(books);

 

            // Deserialize

            books = DeserializeFromXML();

        }

 

        public void SerializeToXML(List<Book> movies)

        {

            XmlSerializer serializer = new XmlSerializer(typeof(List<Book>));

            TextWriter textWriter = new StreamWriter(@"C:\movie.xml");

            serializer.Serialize(textWriter, movies);

            textWriter.Close();

        }

 

        public List<Book> DeserializeFromXML()

        {

            XmlSerializer deserializer = new XmlSerializer(typeof(List<Book>));

            TextReader textReader = new StreamReader(@"C:\movie.xml");

            List<Book> movies;

            movies = (List<Book>)deserializer.Deserialize(textReader);

            textReader.Close();

 

            return movies;

        } 

 

        // Classes

 

        public class Book

        {

            public string Title

            { get; set; }

 

            public float Price

            { get; set; }

 

            public DateTime ReleaseDate

            { get; set; }

 

            public Author Author { get; set; }

 

            public List<Author> AuthorList { get; set; }

        }

 

        public class Author

        {

            public string Name { get; set; }

            public string Email { get; set; }

        }

Posted in C# | Tagged: , | Leave a Comment »