27 Jun 2007

Serialize - Deserialize Classes

Το παρακάτω Class μπορείτε να το χρησιμοποιήσετε για να κάνετε Serialize και Deserialize ένα Class. Είναι πολύ χρήσιμο αν θέλετε να αποθηκεύετε τα Classes είτε στο δίσκο είτε στη βάση δεδομένων. Παρακάτω έχω το Class και ένα παράδειγμα.

#region Using directives
using System;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters.Binary;
#endregion


[Serializable()]
public class Serialization<T>
{

 public string ToXml()
 {
  StringWriter Output = new StringWriter(new StringBuilder());
  string Ret = "";

  try
  {
   XmlSerializer s = new XmlSerializer(this.GetType());
   s.Serialize(Output, this);

   // To cut down on the size of the xml being sent to the database, we'll strip
   // out this extraneous xml.

   Ret = Output.ToString().Replace("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "");
   Ret = Ret.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", "");
   Ret = Ret.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "").Trim();
  }
  catch (Exception) { throw; }

  return Ret;
 }

 public T FromXml(string pXmlizedString)
 {
  try
  {
   XmlSerializer xs = new XmlSerializer(this.GetType());

   MemoryStream memoryStream =
            new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
   XmlTextWriter xmlTextWriter =
            new XmlTextWriter(memoryStream, Encoding.UTF8);

   return (T) xs.Deserialize(memoryStream);               

  }
  catch (Exception) { throw; }
 }

 public T CloneObject(T obj)
 {
  T retObj;

  // Create a memory stream and a formatter.
  MemoryStream ms = new MemoryStream(1000);
  BinaryFormatter bf = new BinaryFormatter();

  // Serialize the object into the stream.
  bf.Serialize(ms, obj);           
  // Position streem pointer back to first byte.
  ms.Seek(0, SeekOrigin.Begin);
  // Deserialize into another object.
  retObj = (T)bf.Deserialize(ms);
  // Release memory.
  ms.Close();

  return retObj;
 }

 /// <summary>
 /// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
 /// </summary>
 /// <param name="characters">Unicode Byte Array to be converted to String</param>
 /// <returns>String converted from Unicode Byte Array</returns>
 private String UTF8ByteArrayToString(Byte[] characters)
 {
  UTF8Encoding encoding = new UTF8Encoding();
  String constructedString = encoding.GetString(characters);
  return (constructedString);
 }

 /// <summary>
 /// Converts the String to UTF8 Byte array and is used in De serialization
 /// </summary>
 /// <param name="pXmlString"></param>
 /// <returns></returns>
 private Byte[] StringToUTF8ByteArray(String pXmlString)
 {
  UTF8Encoding encoding = new UTF8Encoding();
  Byte[] byteArray = encoding.GetBytes(pXmlString);
  return byteArray;
 }
}

Το παραπάνω είναι όλο το Class. Γενικά χρησιμοποιεί Generics έτσι ώστε να παίζει με οτιδήποτε τύπο Class, αρκεί φυσικά το Class το οποίο θέλουμε να αποθηκεύσουμε να είναι Serializable.

Παράδειγμα: 


[Serializable()]
public class Customer : Serialization<Customer>
{
  private string _FirstName;
  private string _LastName;

  public string FirstName
  {
   get { return _FirstName; }
   set { _FirstName = value;}
  }
 
  public string LastName
  {
   get { return _LastName; }
   set { _LastName = value;}
  }
 
  public Custοmer() {}

  public Customer(string firstName, string lastName)
  {
   _FirstName = firstName;
   _LastName = lastName;
  }
}

Το παραπάνω είναι ένα απλό Class με δύο Properties (Firstname και Lastname). Θα μπορούσαμε τώρα μέσα απο το πρόγραμμα μας να δώσουμε :

    Customer cus = new Customer("George","Chatzimanolis");
    //κάνουμε Serialize το Class σε ένα string   
    string Sres = cus.ToXml();

    //Κάνουμε Deserialize το string σε ένα Object Customer
   Customer newCus = new Customer();
   newCus = newCus.FromXml(Sres);

Serialization.cs (2.95 kb)

Categories: Programming

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading