Tuesday, 13 December 2011

Sending Email with ASP.NET

I will demonstrate today how to send email via ASP.NET: from plain to HTML mail and attachments. 

Sending Simple Mail:
I again want to begin with this way because we can test the server configuration quite easily without having to take any side effects into consideration (SimpleMail.aspx) 

<% @Page Language="C#" %>
<% @Import Namespace="System.Web.Mail" %>
<%
string strTo = "christophw@sleeper.Dev.AlfaSierraPapa.Com";
string strFrom = "webmaster@aspheute.com";
string strSubject = "Hi Everybody";

SmtpMail.Send(strFrom, strTo, strSubject,
  "A real nice body text here");

Response.Write("Email was queued to disk");
%>
What actually happens in the script? The complete email support resides in the  System.Web.Mail namespace.  In this namespace we find the class SmtpMail, whose static Send method can accept  four parameters: 
SmtpMail.Send(From, To, Subject, BodyText); 

Sending HTML E-Mail: 

But now we leave this all too simple method behind and look at a very functional object: the MailMessage class. This class 'encapsulates' everything one can wish for in an email - the following example demonstrates the use with a short HTML email (SimpleMailMessage.aspx).

<% @Page Language="C#" %>
<% @Import Namespace="System.Web.Mail" %>
<%
MailMessage msgMail = new MailMessage();

msgMail.To = "christophw@sleeper.Dev.AlfaSierraPapa.Com";
msgMail.Cc = "webmaster@sleeper.Dev.AlfaSierraPapa.Com";
msgMail.From = "webmaster@aspheute.com";
msgMail.Subject = "Hi Everybody, another mail";

msgMail.BodyFormat = MailFormat.Html;
string strBody = "<html><body><b>Hello World</b>" +
   " <font color=\"red\">ASP.NET</font></body></html>";
msgMail.Body = strBody;

SmtpMail.Send(msgMail);

Response.Write("Email was queued to disk");
%>
The code looks much better now and above all, there are significantly more options than  there are in the first Send method. First we set the To, From and  Subject properties of the MailMessage then we set the BodyFormat to the  value Html out of the MailFormat enumeration. And then we already are set to send  a HTML email. 
Worth mentioning is the fact that all overloads of the Send method do not have return values about the success of dispatching the email message. The reason for this is that the emails simply are written into the Pickup folder of the Inetpub directory from where they are read and then sent by the SMTP Service. Failed emails (dispatching errors) also are written into files, this time however in the Badmail folder. 

 Sending Attachments
 
With certain email components, sending attachments can be a bit of an adventure. With .Net, it is just another easy to use component: MailAttachment. The following code demonstrates how an attachment can be added to the MailMessage (MailAttachment.aspx).

<% @Page Language="C#" %>
<% @Import Namespace="System.Web.Mail" %>
<%
MailMessage msgMail = new MailMessage();

msgMail.To = "christophw@sleeper.Dev.AlfaSierraPapa.Com";
msgMail.From = "webmaster@aspheute.com";
msgMail.Subject = "Attachment Test";

msgMail.BodyFormat = MailFormat.Text;
msgMail.Body = "Check out the attachment!";
msgMail.Attachments.Add(new MailAttachment("c:\\temp\\annual-report.pdf"));

SmtpMail.Send(msgMail);

Response.Write("Email was queued to disk");
%>
The line  
msgMail.Attachments.Add(new MailAttachment("c:\\temp\\annual-report.pdf"));
might also be programmed as follows
MailAttachment maAttach = new MailAttachment("c:\\temp\\annual-report.pdf");
IList msgAttachments = msgMail.Attachments;
msgAttachments.Add(maAttach);
I hope this might help you.
Thanks
 

 



 

Sunday, 11 December 2011

How to Export Gridview Data to Excel and Word Document

I have one gridview that has filled with user details now I need to export gridview data to word or excel document based on selection. To implement this functionality first we need to design aspx page like this



<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td align="right">
<asp:ImageButton ID="btnExcel" runat="server" ImageUrl="~/ExcelImage.jpg"
onclick="btnExcel_Click" />
<asp:ImageButton ID="btnWord" runat="server" ImageUrl="~/WordImage.jpg"
onclick="btnWord_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView runat="server" ID="gvdetails" DataSourceID="dsdetails"  AllowPaging="true"AllowSorting="true" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="UserId" HeaderText="UserId" />
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<asp:SqlDataSource ID="dsdetails" runat="server"ConnectionString="<%$ConnectionStrings:dbconnection %>"
SelectCommand="select * from UserInformation"/>
</div>
</form>
</body>
</html>

Here don’t forgot to set the connection string in web.config file here I am getting database connection from web.config file for that reason you need to set the connectionstring in web.config file like this 
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings>

Now in code behind add this reference:

using System.IO;
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
/// <summary>
/// This event is used to export gridview data to word document
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnWord_Click(object sender, ImageClickEventArgs e)
{
gvdetails.AllowPaging = false;
gvdetails.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition"string.Format("attachment; filename={0}","Customers.doc"));
Response.Charset = "";
Response.ContentType = "application/ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
/// <summary>
/// This Event is used to export gridview data to Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition"string.Format("attachment; filename={0}""Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
//Change the Header Row back to white color
gvdetails.HeaderRow.Style.Add("background-color""#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
{
gvdetails.HeaderRow.Cells[i].Style.Add("background-color""#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in gvdetails.Rows)
{
gvrow.BackColor = Color.White;
if (j <= gvdetails.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color""#EFF3FB");
}
}
}
j++;
}
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

I hope this might help you.