Sunday, July 20, 2008

XML Serialization in VB.NET

Serialization is the process of converting an object into a form that can be readily transported. For example, you can serialize an object and transport it over the Internet using HTTP between a client and a server. On the other end, deserialization reconstructs the object from the stream. XML Serialization can convert any CLR objects into XML documents and vise versa.  It is widely used in Web Services. In this article I will discuss the serialization of business objects to XML and vise versa.

Advantages of Xml Serialization

  • The XmlSerializer class gives you complete and flexible control when you serialize an object as XML
  • It provide or consume data without restricting the application that uses the data
  • You can develop an application that processes the XML data in any way you want.

About the Code

Suppose we have a Customer class as below

Public Class Customer
    Private mName As String
    Private mAddress As String
    Private mPhone As String
    Private mEmail As String
    <XmlElement("CustomerName")> Public Property Name() As String
        Get
            Return mName
        End Get
        Set(ByVal value As String)
            mName = value
        End Set
    End Property


    Public Property Address() As String
        Get
            Return mAddress
        End Get
        Set(ByVal value As String)
            mAddress = value
        End Set
    End Property


    Public Property Phone() As String
        Get
            Return mPhone
        End Get
        Set(ByVal value As String)
            mPhone = value
        End Set
    End Property

    Public Property Email() As String
        Get
            Return mEmail
        End Get
        Set(ByVal value As String)
            mEmail = value
        End Set
    End Property
End Class

On Serializing above class, XML File will be created containing CustomerName, Address, Phone and Email. If you intend to change the name of the element in xml file then you can add XmlElement to Property as done in Name property. As you can see in the code below instead of Name Xml data contains CustomerName. If you don’t want to add some property into xml file then you can add XMLIgnore attribute and that property will not be add in the XML File.

<Customer>
<CustomerName>Gaurav Khanna</CustomerName>
<Address>123, SAT Street</Address>
<Phone>123456</Phone>
<Email>abc@gmail.com</Email>
</Customer>

The code to convert business object to xml and vice versa is as below :

Shared Function SaveToXml(Of T)(ByVal instance As T, ByVal filePath As String) As Boolean
        Dim objSerialize As System.Xml.Serialization.XmlSerializer
        Dim fs As System.IO.FileStream
        Try
            If instance Is Nothing Then
                Throw New ArgumentNullException("instance")
            End If
            objSerialize = New System.Xml.Serialization.XmlSerializer(instance.GetType())
            fs = New System.IO.FileStream(filePath, IO.FileMode.Create)
            objSerialize.Serialize(fs, instance)
            fs.Close()
            Return True
        Catch ex As Exception
            Throw
        End Try
    End Function

    Shared Function LoadFromXml(Of T)(ByVal filePath As String) As T
        Dim objSerialize As System.Xml.Serialization.XmlSerializer
        Dim fs As System.IO.FileStream = Nothing

        Try


            'Throw File not found Exception
            If System.IO.File.Exists(filePath) = False Then
                Throw New IO.FileNotFoundException("File not found", filePath)
            End If

            Dim instance As T

            objSerialize = New System.Xml.Serialization.XmlSerializer(GetType(T))
            fs = New System.IO.FileStream(filePath, IO.FileMode.OpenOrCreate)
            instance = CType(objSerialize.Deserialize(fs), T)
            fs.Close()

            Return instance
        Catch ex As Exception
            fs.Close()
            Throw
        End Try
    End Function

Following is the example of using about functions

Save to XML File

Dim objCustomer As New Customer
objCustomer.Name = "Gaurav Khanna"
objCustomer.Address = "123, SAT Street"
objCustomer.Phone = "123456"
objCustomer.Email = "abc@gmail.com"
SaveToXml(Of Customer)(objCustomer, filePath)

Read from XML File

Dim objCustomer As Customer = LoadFromXml(Of Customer)(filePath)

Monday, July 14, 2008

Send Email from your Gmail Account

You can use your gmail account to send emails from VB.NET using SMTP. You need to set SSL credentials. You have to use “smtp.gmail.com” as host and “587” as Port to send email. Following function can send email.

CODE:
Private Sub SendEmail()
Try
Dim fromAddress As String = "fromAddress@domain"
Dim toAddress As String = "toAddress@domain"
Dim message As New Net.Mail.MailMessage(fromAddress, toAddress)

message.Subject = "Subject of the email"
message.Body = "<b>Hello World</b>"  'Will show Hello World in bold letters

'Set True if you your body contains Html
message.IsBodyHtml = True

'Set Priority of the Email
message.Priority = Net.Mail.MailPriority.High

'For gmail host would be "smtp.gmail.com" and port would be 587
Dim client As New Net.Mail.SmtpClient("smtp.gmail.com", 587)

'Set EnableSsl = True as gmail requires SSL
client.EnableSsl = True

'Credentials for the sender
client.Credentials = New Net.NetworkCredential(fromAddress, "Sender gmail password")

'Send the Email
client.Send(message)

Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub