Saturday 31 March 2012

How To : Send Email using SMTPClient in asp.net

Introduction
Now a days most of the web application provide features for sending emails to customers or users for different purpose. In this article I will show you how to sent an email using smtpclient in asp.net.

we need to use System.Net namespace for that.MailMessage class object is used for collects To, CC, Bcc addresses as MailAddressCollection.

Before using mail send function we need to include below code in web.config file.

<system.net>
    <mailSettings>
      <smtp >
        <network host="host name" port="25" userName="userid" password="pwd"/>
      </smtp>
    </mailSettings>
  </system.net>

if you want attachements in email , need to pass arraylist of attachments which is list of set of files objects.

C#.Net 

public bool SendMail(string FromEmailID, string ToEmailID, string CCEmailID, string 
BCCEmailID, string Subject, string Body, Boolean IsBodyHtml, ArrayList _Attachments)
    {
        MailMessage mm;
        SmtpClient smtp;
        try
        {
            mm = new MailMessage(FromEmailID, ToEmailID, Subject, Body);
            mm.IsBodyHtml = IsBodyHtml;
            if (!string.IsNullOrEmpty(CCEmailID)) mm.CC.Add(CCEmailID);
            if (!string.IsNullOrEmpty(BCCEmailID)) mm.Bcc.Add(BCCEmailID);
            if (_Attachments != null)
            {
                for (int i = 0; i < _Attachments.Count; i++)
                {
                    mm.Attachments.Add((Attachment)_Attachments[i]);
                }
            }
            smtp = new SmtpClient();
            smtp.Send(mm);
            return true;
        }
       
        catch
        {
            return false;
        }
    }

VB.Net

Public Function SendMail(FromEmailID As String, ToEmailID As String, CCEmailID As String, _
BCCEmailID As String, Subject As String, Body As String, _
    IsBodyHtml As [Boolean], _Attachments As ArrayList) As Boolean
    Dim mm As MailMessage
    Dim smtp As SmtpClient
    Try
        mm = New MailMessage(FromEmailID, ToEmailID, Subject, Body)
        mm.IsBodyHtml = IsBodyHtml
        If Not String.IsNullOrEmpty(CCEmailID) Then
            mm.CC.Add(CCEmailID)
        End If
        If Not String.IsNullOrEmpty(BCCEmailID) Then
            mm.Bcc.Add(BCCEmailID)
        End If
        If _Attachments IsNot Nothing Then
            For i As Integer = 0 To _Attachments.Count - 1
                mm.Attachments.Add(DirectCast(_Attachments(i), Attachment))
            Next
        End If
        smtp = New SmtpClient()
        smtp.Send(mm)
        Return True

    Catch
        Return False
    End Try
End Function

I hope this article was useful and I thank you for viewing it. keep visiting blog , you can get more stuff.

Saturday 24 March 2012

How To : Set Meta Description , Meta Keyword in asp.net

Introduction

Meta Description and Meta keywords play a major role in terms of making web page search engine friendly. search engine always looks for meta description and meta keywords from the page contents. Here I m showing how to set meta description and meta keywords in web page.

 ASP.Net 4.0 provided new two properties at page level for setting meta description and meta keywords.we can add these two properties with page class in Code behind or in Page Directives.

Asp.Net 4.0

 C#.Net
protected void Page_Load(object sender, EventArgs e)
{
    Page.MetaKeywords = "Test Page";
    Page.MetaDescription = "Test Page";
}

VB.net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.Page.MetaKeywords = "Test Page"
        Me.Page.MetaDescription = "Test Page"
End Sub


Earlier Version of Asp.Net

Need to create some function which will set meta description and meta keywords. here it use HtmlMeta to do the same.

C#.Net

protected void Page_Load(object sender, System.EventArgs e)
{
    SetMetaDescription(this.Page, "Test Page");
    SetMetaKeyword(this.Page, "Test Page");
}

public void SetMetaDescription(Page PageName, string strMetaDesc)
{
    HtmlMeta metaDesc = new HtmlMeta();
    HtmlHead head = PageName.Header;
    metaDesc.Name = "description";
    metaDesc.Content = strMetaDesc;
    head.Controls.Add(metaDesc);

}
public void SetMetaKeyword(Page PageName, string strMetaKeyword)
{
    HtmlMeta metaKeys = new HtmlMeta();
    HtmlHead head = PageName.Header;
    metaKeys.Name = "keyword";
    metaKeys.Content = strMetaKeyword;
    head.Controls.Add(metaKeys);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
       
        SetMetaDescription(Me.Page, "Test Page")
        SetMetaKeyword(Me.Page, "Test Page")
End Sub    

Public Sub SetMetaDescription(ByVal PageName As Page, ByVal strMetaDesc As String)
        Dim metaDesc As New HtmlMeta()
        Dim head As HtmlHead = PageName.Header
        metaDesc.Name = "description"
        metaDesc.Content = strMetaDesc
        head.Controls.Add(metaDesc)

End Sub
Public Sub SetMetaKeyword(ByVal PageName As Page, ByVal strMetaKeyword As String)
        Dim metaKeys As New HtmlMeta()
        Dim head As HtmlHead = PageName.Header
        metaKeys.Name = "keyword"
        metaKeys.Content = strMetaKeyword
        head.Controls.Add(metaKeys)
End Sub
 I hope this article was useful and I thank you for viewing it. keep visiting blog , you can get more stuff.

Friday 23 March 2012

How to : Get Image from SQL database table's image filed in asp.net


Introduction


MS SQL has provided many new data types.Image data type is one of that. which store for example images in any format (.jpg,.bmp,.gif) or any document or file in binary format data. in this article I will show you how to store data into image data type and vice verse how to retrieve those.

For saving image into database we have aspx code as like below.

<asp:FileUpload ID="fl" runat="server" />
<asp:Button ID="btn" runat="server" Text="Save Image" />

Now we have handle button click event for save image.

C#.Net


protected void btn_Click(object sender, System.EventArgs e)
{
    SaveImage();
}

public void SaveImage()
{
    if (fl.HasFile) {
        byte[] productImage = fl.FileBytes;

        string strQuery = null;
        SqlConnection objConnDBConnection = null;
        SqlCommand objCommand = null;
       
        try {
            string connectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString;
            objConnDBConnection = new SqlConnection(connectionString);
            objConnDBConnection.Open();

            strQuery = "insert into customers_details(customer_id,customer_logo)values(@customer_id,@customer_logo)";
            objCommand = new SqlCommand(strQuery, objConnDBConnection);
            objCommand.CommandType = CommandType.Text;
            objCommand.Parameters.AddWithValue("@customer_id", 1);
            objCommand.Parameters.AddWithValue("@customer_logo", productImage);

            int i = objCommand.ExecuteNonQuery();

        } catch (Exception ex) {
        } finally {
            objCommand = null;
            objConnDBConnection.Close();
        }

    }
}

VB.Net


Protected Sub btn_Click(sender As Object, e As System.EventArgs)
    SaveImage()
End Sub

Public Sub SaveImage()
    If fl.HasFile Then
        Dim productImage As Byte() = fl.FileBytes

        Dim strQuery As String = Nothing
        Dim objConnDBConnection As SqlConnection = Nothing
        Dim objCommand As SqlCommand = Nothing
      
        Try
            Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
            objConnDBConnection = New SqlConnection(connectionString)
            objConnDBConnection.Open()

            strQuery = "insert into customers_details(customer_id,customer_logo)values(@customer_id,@customer_logo)"
            objCommand = New SqlCommand(strQuery, objConnDBConnection)
            objCommand.CommandType = CommandType.Text
            objCommand.Parameters.AddWithValue("@customer_id", 1)
            objCommand.Parameters.AddWithValue("@customer_logo", productImage)

            Dim i As Integer = objCommand.ExecuteNonQuery()
        Catch ex As Exception
        Finally
            objCommand = Nothing
            objConnDBConnection.Close()

        End Try
    End If
End Sub


Half the way we have done. now image is stored in binary format in database. now I m showing how to get that image from database and display in image control.


Here is the code for aspx page for image control

<asp:Image ID="img" runat="server" ImageUrl="ImgHandler.ashx?imgid=1" />
Here is some tricky part . As we know for display image normally we need physical file at location.  Over here we need to create handler for getting image binary data , so need to create ashx file and pass id for customer for which you need to display image. in ashx file you need to create below function.



C#.Net
public void GetImageFromDatabase(HttpContext context)
{
    SqlDataReader rdr = default(SqlDataReader);
    SqlConnection conn = default(SqlConnection);
    SqlCommand selcmd = default(SqlCommand);
    try {
        conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString);
        selcmd = new SqlCommand("select customer_logo from customers_details where customer_id=" + context.Request.QueryString("imgid"), conn);
        conn.Open();
        rdr = selcmd.ExecuteReader();
        while (rdr.Read()) {
            context.Response.ContentType = "image/jpg";
            context.Response.BinaryWrite((byte[])rdr("customer_logo"));
        }
        if (rdr != null) {
            rdr.Close();
        }
    } finally {
        if (conn != null) {
            conn.Close();
        }
    }
}
VB.Net

Public Sub GetImageFromDatabase(context As HttpContext)
    Dim rdr As SqlDataReader = Nothing
    Dim conn As SqlConnection = Nothing
    Dim selcmd As SqlCommand = Nothing
    Try
        conn = New System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
        selcmd = New System.Data.SqlClient.SqlCommand("select customer_logo from customers_details where customer_id=" & context.Request.QueryString("imgid"), conn)
        conn.Open()
        rdr = selcmd.ExecuteReader()
        While rdr.Read()
            context.Response.ContentType = "image/jpg"
            context.Response.BinaryWrite(DirectCast(rdr("customer_logo"), Byte()))
        End While
        If rdr IsNot Nothing Then
            rdr.Close()
        End If
    Finally
        If conn IsNot Nothing Then
            conn.Close()
        End If
    End Try
End Sub
 I hope this article was useful and I thank you for viewing it. keep visiting blog , you can get more stuff.