Upload
khaled-salahul-den
View
217
Download
0
Embed Size (px)
Citation preview
7/31/2019 Serialization in DotNet
1/11
Serialization in DotNetSerialization is the Process of objects getting transformed to stream of bytes to be stored in a
File, Memory or a Database. The Main Purpose of Serialization is to Save the State of the object
in order to recreate it when needed. The reverse of this Process is called as De-Serialization.
Serialization as said before stores the state of the object in Stream of bytes which can be stored
in a File, Database or in Memory.
Using which a developer can easily recreate the same instance of the object with all its
properties whenever required.
Different Serialization Formats
A. Binary Format: Binary formatter is the most efficient way to serialize objects thatwill only be read by .NET framework-based applications. This formatter class is in the
System.Runtime.Serialization.Formatters.Binary
B. Soap Format : This XML Based formatter is easily read by .NET and non-.NETframework based applications .
A) Working sample of Binary Formatter :
1) You need to write the Serializable Class
_
Class SerializeObjects
Dim name AsString
PublicProperty EmpName() AsString
Get
Return name
EndGetSet(ByVal value AsString)
name = value
EndSetEndProperty
EndClass
2) Now The class in which the Serialization will take place
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Class BinaryExample
SharedSub Main()
7/31/2019 Serialization in DotNet
2/11
Dim ser AsNew SerializeObjects
ser.EmpName = "Hefin"
Dim binFor AsNew BinaryFormatter()
binFor.Serialize(File.Create("Demo.bin"), ser)
EndSub
End Class
B) Working sample of the SOAP formatter
The Serializable class remains the same only thing that changes is the class where the
serialization will take place.
NOTE : A reference to the Namespace System.Runtime.Serialization.Formatters.Soap needs to
be added.
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Soap
Class SoapExample
SharedSub Main()
Dim ser AsNew SerializeObjects
ser.EmpName = "Hefin"
Dim soapFor AsNew SoapFormatter()
soapFor.Serialize(File.Create( "Demo.xml"), ser)
EndSub
End Class
De-Serialization :- The reverse of the serialization process is called the De-Serialization .
De-Serialization of the SOAP Serialized Object
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Soap
Class SoapExample
SharedSub Main()
Dim ser AsNew SerializeObjects
Dim soapFor AsNew SoapFormatter()
7/31/2019 Serialization in DotNet
3/11
ser = soapFor.Deserialize(File.Open("Demo.xml", FileMode.Open))
Console.WriteLine(ser.EmpName)
EndSub
End Class
De-Serialization of the Binary Serialized Object
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Class BinaryExample
SharedSub Main()
Dim ser AsNew SerializeObjects
Dim binFor AsNew BinaryFormatter()
ser = binFor.Deserialize(File.Open("Demo.xml", FileMode.Open))
Console.WriteLine(ser.EmpName)
EndSub
End Class
Serialization
XML Serialization
Object Serialization is a process through which an object's state is transformed into someserial data format, such as XML or binary format, in order to be stored for some later use.In other words, the object is "dehydrated" and put away until we need to use it again.
Some good uses for serialization/deserialization include:
1. Storing user preferences in an object.2. Maintaining security information across pages and applications.3. Modification of XML documents without using the DOM.4. Passing an object from on application to another.5. Passing an object from one domain to another.6. Passing an object through a firewall as an XML string.
7/31/2019 Serialization in DotNet
4/11
XML Serialization: It is limited that it can serialize only public members.Required Namespace :
Imports System.XmlImports System.Xml.Serialization
Create XSD file from Class
Object instance into XML file
Create one web project and add Person.vb class file.
Imports SystemImports System.XmlImports System.Xml.Serialization
Namespace XMLSerialization'''
''' Summary description for Person.''' _PublicClass Person
Private m_sName AsStringPrivate m_iAge AsIntegerPublicSubNew()EndSub _PublicProperty Name() AsString
GetReturn m_sName
EndGetSet(ByVal value AsString)
m_sName = valueEndSet
EndProperty _PublicProperty Age() AsInteger
GetReturn m_iAge
EndGetSet(ByVal value AsInteger)
m_iAge = valueEndSet
EndPropertyPublicFunction Hello() AsString
Return"Hi! My name is " + Name + " and I am " + Age.ToString() + " years old"EndFunctionPublicFunction GoodBye() AsString
Return"So long"EndFunction
EndClassEndNamespace
7/31/2019 Serialization in DotNet
5/11
[XMLRoot()] and [XMLElement()] these are the .net attributes and tell the serializer where
the various members of this object will appear in the XML document and what they will benamed. Without these, serialization cannot take place.
Dim objXmlSer AsNew XmlSerializer(GetType(Person))Dim objLucky AsNew Person()
Dim objStrWrt As StreamWriterobjLucky.Name = "Myname"
objLucky.Age = 30
Response.Write(objLucky.Hello())
Response.Write(objLucky.GoodBye())
objStrWrt = New StreamWriter(Server.MapPath("abc.xml"))objXmlSer.Serialize(objStrWrt, objLucky)
objStrWrt.Close()
First of al, we declare and instantiate an XMLSerializer object. The typeof() functiondescribes what type of object it's going to be serializing. Then we assign Name and Age
properties of the Person object. Then we used to see the output of that object by callingHello() and GoodBye() functions. Then we initiates a StreamWriter object and that it will be
writing to a file call abc.xml. We then call the Serialize() method of the XMLSerializer object
and send it our person object to be serialized as well as the StreamWriter object so it willwrite the resulting XML to the file specified. Then we close the StreamWriter.
The Abc.Xml file is look like.
7/31/2019 Serialization in DotNet
6/11
Dim objDesPerson AsNew Person()Dim objStrRdr As StreamReaderobjStrRdr = New StreamReader(Server.MapPath("abc.xml"))Dim objXmlSer AsNew XmlSerializer(GetType(Person))objDesPerson = DirectCast(objXmlSer.Deserialize(objStrRdr), Person)
Response.Write(objDesPerson.Name)
Response.Write(objDesPerson.Age.ToString())objStrRdr.Close()
Binary Serialization
PublicClass ArticlePublic sTitle AsStringPublic sAuthor AsStringPublic sText AsString
EndClass
Not much to this class, just a few string variables. Lets suppose that we need to write an
instance of this call tout to disk. To do this, we can use binary serialization. This will createa binary file that can be read back in as an instance of Article. To do this, we will need to
implement 2 methods GetObjectData and Overloaded Constructor.
It will requires following namespace:
Imports System.Runtime.SerializationImports System.Runtime.Serialization.Formatters.Binary
First we will make the class with serializable attribute and implements the ISerializable
interface.
[Serializable()]
PublicClass ArticlesImplements ISerializable
EndClass
We have to implements GetObjectData method of ISerializable interface.
PublicSub GetObjectData(ByVal info As SerializationInfo, ByVal context As
StreamingContext)info.AddValue("Title", sTitle)info.AddValue("Author", sAuthor)info.AddValue("Text", sText)
EndSub
This method will allow you to serialize the objects to disk. We could add any code in herethat we wanted to customize the way the data is serialized.
Now we need a method to retrieve the data from a serialized object then we will use aoverloaded constructor for this.
7/31/2019 Serialization in DotNet
7/11
PublicSubNew(ByVal info As SerializationInfo, ByVal context As StreamingContext)sTitle = Convert.ToString(info.GetValue("Title", GetType(String)))sAuthor = Convert.ToString(info.GetValue("Author", GetType(String)))sText = Convert.ToString(info.GetValue("Text", GetType(String)))
EndSub
The empty constructor is added here so that you can create a new Article object withoutdeserialized one.
Now we have a class that can be serialized and deserialized. For serializing this class wehave to create methods like
Serializing the object
PublicSub serialize(ByVal fileName AsString)Dim s AsNew FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)Dim B AsNew BinaryFormatter()B.Serialize(s, Me)
s.Close()EndSub
Here first we create an instance of FileStream class which, will create file and open it in read
and write mode. Next we create an instance of BinaryForamtter class. This class have
Seralize method which take parameters FileStream and Instance which you want toserialize.
DeSerializing the object
PublicFunction deSerialize(ByVal fileName AsString) As ArticlesDim Fs AsNew FileStream(fileName, FileMode.Open, FileAccess.Read)Dim F AsNew BinaryFormatter()Dim s1 As Articles = DirectCast(F.Deserialize(Fs), Articles)Fs.Close()Return s1
EndFunction
Here again create an instance of BinaryFormatter. The method Deserialize() will take
parameter of FileStream object which point to the binary file which you want to deserialize.
You have to do explicit casting of Article type during Deserializing.
Create One Project For Serializing
Create one Articles.vb class file
Imports SystemImports System.IOImports System.Runtime.SerializationImports System.Runtime.Serialization.Formatters.BinaryNamespace BinarySerialization
_PublicClass Articles
Implements ISerializable
7/31/2019 Serialization in DotNet
8/11
Public sTitle AsStringPublic sAuthor AsStringPublic sText AsString
PublicSubNew()EndSub
PublicSubNew(ByVal info As SerializationInfo, ByVal context As StreamingContext)sTitle = Convert.ToString(info.GetValue("Title", GetType(String)))sAuthor = Convert.ToString(info.GetValue("Author", GetType(String)))sText = Convert.ToString(info.GetValue("Text", GetType(String)))
EndSubPublicSub serialize(ByVal fileName AsString)
Dim s As FileStreams = New FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)Dim B AsNew BinaryFormatter()B.Serialize(s, Me)s.Close()
EndSubPublicFunction deSerialize(ByVal fileName AsString) As Articles
Dim Fs AsNew FileStream(fileName, FileMode.Open, FileAccess.Read)Dim F AsNew BinaryFormatter()Dim s1 As Articles = DirectCast(F.Deserialize(Fs), Articles)Fs.Close()Return s1
EndFunction#Region"ISerializable Members"
PublicSub GetObjectData(ByVal info As SerializationInfo, ByVal context As
StreamingContext)info.AddValue("Title", sTitle)info.AddValue("Author", sAuthor)
info.AddValue("Text", sText)EndSub#EndRegion
EndClassEndNamespace
Create one webForm1.aspx page for testing the binary serialization.
'Binary Serialization of the objectDim c1 AsNew Articles()c1.sTitle = "My Title"c1.sAuthor = "Author Name"
c1.sText = "This is my Text"c1.serialize("C:\123.txt")
'deserialization of the object
Dim c2 As Articles = c1.deSerialize("C:\123.txt")Response.Write(c2.sTitle)Response.Write(c2.sAuthor)
Response.Write(c2.sText)
7/31/2019 Serialization in DotNet
9/11
13.24.1.Class binary Serialization
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization.Formatters.Soap
Public Class Tester
Public Shared Sub Main
DimmyClsSerializableAs New ClsSerializable()
SerializeBinary(myClsSerializable)
Console.WriteLine(FileContent(False))
DimmyFileStreamAs FileStream
myFileStream = New FileStream("test.dat", FileMode.Open, FileAccess.R
ead)
DimmyFormatterAs New BinaryFormatter()
myClsSerializable = CType(myFormatter.Deserialize(myFileStream), ClsS
erializable)
Console.WriteLine(myClsSerializable.intNumber.ToString)
Console.WriteLine(myClsSerializable.lngNumber.ToString)
Console.WriteLine(myClsSerializable.strDemo)
End Sub
Private SharedFunction FileContent(ByVal blnBinaryAs Boolean)As String
DimstrContentAs String
DimmyStreamReaderAs StreamReader
DimmyFileStreamAs FileStream
DimiAs Integer
Try
myFileStream = New FileStream("test.dat", FileMode.Open, FileAcce
ss.Read)
If blnBinary = True Then
For i = 1 To myFileStream.Length
strContent += myFileStream.ReadByte.ToString +" "
Next
Else
myStreamReader = New StreamReader(myFileStream)
strContent = myStreamReader.ReadToEnd
End If
myFileStream.Flush()
myFileStream.Close()
Return strContent
Catch exAs IOException
Console.WriteLine(ex.Message)
End Try
7/31/2019 Serialization in DotNet
10/11
EndFunction
Private Shared Sub SerializeBinary(ByVal myClsSerializableAs ClsSerializ
able)
DimmyFileStreamAs FileStream = New FileStream("test.dat", FileMode.
Create, FileAccess.Write)
DimmyBFormatterAs BinaryFormatter = New BinaryFormatter()
myBFormatter.Serialize(myFileStream, myClsSerializable)
myFileStream.Flush()
myFileStream.Close()
End Sub
End Class
Public Class ClsSerializable
Public intNumberAs Integer = 254
Public strDemoAs String = "This is a poublic test string"
Private strpDemoAs String = "This is a private test string"
Public lngNumberAs Long = 123456
End Class
Binary Serialization Example
[TOC]
Imports System
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
ImportsCenterSpace.NMath.Core
Namespace CenterSpace.NMath.Core.Examples.VisualBasic
' A .NET example in VB.NET showing how to serialize and deserialize an
NMath object
' in binary format.
Module SoapSerializationExample
Private filename As String = "data.dat"
Sub Main()
Console.WriteLine()
' Delete old file, if it exists
If (File.Exists(filename)) Then
Console.WriteLine("Deleting old file")
File.Delete(filename)
End If
http://www.centerspace.net/examples/nmath/index.phphttp://www.centerspace.net/examples/nmath/index.phphttp://www.centerspace.net/doc/NMathSuite/ref/html/N_CenterSpace_NMath_Core.htmhttp://www.centerspace.net/doc/NMathSuite/ref/html/N_CenterSpace_NMath_Core.htmhttp://www.centerspace.net/doc/NMathSuite/ref/html/N_CenterSpace_NMath_Core.htmhttp://www.centerspace.net/examples/nmath/index.php7/31/2019 Serialization in DotNet
11/11
' Create vector
Dim u As NewDoubleVector("[ 5.6 4.2 5.3 -0.004 434 ]")
' Persist to file
Dim stream As FileStream = File.Create(filename)
Dim formatter As New BinaryFormatter()
Console.WriteLine("Serializing vector")
formatter.Serialize(stream, u)
stream.Close()
' Restore from file
stream = File.OpenRead(filename)
Console.WriteLine("Deserializing vector")
Dim v AsDoubleVector = formatter.Deserialize(stream)
stream.Close()
Console.WriteLine()
Console.WriteLine("Press Enter Key")
Console.Read()
End Sub
End Module
End Namespace
http://www.centerspace.net/doc/NMathSuite/ref/html/T_CenterSpace_NMath_Core_DoubleVector.htmhttp://www.centerspace.net/doc/NMathSuite/ref/html/T_CenterSpace_NMath_Core_DoubleVector.htmhttp://www.centerspace.net/doc/NMathSuite/ref/html/T_CenterSpace_NMath_Core_DoubleVector.htmhttp://www.centerspace.net/doc/NMathSuite/ref/html/T_CenterSpace_NMath_Core_DoubleVector.htmhttp://www.centerspace.net/doc/NMathSuite/ref/html/T_CenterSpace_NMath_Core_DoubleVector.htmhttp://www.centerspace.net/doc/NMathSuite/ref/html/T_CenterSpace_NMath_Core_DoubleVector.htm