Friday, 28 December 2012

sending mail with attachment in windows

 How to send a mail with attachment from windows form using C#.Net. || Send an Email using corporate or business email address in C#.Net.
To implement the Email Sending in Windows Application  you need to follow the below steps :

Step1 :
On the File menu, click New Project. Select Windows Forms Application as your project type.
Design the Form using controls from Toolbox.

Step2:
Now open the Form.cs page and write the following source code.

Form.cs Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.Text.RegularExpressions;


namespace Sample
{
    public partial class Sample_MailSend : Form
    {

        public AmirAds_MailSend()
        {
            InitializeComponent();
        }
 
        private void Cancel()
        {
            txtFromMail.Text = string.Empty;
            txtMailPassword.Text = string.Empty;
            txtToMail.Text = string.Empty;
            txtCC.Text = string.Empty;
            txtSubject.Text = string.Empty;
            txtAttachments.Text = string.Empty;
            txtBody.Text = string.Empty;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (txtFromMail.Text == string.Empty || txtMailPassword.Text == string.Empty || txtToMail.Text == string.Empty || txtSubject.Text == string.Empty)
            {
                MessageBox.Show("Please fill all the fields.", "Alert!!");
            }

            else
            {
                string pattern = null;
                pattern = "^([0-9a-zA-Z]([-\\.\\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,9})$";

                if (Regex.IsMatch(txtFromMail.Text, pattern) || Regex.IsMatch(txtToMail.Text, pattern) || Regex.IsMatch(txtCC.Text, pattern))
                {
                    System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
                    msg.From = new MailAddress(txtFromMail.Text);
                    msg.To.Add(txtToMail.Text);//Text Box for To Address

                    if (txtCC.Text != string.Empty)
                    {
                        msg.CC.Add(new MailAddress(txtCC.Text));
                    }

                    msg.Subject = txtSubject.Text; //Text Box for subject
                    msg.IsBodyHtml = true;
                    msg.Body = txtBody.Text;//Text Box for body

                    if (txtAttachments.Text != string.Empty)
                    {
                        System.Net.Mail.Attachment attachment;
                        attachment = new System.Net.Mail.Attachment(txtAttachments.Text);
                        msg.Attachments.Add(attachment);
                    }

                    //msg.Priority = MailPriority.High;
                    System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("relay-hosting.secureserver.net", 26);
                    client.UseDefaultCredentials = false;
                    client.Credentials = new System.Net.NetworkCredential(txtFromMail.Text, txtMailPassword.Text);
                    client.Port = 26;
                    client.Host = "mail.corporatemail.com ";
                    client.EnableSsl = false;
                    object userstate = msg;
                  
                    try
                    {
                        client.Send(msg);
                        MyMessageBox.ShowBox("Your mail has been sent sucessfully.");
                        this.Close();
                    }
                    catch (Exception ex)
                    {
                        MyMessageBox.ShowBox(ex.Message);
                    }
                    Cancel();
                }
                else
                {
                    MyMessageBox.ShowBox("Invalid email address");
                }
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            Cancel();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            DialogResult res = openFileDialog1.ShowDialog();
            if (res == DialogResult.OK)
            {
                txtAttachments.Text = openFileDialog1.FileName;
            }
        }

       }
}

Step4:
Now build the Solution and Debug it for the output.

Saturday, 22 December 2012

Validation Apply in ASP.NET MVC 3 Using Razor View


 Validation Apply in ASP.NET MVC 3 Using Razor View

In my previous article I explained how to create controls in ASP.Net MVC 3 using Razor view. In this I give the example of how to create the registration form. Now in this article I an going to apply the validation to this registration form. For some fields like Name, Email, Phone_No and Address I apply the Required validation that gives the message please enter your  Name, Email, Phone_No and Address respectively and a regular expression field for email_id that contain the @ sign. It also gives the validation summary. Now to start, use the following steps.

Step 1 : First of all please follow my previous article  link, and make the form application like that.
 

Step 2 : Modify some files in order to apply validation, like

Code for Registration.cs file.


using System.ComponentModel.DataAnnotations;

namespace MvcApplication4.Models
{
    public class Registration
    {
        [Required(ErrorMessage="Please enter your Name")]
        public string Name { get; set; }
        [Required(ErrorMessage="Please enter your valid Email_id")]
        [RegularExpression(".+\\@.+\\..+",ErrorMessage="Please Enter your valid email which contains the @ Sign")]
        public string Email { get; set; }
        [Required(ErrorMessage="Please enter your valid phone number")]
        public string Phone { get; set; }
        [Required(ErrorMessage="Please enter your address")]
        public string Address { get; set; }
    }
}

Code for HomeController.cs file
namespace MvcApplication4.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }
        [HttpGet]
        public ViewResult RegistrationForm()
        {
            return View();
        }
        [HttpPost]
        public ViewResult RegistrationForm(Registration registration)
        {
            if (ModelState.IsValid)
            {
                return View("Congratualation", registration);
            }
            else
            {
                // there is a validation error - redisplay the form
                return View();
            }
        }
    }
}

Code for RegistrationForm.cshtml file
@model MvcApplication4.Models.Registration
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>RsvpForm</title>
</head>
<body>
    @using (Html.BeginForm())
    {
        @Html.ValidationSummary()
        <p>
            Your name: @Html.TextBoxFor(x => x.Name)
        </p>
        <p>
            Your email: @Html.TextBoxFor(x => x.Email)</p>
        <p>
            Your phone: @Html.TextBoxFor(x => x.Phone)</p>
        <p>
           Your address: @Html.TextBoxFor(x=>x.Address)</p>
        <input type="submit" value="Register Me" />
    }
</body>
</html>Code for Index.cshtml file
 
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
</head>
<body>
    <div>
        <h3>Please fill the registration form by clicking on the following registration link</h3>
        @Html.ActionLink("Registration", "RegistrationForm")
    </div>
</body>
</html>Code for Congratualation.cshtml file
 
@model MvcApplication4.Models.Registration

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>Congratualation</title>
</head>
<body>
    <div>
        <h1>Congratualation, @Model.Name!!!</h1>
        <p>Your Registration has been Successfully completed.</p>
    </div>
</body>
</html>Step 3 : Now run the application by pressing F5, and the output looks like:

pic1.gif
When I click on the Registration link, the registration form is open, and when I only give the name and submit then the form gives the Errormessage because I apply the validation in all the fields.

pic2.gif

When all the fields are filled in, it does not submit the form when the submit button is clicked because the regular expression validation is applied to the email field, so that we can enter the email with the @ and . sign.

pic3.gif

Now after giving all the valid information and the submit button is clicked the congratulation message is displayed.

pic4.gif

Summary : In this article I discussed how to apply the validation in the form using Razor view.

Creating the Registration Form in ASP.NET MVC 3 Using Razor View



 Creating the Registration Form in ASP.NET MVC 3 Using Razor View

Introduction

In MVC (Model View Controllers) 3 I used a Razor view to create a simple registration form. To do this, first the registration request page is opened; if the user clicks on the registration link then the registration form is opened and after entering all the details the congratulation message will displayed that shows the registration is successfully completed. In this I used models, views and controllers. To create this simple form use the following steps:

Step 1 : Open the Visual Studio 2010 and select new project from the file menu. A dialog box appears; in that, under C# -> web, select "ASP.NET MVC3 Application" and click the Ok button:

razor1.gif

Step 2 : A window is opened; in that select Empty from the template option and select Razor from the View engine option and click ok.

razor2.gif

Step 3 : Now add the Controller by right-clicking on the controller folder placed at the Solution Explorer by clicking add->Controller.

razor3.gif

Step 4 : A window will opened; give the name of the controller as HomeController and add it:

razor4.gif

Step 5 : Modify the HomeController.cs file as:

using System.Web.Mvc;



namespace MvcApplication4.Controllers

{

    public class HomeController : Controller

    {

        public ViewResult Index()

        {

            return View();

        }

    }

}


Step 6 : Now right-click on the ViewResult method in order to add the view, like:

razor5.gif

Step 7 : A window will appear; in it give the name of the view and click add. The extension of the view is cshtml.
razor6.gif
Step 8 : Write the code in index.cshtml as:


@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <title>Index</title>

</head>

<body>

    <div>

        <h3>Please fill the registration form by clicking on the following registration link</h3>

    </div>

</body>

</html>

Step 9 : Add the Model by right-clicking on the Model folder in the Solution Explorer and add the class:

razor7.gif

Step 10 : A window will appear; in it select a class and give the name of the class as Registration.cs and click ok:

razor8.gif

Step 11 : Write the code in Registration.cs as:


namespace MvcApplication4.Models

{

    public class Registration

    {

        public string Name { get; set; }

        public string Email { get; set; }

        public string Phone { get; set; }

        public string Address { get; set; }

    }

}


Step 12 : Now in order to add the registration link modify the index.cshtml file as:

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <title>Index</title>

</head>

<body>

    <div>

        <h3>Please fill the registration form by clicking on the following registration link</h3>

        @Html.ActionLink("Registration", "RegistrationForm")

    </div>

</body>

</html>

Step 13 : When I run this the output will look like:

razor9.gif

Step 14 : Now In order to perform the action when I click on the Registration link write and modify the code as, modify the Controller as:


namespace MvcApplication4.Controllers

{

    public class HomeController : Controller

    {

        public ViewResult Index()

        {

            return View();

        }

        public ViewResult RegistrationForm()

        {

            return View();

        }

    }

}

Step 15 : Now add the View for the Registration Form by right-clicking on the ViewResult. In this step I am going to create the strongly typed view.

razor10.gif

Step 16 : Write the code in the RegistrationForm.cshtml file as:


@model MvcApplication4.Models.Registration

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <title>RsvpForm</title>

</head>

<body>

    @using (Html.BeginForm())

    {

        <p>

            Your name: @Html.TextBoxFor(x => x.Name)

        </p>

        <p>

            Your email: @Html.TextBoxFor(x => x.Email)</p>

        <p>

            Your phone: @Html.TextBoxFor(x => x.Phone)</p>

        <p>

           Your address: @Html.TextBoxFor(x=>x.Address)</p>      

        <input type="submit" value="Register Me" />

    }

</body>

</html>

Step 17 : Again modify the Controller in order to generate the event when the registration button is clicked:


using MvcApplication4.Models;



namespace MvcApplication4.Controllers

{

    public class HomeController : Controller

    {

        public ViewResult Index()

        {

            return View();

        }

        [HttpGet]

        public ViewResult RegistrationForm()

        {

            return View();

        }

        [HttpPost]

        public ViewResult RegistrationForm(Registration registration)

        {          

            return View("Congratualation", registration);

        }

    }

}



Step 18 : Again create the view for the third ViewResult as we create for the second the strongly typed view and give the name of the view as Congratualation.

Write the code in Congratualation.cshtml file as:


@model MvcApplication4.Models.Registration



@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <title>Congratualation</title>

</head>

<body>

    <div>

        <h1>Congratualation, @Model.Name!!!</h1>

        <p>Your Registration has been Successfully completed.</p>

    </div>

</body>

</html>



Step 19 : Now build the application and then run it; you will see the result as:

razor9.gif

When I click on the Registration link then:

razor12.gif

When the Register Me button is clicked then:

razor13.gif

Summary : In this article I explained how to create a registration form and perform actions, creation of models, views and controllers. 

Paging in ASP.NET MVC3

Paging in ASP.NET MVC3



In this article I will tell you that how to create paging in ASP.NET MVC3. For creating Paging functionality I had created an extension method which we will directly use in our views. Here I will give you required steps to create Paging for your application.
Creating a ViewModel

Here I am creating a ViewModel named PageInfo which contains Paging information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SportsStore.WebUI.Models
{
    public class PageInfo
    {
        public int TotalItems { get; set; }
        public int ItemsPerPage { get; set; }
        public int CurrentPage { get; set; }

        public int TotalPages
        {
            get
            {
                return (int)Math.Ceiling((decimal)TotalItems / ItemsPerPage);
            }
        }
    }
}


After creating PageInfo view model we need to create PagingHelper class. Paging Helper class work as an extension method for ASP.NET MVC so that it needs to be static.
Creating PagingHelper extension method

Here I am creating PagingHelper extension method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SportsStore.WebUI.Models;
using System.Text;

namespace SportsStore.WebUI.HtmlHelpers
{
    public static class PagingHelpers
    {
        /// <summary>
        /// This method returns an MVCHtmlString which
        /// is used for Paging purpose. this represents
        /// that it is an extension method, PageInfo is a
        /// ViewModel class which I had created and pageUrl
        /// is anomyous type function.
        /// </summary>
        public static MvcHtmlString PageLinks(this HtmlHelper html, PageInfo pageInfo, Func<int, string> pageUrl)
        {
            //Create an object of StringBuilder class
            StringBuilder result = new StringBuilder();

            for (int i = 1; i <= pageInfo.TotalPages; i++)
            {
                //TagBuilder class is used to create Tag.
                //Here I am creating <a></a> tag.
                TagBuilder tag = new TagBuilder("a");

                //Merge required attributed like href, title etc.
                tag.MergeAttribute("href", pageUrl(i));

                //Set inner heml.
                tag.InnerHtml = i.ToString();

                if (i == pageInfo.CurrentPage)
                {
                    //Add any class if you want to add.
                    tag.AddCssClass("selected");
                }

                //Finally add resulted string in StringBuilder object.
                result.Append(tag.ToString());
            }

            //Create MVCHtmlString.
            return MvcHtmlString.Create(result.ToString());
        }
    }
}


Now I am going to use this extension method in our view to create Paging
Using PagingHelper extension method

<div class="pager">
    @Html.PageLinks(Model.PageInfo, x => Url.Action("List", new { page = x }))
</div>


Now after executing current application output will be as follows.


Note: This is not complete example. Here I am trying to tell that how to use extension method to create HtmlHelper and how to create Paging. If you copy and paste above code then it will not work.

Thanks for reading this article. Please write your valuable comments.

Saving Image in Sql Server Database

 Saving Image in Sql Server Database


In this blog I am going to told you that how to save image in a sql server table. For completing this blog I had used Sql Server 2005 and Visual Studio 2010. I had used C# as a programing language.

1) Before we are starting to make application in C# firstly we need to create a table in sql server where we store out image. Here I will create a table named tbl_Image in which I will store image. tbl_Image contains two column one is imageID which will store id of image in image table. And other column which have name imageData is stored image in format of binary.
Here I will provide a sample sql code snippet to create ImageTable
create table tbl_Image
(
imageID int,
imageData image
)

2) Now import System.Data.SqlClient namespace in your project. This namespace provide you all necessary classes and interfaces which is necessary to establish connection to SqlServer.

3) Create following methods and call it according to your requiremnt.

/// <summary>
/// On click event of browse button write down following code. This
/// Will display a open file dialog box which will ask to choose you
/// image and will store path of image in textbox.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private voidbutton1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = newOpenFileDialog();
if (DialogResult.OK == ofd.ShowDialog())
{
textBox1.Text = ofd.FileName; //storing path of image in textbox.
}
}
/// <summary>
/// On the click of SaveButton call saveImageInDataBase(int imgId) method
/// which will save image in database.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private voidbutton2_Click(object sender, EventArgs e)
{
saveImageInDataBase(1);
}
/// <summary>
/// This is a required method which will save image in database.
/// </summary>
/// <param name="imageID"></param>
public voidsaveImageInDataBase(int imageID)
{
byte[] imageData = ReadImageFile(textBox1.Text); //This nethod returns image in byte array format.
SqlConnection con = newSqlConnection();
con.ConnectionString = "Data Source=aaaa;User ID=sa;Password=abcd;Initial Catalog=Workbook"; //provide connection string of your server.
con.Open(); //open connection to server.
string query = "insert into tbl_Image values(@imageId,@imageData)"; //create a query variable.
SqlCommand cmd = newSqlCommand(query, con); //create a sqlcommand object.
cmd.Parameters.Add(new SqlParameter("@imageId", imageID)); //add first parameters.
cmd.Parameters.Add(new SqlParameter("@imageData", imageData)); //add second parameters.
int rows = cmd.ExecuteNonQuery(); //execute query.
if (rows > 0)
MessageBox.Show("Image saved.");
else
MessageBox.Show("Unable to save image.");
con.Close();
}
/// <summary>
/// This method will converts image in byte array format and returns to its caller.
/// use System.IO namespace regarding streaming concept.
/// </summary>
/// <param name="imageLocation"></param>
/// <returns></returns>
public byte[] ReadImageFile(string imageLocation)
{
byte[] imageData = null;
FileInfo fileInfo = newFileInfo(imageLocation);
long imageFileLength = fileInfo.Length;
FileStream fs = newFileStream(imageLocation, FileMode.Open, FileAccess.Read);
BinaryReader br = newBinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
return imageData;
}
}
By Implementing above code you can successfully insert an image in a database.

SQL Query to Get Month wise Data, Year wise Data

SQL Query to Get Month wise Data, Year wise Data

Nov 29, 2012
Introduction
In this SQL Server article I will explain how to write query to get monthly (month wise) data or year wise data from database.
Description
In previous articles I explained Query to get Exclude weekends in SQL Query, While Loop Example in SQL Server, Find First and last day of current month in SQL, Convert Rows to Columns in SQL, Joins in SQL Server and many articles relating to SQL Server.  Now I will explain how to write query to get month wise data or year wise data from database in SQL Server.

If we want to get data based on month wise or year wise we need to write the query like as shown below 
SELECT YEAR(DateColumn) AS [Year],MONTH(DateColumn) AS [Month],COUNT(*) from yourtable Group By YEAR(DateColumn) MONTH(DateColumn)
If you want to see it in complete example first design one table (UserInfo) with two columns in database and enter some dummy data like as show below 
Type
CreateDate
Technology
2012-11-18 09:00:00:00
Social Network
2012-11-28 09:29:00:00
Education
2012-11-30 10:30:20:00
Politics
2012-10-04 04:20:33:59
Software
2012-10-03 04:20:33:59
Hardware
2012-10-02 04:20:33:59
Teaching
2012-10-01 04:20:33:59
Tech Support
2012-09-28 09:00:00:00
Customer Support
2012-09-10 09:00:00:00
Now from above table we need to get the records month wise and year wise for that we need to write the query like as shown 
DECLARE @temp TABLE (ID INT,Location varchar(120))
INSERT INTO @temp VALUES(1,'Near to Men''s Hostel')
SELECT * FROM @temp
Once we run above query we will get output like as shown below

Output:
Year
Month
Count
2012
9
2
2012
10
4
2012
11
3