Sunday, September 11, 2011

Sending E-Mail by C#.NET, Simple steps

Step 1 : Design Preparation.

we need the following design in windows application project.



the above forms for SMTP Configuration form and Sending Mail form.

Step 2 : Add the SMTP configuration class

add the following class in you project in order to make a SMTP configuration for your mail that we need to send.

public class cls_smtpConfiguration 
    {
        public static string host;
        public static int port;
        public static int timeout;
        public static bool enable_ssl;
        public static string username_account;
        public static string password_account;
    }

this class has a values from SMTP Configuration form and will get it for Sending Mail form.


Step 3 : In the SMTP Configuration form
Add the following code in the button Save Setting in the SMTP Configuration form

            cls_smtpConfiguration.host = textBox1.Text;
            cls_smtpConfiguration.port = Convert.ToInt32(textBox2.Text);
            cls_smtpConfiguration.timeout = Convert.ToInt32(textBox4.Text);
            if (radioButton1.Checked == true)
            {
                cls_smtpConfiguration.enable_ssl = true;
            }
            else 
            {
                cls_smtpConfiguration.enable_ssl = false;
            }
            cls_smtpConfiguration.username_account = textBox6.Text;
            cls_smtpConfiguration.password_account = textBox5.Text;
            this.Close();


The above code try to setting values from controls of form to members of cls_smtpConfiguration Class

Step 4 : In the 
Sending Mail form

follow the following steps under the Send mail button

  • Define the following line

  1. System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
  2. System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(cls_smtpConfiguration.host, cls_smtpConfiguration.port);
  3. System.Net.Mail.Attachment attach;
message object : for setting values (from, to, body ....)
smtp object : for setting smtp configuration about from mail
attach object : for setting the attachement files that is required to be attached with mail .

  • Try to validate [mail from] and [mail to]
  • if (ValidateEmail(textBox2.Text) == true) { message.To.Add(textBox2.Text); } else { MessageBox.Show("not valid mail");return; }
    if (ValidateEmail(textBox1.Text) == true) {message.From = new System.Net.Mail.MailAddress(textBox1.Text); } else { MessageBox.Show("not valid mail"); return; }
  • Setting the following values
  1. message.Subject = textBox3.Text;
  2. message.Body = richTextBox1.Text;
  3. smtp.Timeout = cls_smtpConfiguration.timeout;
  4. smtp.EnableSsl = cls_smtpConfiguration.enable_ssl;
  5. smtp.Credentials = new System.Net.NetworkCredential(cls_smtpConfiguration.username_account, cls_smtpConfiguration.password_account);
  • the following code for setting [attach] object all attachement that is exist in listbox1
  • if (listBox1.Items.Count > 0) { for (int i = 0; i < listBox1.Items.Count; i++) { attach = new System.Net.Mail.Attachment(listBox1.Items[i].ToString()); message.Attachments.Add(attach); } }
  • Final Step, sending mail
  • smtp.Send(message); MessageBox.Show("message sended !!");
follow the following steps under the SMTP configure button

Form2 x = new Form2();
x.ShowDialog();


follow the following steps under the Select button

OpenFileDialog x = new OpenFileDialog();
x.ShowDialog();
listBox1.Items.Add(x.FileName);



How to validate E-mail by C#, Simple Steps

Step 1: type the following reference in above your class form

using System.Text.RegularExpressions;

Step 2: Insert the following method in your application.


 public bool ValidateEmail(string sEmail)
        {
            Regex exp = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
            Match m = exp.Match(sEmail);
            if (m.Success && m.Value.Equals(sEmail))
            {
                return true;
            }
            else 
            {
                return false;
            }
        }


Step 3 : Call above method in any pace you want .

if (ValidateEmail(textBox2.Text) == true)
    {
         MessageBox.Show("valid mail");
     }
else { MessageBox.Show("not valid mail"); }  

Saturday, February 26, 2011

VB.NET - ListView Class

This example requires that you have added the code to a Form and call the method created in the example from the constructor or another method on the form. The example also requires that images named MySmallImage1, MySmallImage2, MyLargeImage1, and MyLargeImage2 are located in the root directory of drive C.

for more details : http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.aspx

        Private Sub CreateMyListView()
            ' Create a new ListView control.
            Dim listView1 As New ListView()
            listView1.Bounds = New Rectangle(New Point(10, 10), New Size(300, 200))
            ' Set the view to show details.
            listView1.View = View.Details
            ' Allow the user to edit item text.
            listView1.LabelEdit = True
            ' Allow the user to rearrange columns.
            listView1.AllowColumnReorder = True
            ' Display check boxes.
            listView1.CheckBoxes = True
            ' Select the item and subitems when selection is made.
            listView1.FullRowSelect = True
            ' Display grid lines.
            listView1.GridLines = True
            ' Sort the items in the list in ascending order.
            listView1.Sorting = SortOrder.Ascending
            ' Create three items and three sets of subitems for each item.
            Dim item1 As New ListViewItem("item1", 0)
            ' Place a check mark next to the item.
            item1.Checked = True
            item1.SubItems.Add("1")
            item1.SubItems.Add("2")
            item1.SubItems.Add("3")
            Dim item2 As New ListViewItem("item2", 1)
            item2.SubItems.Add("4")
            item2.SubItems.Add("5")
            item2.SubItems.Add("6")
            Dim item3 As New ListViewItem("item3", 0)
            ' Place a check mark next to the item.
            item3.Checked = True
            item3.SubItems.Add("7")
            item3.SubItems.Add("8")
            item3.SubItems.Add("9")
            ' Create columns for the items and subitems.
            ' Width of -2 indicates auto-size.
            listView1.Columns.Add("Item Column", -2, HorizontalAlignment.Left)
            listView1.Columns.Add("Column 2", -2, HorizontalAlignment.Left)
            listView1.Columns.Add("Column 3", -2, HorizontalAlignment.Left)
            listView1.Columns.Add("Column 4", -2, HorizontalAlignment.Center)
            'Add the items to the ListView.
            listView1.Items.AddRange(New ListViewItem() {item1, item2, item3})
            ' Create two ImageList objects.
            Dim imageListSmall As New ImageList()
            Dim imageListLarge As New ImageList()
            ' Initialize the ImageList objects with bitmaps.
            imageListSmall.Images.Add(Bitmap.FromFile("C:\MySmallImage1.bmp"))
            imageListSmall.Images.Add(Bitmap.FromFile("C:\MySmallImage2.bmp"))
            imageListLarge.Images.Add(Bitmap.FromFile("C:\MyLargeImage1.bmp"))
            imageListLarge.Images.Add(Bitmap.FromFile("C:\MyLargeImage2.bmp"))
            'Assign the ImageList objects to the ListView.
            listView1.LargeImageList = imageListLarge
            listView1.SmallImageList = imageListSmall
            ' Add the ListView to the control collection.
            Me.Controls.Add(listView1)
        End Sub 'CreateMyListView

Friday, February 18, 2011

Like Operator - VB.NET

This example uses the Like operator to compare a string to a pattern. The result is a Boolean value representing whether the string fits the pattern.

Dim myCheck As Boolean
myCheck = "F" Like "F"   ' Does "F" match "F"? Returns True.
myCheck = "F" Like "f"   ' Does "F" match "f"? Returns False.
myCheck = "F" Like "FFF"   ' Does "F" match "FFF"? Returns False.
myCheck = "aBBBa" Like "a*a"   ' Does "aBBBa" have a "a" at the
   ' beginning, an "a" at the end, and any number of characters in
   ' between? Returns True.
myCheck = "F" Like "[A-Z]"   ' Does "F" occur in the set of
   ' characters from A to Z? Returns True.
myCheck = "F" Like "[!A-Z]"     ' Does "F" NOT occur in the set of
   ' characters from A to Z? Returns False.
myCheck = "a2a" Like "a#a"     ' Does "a2a" begin and end with an
   ' "a" and have any single-digit number inbetween? Returns True.
myCheck = "aM5b" Like "a[L-P]#[!c-e]" ' Does "aM5b" fit the following
   ' pattern: Begins with "a", has and character from the set L through
   ' P, followed byb any single-digit number, and finally contains any
   ' character excluded from the character set c through e. Returns True.
myCheck = "BAT123khg" Like "B?T*"  ' Does "BAT123khg" fit the
   ' following pattern: Begins with "B", followed by any single
   ' character, followed by a "T" and finally zero or more characters
   ' of any type. Returns True.
myCheck = "CAT123khg" Like "B?T*"  ' Does "CAT123khg" fit the
   ' following pattern: Begins with "B", followed by any single
   ' character, followed by a "T" and finally zero or more characters
   ' of any type. Returns False.
------------------------------------------
from : http://msdn.microsoft.com/en-us/library/swf8kaxw(v=vs.71).aspx