Showing posts with label Serilization. Show all posts
Showing posts with label Serilization. Show all posts

XmlSerializer : Entity Object to DataSet



Below code is used to convert Entity Object to DataSet.

  1. Create Book.cls
  2.            Serializing using XmlSerializer

  1. Create Book.cls

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

    public class Book
    {
            public string FirstName;
            public string MI;
            public string LastName;
    }
 2. Create console application for Serializing using XmlSerializer .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
using System.Data;

class Program
{
      Book objbooks;
      static void Main(string[] args)
        {
            fnserialise();
        }

        static void fnserialise()
        {
            Book objbooks = new Book();
            objbooks.FirstName = "Ram";
            objbooks.LastName = "Kumar";
            objbooks.MI = "A";
            XmlSerializer serializer;
            MemoryStream stream;
            serializer = new XmlSerializer(objbooks.GetType());
            stream = new MemoryStream();
            serializer.Serialize(stream, objbooks);
            DataSet BookData = new DataSet("Books");
             stream.Position = 0;
            BookData.ReadXml(stream);
            stream.Close();

        }

XML Serialization in .NET


XML Serialization:

By using XML serialization only public properties and fields can be serialized.

If private members are to be serialized, other serialization methods should be used (Binary Serialization and SOAP Serialization).

It requires a parameterless constructor. This constructor is called during deserialization.


Serialized form of the object does not contain any type, assembly information of the class. Only the data is stored.

Using XML serialization not all the classes can be serialized. Classes that implement IDictionary cannot be serialized. E.g. Hashtables cannot be serialized. Arrays of objects can be easily serialized. Collections can be serialized but to serialize collections certain rules must be followed.

Null values are not serialized with XML serialization. To include the null members in the serialized form IsNullable attribute should be set to true.

For example: [ XmlElement( IsNullable = true ) ]


Here ClsSample is a Serializable class. It has private and Public members,

using System;
using System.Collections.Generic;
using System.Text;

namespace XMLSerilization
{
public class ClsSample
{
private int m_TotalCount = 5;
public String m_StrWord = "Ten";

public void ReAssignMemberValues()
{
m_TotalCount = 20;
m_StrWord = "Twenty";
}
public void DisplayMemberValueAfterDeSerialization()
{
Console.WriteLine("Private member value is " + m_TotalCount);
Console.WriteLine("Public member value is " + m_StrWord);
}
}
}

Following way you can Serialize and Deserialize the objects(through files)

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace XMLSerilization
{
public class ClsXML
{
public void ToXMLSerilization(Object objToXml, string filePath)
{
StreamWriter stWriter = null;
XmlSerializer xmlSerializer;
try
{
xmlSerializer = new XmlSerializer(objToXml.GetType());
stWriter = new StreamWriter(filePath);
xmlSerializer.Serialize(stWriter, objToXml);
}
catch (Exception exception)
{
throw exception;
}
finally
{
if (stWriter != null) stWriter.Close();
}
}

public object FromXMLSerilization(string filePath, Type type)
{
XmlSerializer xmlSerializer;
FileStream fileStream = null;
try
{
xmlSerializer = new XmlSerializer(type);
fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
object objectFromXml = xmlSerializer.Deserialize(fileStream);
return objectFromXml;
}
catch (Exception Ex)
{
throw Ex;
}
finally
{
if (fileStream != null) fileStream.Close();
}
}
}
}

//Main Class

using System;
using System.Collections.Generic;
using System.Text;

namespace XMLSerilization
{
public class Program
{
static void Main(string[] args)
{
ClsSample ObjSample;
ClsXML ObjXML;
ObjSample = new ClsSample();
ObjSample.ReAssignMemberValues();
ObjXML = new ClsXML();
//Serialize
ObjXML.ToXMLSerilization(ObjSample, "c:\\XMLSerialized.TXT");
ObjSample = null;
//Deserilize
ClsSample ObjDeseialXML;
ObjDeseialXML = (ClsSample) ObjXML.FromXMLSerilization("c:\\XMLSerialized.TXT", typeof(ClsSample)) ;
ObjDeseialXML.DisplayMemberValueAfterDeSerialization();
}
}
}

Output :
Private member value is 5
Public member value is Twenty

Actually reassigned value for the private member is 20 but you are unable to get that value in deserialized object. Because XML Serilization does not keep private members information

SOAP Serialization in .NET

SOAP Serialization :

SOAP Serialization and Binary Serialization having many similar properties.

In SOAP Serialization private fields, type information including assembly, namespace, public key token information are also serialized.

Deserialization gives the same object as it was before serialization.

Serialization can be controlled to exclude a field using [NonSerialized] attribute.

[Serializable] attribute is used to mark a class as serializable.

Classes do not need to have a parameterless constructor. Because of performance issues, the constructor of the class is not called during deserialization.

Use if the serialization and deserialization platforms are not .NET.

Use if the message is sent through a firewall.

Here ClsSample is a Serializable class. It has private and Public members,


using System;
using System.Collections.Generic;
using System.Text;

namespace SOAPSerilization
{
[Serializable]
public class ClsSample
{
private int m_TotalCount = 5;
public String m_StrWord = "Ten";
public void ReAssignMemberValues()
{
m_TotalCount = 20;
m_StrWord = "Twenty";
}
public void DisplayMemberValueAfterDeSerialization()
{
Console.WriteLine("Private member value is " + m_TotalCount);
Console.WriteLine("Public member value is " + m_StrWord);
}
}
}

Following way you can Serialize and Deserialize the objects(through files)

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;

namespace SOAPSerialization
{
public class ClsSOAP
{
//Serialization
public void ToSoapSerialization(Object objToSoap,string filePath)
{
IFormatter formatter;
FileStream fileStream = null;
try
{
fileStream = new FileStream(filePath,FileMode.Create, FileAccess.Write);
formatter = new SoapFormatter();
formatter.Serialize(fileStream, objToSoap);
}
catch (Exception exception)
{
throw exception;
}
finally
{
if (fileStream != null) fileStream.Close();
}
}

//Deserialization
public object FromSoapSerialization(string filePath)
{
IFormatter formatter;
FileStream fileStream = null;
try
{
fileStream = new FileStream(filePath,FileMode.Open, FileAccess.Read);
formatter = new SoapFormatter();
return formatter.Deserialize(fileStream);
}
catch (Exception exception)
{
throw exception;
}
finally
{
if (fileStream != null) fileStream.Close();
}
}
}
}

//Main Class
using System;
using System.Collections.Generic;
using System.Text;

namespace SOAPSerialization
{
public class Program
{
static void Main(string[] args)
{
ClsSample ObjSample;
ClsSOAP ObjSOAP;
ObjSample = new ClsSample();
ObjSample.ReAssignMemberValues();
ObjSOAP = new ClsSOAP();
//Serialize
ObjSOAP.ToSoapSerialization(ObjSample, "c:\\SOAPSerialized.TXT");
ObjSample = null;
//Deserilize
ClsSample ObjDeseialSOAP;
ObjDeseialSOAP = (ClsSample)ObjSOAP.FromSoapSerialization("c:\\SOAPSerialized.TXT");
ObjDeseialSOAP.DisplayMemberValueAfterDeSerialization();
}
}
}

Output:

Private member value is 20

Public member value is Twenty

Here both private and public members are serialized


Serailization in .NET


Serialization:

Serialization is the process of saving the state of an object in a persistent storage media in the form of linear stream of bytes. The object can be stored to a file, a database or even in the memory. Serialization in .NET is provided by the System.Runtime.Serialization namespace.

In order for a class to be serializable, it must have the attribute SerializableAttribute set
and all its members must also be serializable, except if they are ignored with the attribute NonSerializedAttribute. However, the private and public members of a class are always serialized by default. The SerializationAttribute is only used for the binary serialization.

[Serializable]
public class Student
{
private int StudentID;
public string StudentName;
public void dispaly()
{
Console.WriteLine("Student Name "+ StudentName);
}
}


Binary Serialization:

In Binary serialization the entire object state is saved. Both public and private members states are saved.

//The following way Student object is serialized
public void BinarySerialize(string filename, Student Stud)
{
FileStream fileStreamObject;
try
{
fileStreamObject =
new FileStream(filename, FileMode.Create);
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStreamObject, Stud);
}
finally
{
fileStreamObject.Close();
}
}

//The following way Deserialize the Student Object
public static object BinaryDeserialize(string filename)
{
FileStream fileStreamObject;

try
{
fileStreamObject = new FileStream(filename, FileMode.Open);
BinaryFormatter binaryFormatter = new BinaryFormatter();
return (binaryFormatter.Deserialize(fileStreamObject));
}
finally
{
fileStreamObject.Close();
}
}


Serialization is used to transportation of an object through a network.