Saturday, May 23, 2009

Send email with embedded Image

Recently one of my friend wanted to send email containing embedded image, similarly like we can do using Outlook. So I decided to create an example for him. To embed external resource in email we can use LinkedResource class provide in System.Net.Mail. In this article we will send email containing embedded image with smtp server as gmail.

Code:

Private Sub SendEmail()
Dim mail As New MailMessage("fromAddress@gmail.com", "toAddress@gmail.com")
mail.Subject = "This is an embedded image mail"
'create the image resource from image path using LinkedResource class..
Dim imageResource1 As New LinkedResource("C:\MyPhotos\Photo1.jpg", "image/jpeg")
imageResource1.ContentId = "uniqueId1"
imageResource1.TransferEncoding = TransferEncoding.Base64
Dim imageResource2 As New LinkedResource("C:\MyPhotos\Photo2.jpg", "image/jpeg")
imageResource2.ContentId = "uniqueId2"
imageResource2.TransferEncoding = TransferEncoding.Base64
Dim htmlBody As New StringBuilder
htmlBody.AppendLine("")
htmlBody.AppendLine("<b>LIST OF PHOTOS</b>")
htmlBody.AppendLine("</br></br>")
htmlBody.AppendLine("PHOTO 1")
htmlBody.AppendLine("<img alt="""" hspace=0 src=""cid:uniqueId1"" align=baseline border=0 >")
htmlBody.AppendLine("</br></br>")
htmlBody.AppendLine("PHOTO 2")
htmlBody.AppendLine("<img alt="""" hspace=0 src=""cid:uniqueId2"" align=baseline border=0 >")
htmlBody.AppendLine("</br></br>")
Dim htmlView As AlternateView = AlternateView.CreateAlternateViewFromString(htmlBody.ToString, Nothing, "text/html")
'adding the imaged linked to htmlView...
htmlView.LinkedResources.Add(imageResource1)
htmlView.LinkedResources.Add(imageResource2)
mail.AlternateViews.Add(htmlView)
Dim smtp As New SmtpClient("smtp.gmail.com", 587)
'If smtp server requires SSL
smtp.EnableSsl = True
smtp.Credentials = New NetworkCredential("fromAddress@gmail.com", "SMTP Password")
smtp.Send(mail)
End Sub

Thursday, January 29, 2009

WPF MessageBox

Introduction

When we open MessageBox in a WPF application, it looks are very similar to that of a Window Form. We cannot inherits or apply style to MessageBox. Using MessageBox in a WPF application with a rich user interface can look bad. So in this article we will create our own WPFMessageBox with rich user interface.

Using the code

WPFMessageBox is very similar to MessageBox in WPF with added functionality and rich user interface. We can apply two different skin to WPFMessageBox just by setting Skin property.

WPFMessageBox with Black Skin

WPFMessageBox2

WPFMessageBox with Blue Skin

WPFMessageBox1

Code to apply Black Skin and Blue Skin to WPFMessageBox is as below

'Code to apply Black Skin
WpfMessageBox.Skin = DisplaySkin.Black
'Code to apply Blue Skin
WpfMessageBox.Skin = DisplaySkin.Blue

Just like MessageBox, WPFMessageBox also has Show() method with various overloads to set caption, text, icon, buttons and default result.

Various overloaded functions for WPFMessageBox are shown in following code.


Function Show(ByVal text As String) As WpfMessageBoxResult
Function Show(ByVal text As String, ByVal caption As String) As WpfMessageBoxResult 
Function Show(ByVal text As String, ByVal caption As String, ByVal button As WpfMessageBoxButton) As WpfMessageBoxResult
Function Show(ByVal text As String, ByVal caption As String, ByVal button As WpfMessageBoxButton, ByVal icon As WpfMessageBoxImage) As WpfMessageBoxResult
Function Show(ByVal text As String, ByVal caption As String, ByVal button As WpfMessageBoxButton, ByVal icon As WpfMessageBoxImage, ByVal defaultResult As WpfMessageBoxResult) As WpfMessageBoxResult

All these overload functions are shared. So we can use them without creating their object.

WpfMessageBox.Show("Message box with a text and Caption", "WPF Message Box")

Above example will show WPFMessageBox with “Message box with a text and Caption” as text and “WPF Message Box” as caption.

WpfMessageBox.Show("Message with Yes and No", "WPF Message Box", WpfMessageBoxButton.YesNo)

Above example will show “Message with Yes and No” as text, “WPF Message Box” as caption and will contain Yes and No button.

Code for WPFMessageBox.Show have similar overload parameters to MessageBox.Show with great user interface. So one familiar to MessageBox can easily use WPFMessageBox

You can download the code from below link


Download Source Code

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