How to serialize an object in Silverlight.

If we want to serialize and deSerialize an object in silverlight We have to use DataContractSerializer as Silverlight doesn’t support BinaryFormatter.

DataContractSerializer under the type System.Runtime.Serialization Serializes and deserializes an instance of a type into an XML stream  using dataContract.

Create a Silverlight-enabled wcf service and define the data contract and Datamember attributes withing the .svc.

Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.Runtime.Serialization
 _
 _
Public Class EmployeeService
     _
    Public Sub DoWork()
        ' Add your operation implementation here
    End Sub
    ' Add more operations here and mark them with 
    
End Class
 
 _
Public Class Person
    Private UserNameStr As String
    Private PasswordStr As String
     _
    Public Property UserName() As String
        Get
            Return UserNameStr
        End Get
        Set(ByVal value As String)
            UserNameStr = value
        End Set
    End Property
     _
    Public Property Password() As String
        Get
            Return PasswordStr
        End Get
        Set(ByVal value As String)
            PasswordStr = value
        End Set
    End Property
End Class

By referencing the service in the Silverlight application we can serialize and deSerialize an object in silverlight

Below is the code for Serializing the object in the .xaml page.

Imports System.IO Imports System.IO.IsolatedStorage Imports System.ServiceModel

Imports System.Runtime.Serialization

We will use IsolatedStorageFile.GetUserStoreForApplication() function  get the isolated storage for the application and Serialize the objects to Isolated storage

Private IsolateStorageFileObj As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()

Dim PersonObj As New Person PersonObj.UserName = “Soumyap” PersonObj.Password = “Mindfire” Dim fs As New IsolatedStorageFileStream(“Person.dat”, FileMode.Create, IsolateStorageFileObj) Dim serializer As New DataContractSerializer(GetType(Person)) serializer.WriteObject(fs, PersonObj)

fs.Close()

Similarly We can deSerialize the object from Isolated storage.

Dim PersonObj As New Person Dim isfstream As New IsolatedStorageFileStream(“Person.dat”, FileMode.Open, IsolateStorageFileObj) Dim serializer As New DataContractSerializer(GetType(Person))

PersonObj = DirectCast(serializer.ReadObject(isfstream), Person)

150 150 Burnignorance | Where Minds Meet And Sparks Fly!