Sunday, January 3, 2010

Gaurav Khanna – Microsoft MVP 2010

I am proud to announce that I am awarded Microsoft MVP on January 01, 2010 for providing technical expertise in Visual Basic technical communities for past one year.

About the MVP Award Program (As described by microsoft)

Since the early 1990s, Microsoft has recognized the inspiring activities of MVPs around the world with the MVP Award. MVPs freely share their deep knowledge, real-world experience, and impartial, objective feedback to help people enhance the way they use technology. Of more than 100 million users who participate in technology communities, around 4,000 are recognized as Microsoft MVPs.

MVPs make exceptional contributions to technical communities, sharing their passion, knowledge, and know-how. Meanwhile, because MVPs hear the opinions and needs of many others in the technical community, they are well-placed to share highly focused feedback with Microsoft.

MVPs are independent experts who are offered a close connection with people at Microsoft. To acknowledge MVPs’ leadership and provide a platform to help support their efforts, Microsoft often gives MVPs early access to Microsoft products, as well as the opportunity to pass on their highly targeted feedback and recommendations about product design, development, and support.

Email from Microsoft

Dear Gaurav Khanna,

Congratulations! We are pleased to present you with the 2010 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in Visual Basic technical communities during the past year.

The Microsoft MVP Award provides us the unique opportunity to celebrate and honor your significant contributions and say “Thank you for your technical leadership.”

Toby Richards
General Manager
Community & Online Support

List of MVPs announced from South Asia in January 2010 can be found on following link

http://blogs.technet.com/southasiamvp/archive/2010/01/03/new-mvps-announced-january-2010.aspx

Sunday, October 18, 2009

I’m A VB: Gaurav Khanna

My Interview with some of the great VB.NET programmer in MSDN Website. It great to be in the list with leading programmer of VB.NET.

http://blogs.msdn.com/vbteam/pages/i-m-a-vb-gaurav-khanna.aspx

Sunday, October 4, 2009

Encrypt/Decrypt Text in VB.NET

In this article I have code which can be used encrypt the text before saving it in the file, database, registry, etc to protect from misuse. There are many article we can find on internet to encrypt/decrypt text in .Net. Each have different ways for encryption with some having very long code. So I have created a  very simple two functions to encrypt/decrypt a text in .Net. Both the functions contains two parameter. First parameter “Text” will be the text which need to encrypted and second parameter is “Key” which is a private key which will help identity during decrypt. So key during decrypt should be same as in encypt to decrypt the text correctly.

Code to encrypt the Text

 

Imports System.Security.Cryptography
Imports System.Text
Imports System.IO

Function Encrypt(ByVal text As String, ByVal key As String) As String
Try
Dim crp As New TripleDESCryptoServiceProvider
Dim uEncode As New UnicodeEncoding
Dim bytPlainText() As Byte = uEncode.GetBytes(text)
Dim stmCipherText As New MemoryStream
Dim slt() As Byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Dim pdb As New Rfc2898DeriveBytes(key, slt)
Dim bytDerivedKey() As Byte = pdb.GetBytes(24)

crp.Key = bytDerivedKey
crp.IV = pdb.GetBytes(8)

Dim csEncrypted As New CryptoStream(stmCipherText, crp.CreateEncryptor(), CryptoStreamMode.Write)

csEncrypted.Write(bytPlainText, 0, bytPlainText.Length)
csEncrypted.FlushFinalBlock()
Return Convert.ToBase64String(stmCipherText.ToArray())
Catch ex As Exception
Throw
End Try
End Function

So for example Encrypt(“Demo”, “12345″) will return 1T5yxecmgLbsxQu4iQx5Bg==”


Code to decrypt the Text

Function Decrypt(ByVal text As String, ByVal key As String) As String
Dim crp As TripleDESCryptoServiceProvider
Try
crp = New TripleDESCryptoServiceProvider
Dim uEncode As New UnicodeEncoding
Dim bytCipherText() As Byte = Convert.FromBase64String(text)
Dim stmPlainText As New MemoryStream
Dim stmCipherText As New MemoryStream(bytCipherText)
Dim slt() As Byte = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Dim pdb As New Rfc2898DeriveBytes(key, slt)
Dim bytDerivedKey() As Byte = pdb.GetBytes(24)
crp.Key = bytDerivedKey
crp.IV = pdb.GetBytes(8)

Dim csDecrypted As New CryptoStream(stmCipherText, crp.CreateDecryptor(), CryptoStreamMode.Read)
Dim sw As New StreamWriter(stmPlainText)
Dim sr As New StreamReader(csDecrypted)
sw.Write(sr.ReadToEnd)
sw.Flush()
csDecrypted.Clear()
crp.Clear()
Return uEncode.GetString(stmPlainText.ToArray())
Catch ex As Exception
Throw
End Try
End Function

So now when we decrypt the text encrypted above we will get the required text

So Decrypt(“1T5yxecmgLbsxQu4iQx5Bg==”, “12345″) will return “Demo”

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