Saturday, June 26, 2010

Sending email from asp.net

These are very basic step needed to send email from asp.net. I am here not explaining error handling and attachment in mail message.Make sure to import system.net.mail namespace

Dim XMail As New MailMessage ‘Declare a mail object
Dim XSmtp As New SmtpClient ‘declare object of Smtp client

‘Set mail from
XMail.From = New MailAddress("xyzfrom@domain.com", "From display name")
‘set mail to, here we can add multiple addresses

XMail.To.Add("xyzto@domain.com")
‘set cc for mail message, in the same way we can set name in to also
XMail.CC.Add(New MailAddress("xyzcc@domain.com", "cc display name"))
XMail.Subject = "email subject"
XMail.Body = "email body"
‘host will provide you email service provider
XSmtp.Host = "mail.domain.com"
‘credentials will be your email address and password
XSmtp.Credentials = New System.Net.NetworkCredential("xyzfrom@domain.com", "password")
‘send email
XSmtp.Send(XMail)

Friday, June 25, 2010

Convert SQLDataReader to DataTable

In ADO.Net SQLDataReader is a way of reading forward-only streams of sql server database.
SqlDataReader cannot be inherited. Only one SqlDataReader can open on associated SQL Connection.

This function is handy in the case of you want to store result of the reader to table and want to open further SqlDataReader on same SQL Connection.

This function receives SqlDataReader as Input and return DataTable as return

Public Function ReaderToTable(ByVal LReader As SqlDataReader) As Data.DataTable
Dim LTable As New Data.DataTable
Dim I As Integer
'Create table structure and get data type from each column
For I = 0 To LReader.FieldCount - 1
LTable.Columns.Add(LReader.GetName(I).ToString(), LReader.GetFieldType(I))
Next

'now start writing the rows
Do While LReader.Read()
Dim DRow As DataRow
DRow = LTable.Rows.Add()
For I = 0 To LReader.FieldCount - 1
DRow.Item(LTable.Columns(I).ColumnName) = LReader.Item(I)
Next
Loop

'give a name to table
LTable.TableName = "Reader"
Return LTable
End Function