ASP.Net Email Sending

This is very common usage that whenever we are working with webform or winform sometimes , instead most of the times we need to send email
To send email there is simple logic you just need Two very crucial things one the email server somtimes called host , and its port throuth which you want to send email
Here is the detail of some Hosts and there ports setting
For sending Email
Gmail : 
Incoming Mail Server (POP3) – pop.gmail.com (SSL enabled, port 995)
Outgoing Mail Server (SMTP) – smtp.gmail.com (TLS enabled, port 587)
MSN :
Incoming Mail Server (POP3) – pop3.email.msn.com (port 110, using Secure Password Authentication – SPA)
MSN Outgoing Mail Server – smtp.email.msn.com
Yahoo:
Yahoo Incoming Mail Server (POP3) – pop.mail.yahoo.com (SSL enabled, port 465)
Yahoo Outgoing Mail Server (SMTP) – smtp.mail.yahoo.com (SSL enabled, port 995)


And the credential we have to provide the sender email and sender password .
Below is the working sample , Make a function in you app_code Class and call it where u need it


METHOD 1 :

public static bool SendEmail(string ToAddress, string subject, string body,string emailaddress)
    {
        string setupemail = “”;
        string setuppassword = “”;
        string setupport = “”;


        SqlDataReader dr = DataLayer.DBOperation.ExecuteReader(“select * from emailsetup”);
        if (dr.Read())
        {
            setupemail = dr[“emailaddress”].ToString();
            setuppassword = dr[“password”].ToString();
            setupport = dr[“port”].ToString();
        }
        dr.Close();
        System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();
        mail.From = “\”Innovation in Diabetes\” < “+emailaddress+”>”;
        mail.To = ToAddress;
        mail.Headers.Add(“Reply-To”, emailaddress);
        mail.Body = body;
        mail.Subject = subject;
        mail.Bcc = setupemail;
        mail.BodyFormat = MailFormat.Html;
        SmtpMail.SmtpServer = “smtp.gmail.com”;
        // – smtp.gmail.com use smtp authentication
        mail.Fields.Add(“http://schemas.microsoft.com/cdo/configuration/smtpauthenticate”, “1”);
        mail.Fields.Add(“http://schemas.microsoft.com/cdo/configuration/sendusername”, “”+setupemail+””);
        mail.Fields.Add(“http://schemas.microsoft.com/cdo/configuration/sendpassword”, “”+setuppassword+””);
        // – smtp.gmail.com use port 465 or 587
        mail.Fields.Add(“http://schemas.microsoft.com/cdo/configuration/smtpserverport”, “”+setupport+””);
        // – smtp.gmail.com use STARTTLS (some call this SSL)
        mail.Fields.Add(“http://schemas.microsoft.com/cdo/configuration/smtpusessl”, “true”);
        // try to send Mail
        try
        {
            SmtpMail.Send(mail);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }


METHOD 2:


Public Sub SendEmail()

‘Hotmail/Live Host & Port smtp.live.com (Port 25)
        ‘Hotmail/Live Host & Port pop3.live.com (Port 995)


        ‘Yahoo pop.mail.yahoo.com (port 110)
        ‘Yahoo smtp.mail.yahoo.com (port 25)
        ‘Gmail smtp.gmail.com(port 587)
        Try


            ‘    Dim client As New SmtpClient
            ‘    client.Credentials = New System.Net.NetworkCredential(“ur_own_ftp_email account”, “password of that account”)
            ‘    client.EnableSsl = True
            ‘    client.Host = “smtp.gmail.com”


            ‘    client.Port = 485


            ‘    client.UseDefaultCredentials = False
            ‘    client.Send(mailMsg)
            ‘    ‘Attachments.Items.Clear()
            ‘    ‘Attachments.Items.Add(“(No Attachments)”)


 Dim mailClient As New SmtpClient(“smtp.gmail.com”, 587)


            mailClient.EnableSsl = True
‘Dim cred As New NetworkCredential(“your email”, “ur pwd goes here”)
Dim cred As New NetworkCredential(From.Text, txtPassword.Text)
            mailClient.Credentials = cred
            mailClient.Send(From.Text, ToAddress.Text, Subject.Text, Body.Text)


            MessageBox.Show(“Your email has been successfully sent!”, “Email Send Status”, MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch exp As Exception
            MessageBox.Show(“The following problem occurred when attempting to ” + exp.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
End Sub

Encrypt-Decrypt

Data is most vulnerable when it is stored persistently or transferred across a network , or we are storing it in database like passwords , security keys , security questions and answers , pin code etc. There are several classes provided by .Net to encrypt , decrypt information , Here i used MD5 encryption decryption methodology you can pass any string to the method and it will give u the encrypted string , the encrypted string can be decrypted by calling Decrypt() method. The methods given below are very useful can be easily deployed in any .Net web or desktop application .

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Configuration;
    public class CryptorEngine
    {
        ///

 

        /// Encrypt a string using dual encryption method. Return a encrypted cipher Text
        ///
        ///string to be encrypted
        ///use hashing? send to for extra secirity
        ///
        public static string Encrypt(string toEncrypt, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
            System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
            // Get the key from config file
            string key = (string)settingsReader.GetValue(“SecurityKey”, typeof(String));
            //System.Windows.Forms.MessageBox.Show(key);
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdes.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        ///

        /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
        ///
        ///encrypted string
        ///Did you use hashing to encrypt this data? pass true is yes
        ///
        public static string Decrypt(string cipherString, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = Convert.FromBase64String(cipherString);
            System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
            //Get your key from config file to open the lock!
            string key = (string)settingsReader.GetValue(“SecurityKey”, typeof(String));
            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(key);
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdes.Clear();
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
        public static string Decrypt(object p)
        {
            throw new Exception(“The method or operation is not implemented.”);
        }
        public static object Encrypt(string p)
        {
            throw new Exception(“The method or operation is not implemented.”);
        }
    }


Ranking-Query

While working with sql queries , sometimes we need to sort result set and find out the top 10 products , prices etc . we use order by clause to sort the results either ascending or descending.
But what if someone told u to find out the top 10 records and display their ranks too besides.
Here is one demonstration of ranking query . SQL Server provides a special function rank() over that can solve the problem very easily and its is very useful .

Syntax : RANK () OVER ( < order_by_clause > )

For example if in sample DB “Adventure work” we want to find top 10 products according to unit price then we can use the query as

Select Distinct ProductID, UnitPrice , LineTotal, ReceivedQty,RANK() OVER (order by UnitPrice) as [Unit Price Rank]
from Purchasing.PurchaseOrderDetail
Where ProductID between 800 and 900
order by [Unit Price Rank]

It will return all products sorted alongwith their rank like

Databound Controls

While working in asp.net applications there are few template repeating controls available like Gridview , Datalist  and DataRepeater . know if one wants to get a single element for any of the control , e.g i want to get the value of some specific item like in shopping cart how many items in cart etc so here are some methods to go through the elements of these controls.

Method 1
  1. click Event of that control , or selected index change event of that control
ImageButton btnbid = (ImageButton)sender;
        int id = Convert.ToInt16(btnbid.CommandArgument);
Method 2
 2. foreach (GridViewRow row in GridView1.Rows)
    {
        // Selects the text from the TextBox
        // which is inside the GridView control
        string textBoxText = ((TextBox)row.FindControl("TextBox1")).Text;
        Response.Write(textBoxText);
Method 3
 private void ChangeBtn_Click(object sender, EventArgs e)
    {
        Control x = MyRepeater.Items[0].FindControl("Message");
        if (x != null) list = WalkContainers(x);
        MyRepeater.DataSource = list;
        MyRepeater.DataBind();
    }
    private ArrayList WalkContainers(Control ctl)
    {
        ArrayList ret = new ArrayList();
        Control parent = ctl.NamingContainer;
        if (parent != null)
        {
            ArrayList sublist = WalkContainers(parent);
            for (int j = 0; j < sublist.Count; j++) ret.Add(sublist[j]);
        }
        ret.Add(ctl.GetType().Name);
        return ret;
    }
Method 4 :
((RepeaterItem)e.Item.NamingContainer.NamingContainer).DataItem
Method 5 :
GridViewRow gr1 = (GridViewRow)((ImageButton)sender).NamingContainer;
Method 6 :
void AuthorsGridView_RowDataBound (Object sender, GridViewRowEventArgs e)
  {
    // Check for a row in edit mode.
    if(e.Row.RowState == DataControlRowState.Edit)
    {
      // Preselect the DropDownList control with the state value
      // for the current row.
 
      // Retrieve the underlying data item. In this example
      // the underlying data item is a DataRowView object. 
      DataRowView rowView = (DataRowView)e.Row.DataItem;
 
      // Retrieve the state value for the current row. 
      String state = rowView["state"].ToString();
 
      // Retrieve the DropDownList control from the current row. 
      DropDownList list = (DropDownList)e.Row.FindControl("StatesList");
 
      // Find the ListItem object in the DropDownList control with the 
      // state value and select the item.
      ListItem item = list.Items.FindByText(state);
      list.SelectedIndex = list.Items.IndexOf(item);
    }
  }