DotNetSlackers: ASP.NET News for lazy Developers

Showing posts with label asp.net c#. Show all posts
Showing posts with label asp.net c#. Show all posts

Thursday, December 10, 2015

Send email to multiple receipent in asp.net

Explanation

Sending email using Asp.net is simple thing but I cannot forget my first task.Because am a fresher without knowing about dotnet I started my carrer, the first task is email sending using asp.net .Ok let me come to the point, here am trying to explain how to send the same email details to multiple receipents, One way this code will helpful for monthly news letters sending and checking.Also we may easily check the email configuration setting through this.First we may design the screen as mentioned below. 

Design


<table cellpadding="2" cellspacing="2" border="2" align="center" width="500px">
    <tr>
    <td colspan="2"><asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label></td>
    </tr>
    <tr>
    <td>SMTP(HOST) :</td>
    <td><asp:TextBox ID="txtsmtp" runat="server" Width="268px"></asp:TextBox></td>
    </tr>
    <tr>
    <td>UserName eMailID :</td>
    <td><asp:TextBox ID="txtFromUID" runat="server" Width="270px"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Password :</td>
    <td><asp:TextBox ID="txtPwd" runat="server" Width="133px" TextMode="Password"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Port :</td>
    <td><asp:TextBox ID="txtPort" runat="server" Width="270px"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Enable SSL :</td>
    <td><asp:CheckBox ID="chkSSL" runat="server" /> </td>
    </tr>
    <tr>
    <td>FromID :</td>
    <td><asp:TextBox ID="txtFromID" runat="server" Width="270px"></asp:TextBox></td>
    </tr>
    <tr>
    <td>To :</td>
    <td><asp:TextBox ID="txtTo" runat="server" Width="272px" Height="60px" 
            TextMode="MultiLine"></asp:TextBox><br />(use comma for multiple mailid)</td>
    </tr>
    <tr>
    <td>Subject :</td>
    <td><asp:TextBox ID="txtSubject" runat="server" Width="267px"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Body :</td>
    <td><asp:TextBox ID="txtBody" runat="server" Width="279px" Height="52px" 
            TextMode="MultiLine"></asp:TextBox></td>
    </tr>

    <tr align="center">
    <td colspan="2"><asp:Button ID="btnSubmit" runat="server" Text="Send" 
            onclick="btnSubmit_Click" />&nbsp;<asp:Button ID="btnClear" runat="server" Text="Clear" 
            onclick="btnClear_Click" /></td>
    </tr>
    </table>


Coding
using System.Net.Mail;



    public void Clear()
        {
            txtTo.Text = "";
            txtSubject.Text = "";
            txtsmtp.Text = "";
            txtPwd.Text = "";
            txtPort.Text = "";
            txtFromID.Text = "";
            txtBody.Text = "";
        }
    
    protected void btnClear_Click(object sender, EventArgs e)
        {
       Clear();

    }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            lblMessage.Text = string.Empty;
            SmtpClient smtpClient = new SmtpClient();
            MailMessage message = new MailMessage();

            try
            {
                MailAddress fromAddress = new MailAddress(txtFromID.Text, "");                
                //Provide smtp Host name
                smtpClient.Host = txtsmtp.Text;
                //made default credential as false
                smtpClient.UseDefaultCredentials = false;
                //Here pass the login from emailID and Password
                smtpClient.Credentials = new System.Net.NetworkCredential(txtFromUID.Text, txtPwd.Text);
                //Port is important, default port is 25.
                smtpClient.Port = (txtPort.Text.Trim() == string.Empty) ? 25 : Convert.ToInt32(txtPort.Text.Trim());
                
                //From email Id
                message.From = fromAddress;
                //Subject which we are going to send
                message.Subject = txtSubject.Text.Trim().Replace("'","");
                //Whether we are going to send body content as plain text/HTML format here i am going to use plain text so i kept html false
                message.IsBodyHtml = false;

                if ((txtTo.Text != null) && (txtTo.Text != string.Empty))
                {
                    //Here we are splitting the email ID by comma separated
                    string[] emailTo = txtTo.Text.Split(',');

                    foreach (string emails in emailTo)
                    {

                        if (emails.Trim().Length > 0)
                        {
                            //Add the To email id in Mail to List
                            message.To.Add(new MailAddress(emails));

                        }
                    }
                }

                // Message body content
                message.Body = txtBody.Text.Trim().Replace("'", "");

                //If SSL is enabled we have check the enable SSL true
                if (chkSSL.Checked)
                {
                    smtpClient.EnableSsl = true;
                }
                // Send SMTP mail
                smtpClient.Send(message);

                Clear();
                lblMessage.Text = "Email successfully sent.";               

            }
            //Here am using smtp exception original mail exception able to catch
            catch (SmtpException ex)
            {
                lblMessage.Text = "Email sending Failed." + ex;
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Email sending Failed." + ex;
            }
        }


Output

Here I mentioned the gmail smtp configuration for sending the email for multiple users, you may give your email id and password and try the same.
em 
In this post I tried to explain how to Send email to multiple recipient in Asp.net.

Difference between DataSet and DataReader

DataSet

DataSet is a type of disconnected architecture which means sql live database connections is not required while fetch the data from database. DataSet contains the collection of multiple DataTables. We are able to keep the tables, views values from database in DataSet. Also we can fetch the XML values and store in DataSet. We can use DataAdapter as a mediator between DataSet and SQL DataBase tables.

public DataSet GetData()
{
    SqlConnection conString = new SqlConnection("DataBase Connection");
    conString.Open();
    SqlCommand cmdQuery = new SqlCommand("SQL Statement", conString);
    SqlDataAdapter sda = new SqlDataAdapter(cmdQuery);
    DataSet dsData = new DataSet();
    sda.Fill(dsData);
    return dsData;
}


DataReader

DataReader is also used to fetch the data from SQL database. When compared to DataSet, DataReader is a connection oriented architecture. Also it is a read/forward only approach while fetching the data from SQL database. We can use DataReader for fast fetching the data from SQL database. DataReader will loop one by one record and return the data. Here we will see a sample for binding the GridView using DataReader.

Protected void BindDataGrid()
{
    SqlConnection conString = new SqlConnection("DataBase Connection");
    conString.Open();
    SqlCommand cmdQuery = new SqlCommand("SQL Statement", conString);
    SqlDataReader sdrData = cmdQuery.ExecuteReader();
    gvEmployees.DataSource = sdrData;
    gvEmployees.DataBind();
    conString.Close();
}


Output
In this post i tried to explain the difference between SQL Stored procedure and functions. 

Thursday, October 15, 2015

Difference between throw and throw ex in Asp.Net C# Exception

Exceptions

Exceptions are always useful for dotnet developers, because we are able to provide a bug free application with the use of exception handlings.We need to find the actual exception, here throw will give the exception details.We are confusing whileusing the throw and throw ex in exceptions.Difference between "throw" and "throw ex" is, "throw" will provide the orginal exception which was available at first in stack and "throw ex" will provide the last exception message available in stack.

Syntax for "throw ex"



try
{
   //If error occured go to catch and throw exception
}
catch (Exception ex)
{
   throw ex;
}

Syntax for "throw"


try
{
   //If error occured go to catch and throw exception
}
catch
{
   throw;
}
Eg: While working in N layered architecture application, "throw ex" will be use in UI Layer and "throw" will be use in all other layers.So try this in your application and check the difference.

Output
In this post i tried to explain the difference between throw and throw ex in Asp.Net C# Exceptions. My previous post Difference between dataset and datareader in Asp.Net C# exceptions.