Wednesday 20 February 2013

How to export DataTable into Excel file in ASP.NET

There is a one simple function written below, which takes datatable as a parameter and give it popup to user to save the file as an excel file.
Copy and paste file in your code, and call this function on Event where it required

using System;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;
protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Qualification", typeof(string));
        dt.Rows.Add("Raja", "M.B.A");
        dt.Rows.Add("Durai", "M.B.B.S");
        dt.Rows.Add("SRD", "BE");
        ExportToExcel(dt);
    }

public void ExportToExcel(DataTable dt)
    {
        if (dt.Rows.Count > 0)
        {
            string filename = "Raja.xls";
            string excelHeader = "Raja Report";
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            DataGrid dgGrid = new DataGrid();
            dgGrid.DataSource = dt;
            dgGrid.DataBind();
            // Report Header
            hw.WriteLine("<b><u><font size='3'> " + excelHeader + " </font></u></b>");
            //Get the HTML for the control.
            dgGrid.RenderControl(hw);
            //Write the HTML back to the browser.          
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
            this.EnableViewState = false;
            Response.Write(tw.ToString());
            Response.End();
        }
    }

 

Export DataTable To MicroSoft Word In C#

we have Export the DataTable as a Word Format. I hope the below code is useful to us.

using System;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;

protected void Page_Load(object sender, EventArgs e)
    {
        ExportToWord();
    }

protected void ExportToWord()
    {      
        DataTable dt = new DataTable();
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Qualification", typeof(string));
        dt.Rows.Add("Raja", "M.B.A");
        dt.Rows.Add("Durai", "M.B.B.S");
        dt.Rows.Add("SRD", "BE");
        //Create a dummy GridView
        GridView GridView1 = new GridView();
        GridView1.AllowPaging = false;
        GridView1.DataSource = dt;
        GridView1.DataBind();
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition",
        "attachment;filename=DataTable.doc");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-word ";
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.RenderControl(hw);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
 

Friday 15 February 2013

Send Table Format Mail Using C#



DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Place", typeof(string));
dt.Rows.Add(“Raja”,”KanyaKumari”);
dt.Rows.Add(“Durai”,”KanyaKumari”);

string str1 = "", str2 = "", str3 = "";
str2 = "<table border =1 bordercolor=black cellspacing=0 cellpadding=0 >";

str2 += "<tr><td width=100px align=center><b>Name</b><b></td><td width=100px align=center><b>Place</b></td>>/tr>”;

foreach (DataRow r in dt.Rows)
{
  str2 += "<tr><td> <font color=blue><i><center>" + r[0].ToString() + "</center></i></font></td>";
  str2 += "<td><font color=blue><i><center>" + r[1].ToString() + "</center></i></font></td></tr>";
}

try
  {
   MailMessage mailmsg = new MailMessage();
   mailmsg.From = new MailAddress("raja30march90@Gmail.com");
   mailmsg.To.Add(raja30march90@Gmail.com);
   mailmsg.CC.Add(raja30march90@Gmail.com);
   mailmsg.Subject = "V-EnerTek Expense WorkAllocated";
   mailmsg.IsBodyHtml = true;

   str1 = "<html><body> <br/>" +
        "<br/><b>" + “Example”</b> <br/>" +
                               "<br/>" +
         "Name: " + “Raja Durai+
                              "<br/>";


   str3 = "<br/>" +
     "With Regards,<br/>" + “Raja.S” + "<br/>" +
                              "<br/>" +
                              "<br/>" +
                              "<br/>" +
"</body></html>";
mailmsg.Body = str1.ToString() + " " + str2.ToString() + " " + str3.ToString();
  SmtpClient smtpclt = new SmtpClient();
  smtpclt.Host = "127.0.0.1";
  smtpclt.Send(mailmsg);

}
 

Check Image Extensions In FileUpload OnChange in C# JQuery



 Type The Below Query In ASPX page....

function checkFileExtension(elem) {
            var filePath = elem.value;
           
            var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
            var validExtensions;


            validExtensions = new Array();
            validExtensions[0] = 'jpg';
            validExtensions[1] = 'jpeg';
            validExtensions[2] = 'bmp';
            validExtensions[3] = 'png';
            validExtensions[4] = 'gif';


            for (var i = 0; i < validExtensions.length; i++) {
                if (ext == validExtensions[i])
                    return true;
            }
            alert('The file extension ' + ext.toUpperCase() + ' is not allowed!');
            elem.value = "";
            return false;
        }

 Type The Below Query In ASPX.CS page Load....


protected void Page_Load(object sender, EventArgs e)
{
ImageUpload.Attributes.Add("onchange", "return checkFileExtension(this);");
}
 



Export DataTable To Pdf & Download in C#

Add  " iTextSharp " dll in your project...
 then add


using iTextSharp.text;
using iTextSharp.text.pdf;

Namespace 

Then Give The Query Same As Given Below...



public partial class VideoPlayer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {      
        DataTable dt = new DataTable();
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Qualification", typeof(string));
        dt.Rows.Add("Raja", "M.B.A");
        dt.Rows.Add("Durai", "M.B.B.S");
        dt.Rows.Add("SRD", "BE");
       GeneratePDF(dt);
    }
   
    private void GeneratePDF(DataTable dataTable)
    {
        Document pdfDoc = new Document(PageSize.A4, 30, 30, 40, 25);
        System.IO.MemoryStream mStream = new System.IO.MemoryStream();
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
        int cols = dataTable.Columns.Count;
        int rows = dataTable.Rows.Count;
        pdfDoc.Open();

        iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
        pdfTable.BorderWidth = 1;     
        pdfTable.Padding = 1;
        pdfTable.Spacing = 1;

        //creating table headers
        for (int i = 0; i < cols; i++)
        {
            Cell cellCols = new Cell();
            Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 12, Font.BOLD);
            Chunk chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);
            cellCols.Add(chunkCols);
            pdfTable.AddCell(cellCols);

        }
        //creating table data (actual result)
        for (int k = 0; k < rows; k++)
        {
            for (int j = 0; j < cols; j++)
            {
                Cell cellRows = new Cell();
                Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
                Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
                cellRows.Add(chunkRows);
                pdfTable.AddCell(cellRows);

            }
        }

        pdfDoc.Add(pdfTable);
        pdfDoc.Close();
        Response.ContentType = "application/octet-stream";
        Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
        Response.Clear();
        Response.BinaryWrite(mStream.ToArray());
        Response.End();
     
    }
}

How to make secure web application



Step1->The best way to add logout button in your master page instead of each page in your application
 
Demonstration:- <asp:LinkButton ID="lnk" runat="server" Text="Logout" ForeColor="white"
                onclick="lnk_Click" CausesValidation="false"></asp:LinkButton>

Step2-> Now remove the session from cache, To do it, write the following code in page_load event of your master page in which you have logout button.

Demonstration:-

                           protected void Page_Load(object sender, EventArgs e)
                            {
                                     Response.Cache.SetCacheability(HttpCacheability.NoCache);
                             }

Step3-> Now write the following code in click event of link button

Demonstration:-
                         protected void lnk_Click(object sender, EventArgs e)
                                   {
                                       Session.Abandon();      
                                        Response.Redirect("~/Home.aspx");
                                   }

After performing all these steps your logout button will perform fine,
If you want to make more secure of your web application then you need to add Global.asax file in your web application. We define an event in this file that will perform globally and provide security from intruders.

Step1-> *Right click on your web application .
             *Add new item.
             *Add Global.asax file.

Step2-> Write a function in your Global.asax file as mention below.

                       void session_start()
                            {
                              if (Session["usr"] == null)
                                {
                                     Response.Redirect("~/Home.aspx");
                                    //Here you can write the address of your home page or index page
                                    // Or which you want to make start page.
                                 }
                          }


Now your web application is secure.

Tuesday 12 February 2013

ASP.NET Page Lifecycle

ASP.NET Page LifeCycle Summary

Here is a summary of the events (and method) which get fired during the processing of the ASP.NET Page Life Cycle as of .NET 4.0.

PreInit
Init
InitComplete
PreLoad
Load
Control events
LoadComplete
PreRender
PreRenderComplete
SaveStateComplete
Render
Unload

PreInit

  • Create dynamic controls
  • Set Master Page dynamically
  • Set Theme dynamically
  • Set/Get Profile properties

Init

  • Control Init fires before Page Init
  • Set/Get Control properties
  • Don't access other controls

InitComplete

  • ViewState tracking switched on
  • Control(s) are accessible but won't have their user data set yet

PreLoad

  • Raised after ViewState has been loaded for Page and Control(s)
  • Raised after processing postback data in Request

Load

  • Load called for Page and then the child Controls recursively
  • Set Control properties and database connections
  • ViewState and POST data available
  • Other Control(s) in Page hierarchy are accessible

Control events eg Button Click

  • Check Page.IsValid where required in code

LoadComplete

  • All controls loaded
  • Postback data and ViewState has been loaded into Page and Control(s)

PreRender

  • PreRender called for Page and then child Control(s) recursively
  • Final changes to Page and Controls before rendering begins

PreRenderComplete

  • Raised after each Control's DataBind is called, which is called when DataSourceID is set
  • Last event before ViewState is saved

SaveStateComplete

  • Raised after ViewState and Control state saved for Page and Control(s)
  • Changes here affect this Page rendering but will not be persisted on a Postback

Render (method not an event)

  • Method not an event
  • Page calls Render on each Control
  • Writes out markup for browser
  • Override in a custom control for custom markup

Unload

  • Cleanup code (such as closing database connections and closing files)
  • Page and Control(s) already rendered so can't be changed

ASP.NET Page LifeCycle Example

Here is a simple example which overrides each of the event handlers for these events and the Render method, as this is not an event. Notice the inclusion of a button onclick event handler which isn't currently utilised. The following shows the HTML output:

OnPreInit
OnInit
OnInitComplete
OnPreLoad
OnLoad
OnLoadComplete
OnPreRender
OnPreRenderComplete
OnSaveStateComplete
Render


using System;
using System.Web.UI;

namespace PageLifeCycle
{
    public partial class _Default : System.Web.UI.Page
    {
        protected override void OnPreInit(EventArgs e)
        {
            Response.Write("OnPreInit <br />");
            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e)
        {
            Response.Write("OnInit <br />");
            base.OnInit(e);
        }

        protected override void OnInitComplete(EventArgs e)
        {
            Response.Write("OnInitComplete <br />");
            base.OnInitComplete(e);
        }

        protected override void OnPreLoad(EventArgs e)
        {
            Response.Write("OnPreLoad <br />");
            base.OnPreLoad(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            Response.Write("OnLoad <br />");
            base.OnLoad(e);
        }

        protected void Button_Postback_Click(object sender, EventArgs e)
        {
            Response.Write("Button OnClick on Postback <br />");
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            Response.Write("OnLoadComplete <br />");
            base.OnLoadComplete(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            Response.Write("OnPreRender <br />");
            base.OnPreRender(e);
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            Response.Write("OnPreRenderComplete <br />");
            base.OnPreRenderComplete(e);
        }

        protected override void OnSaveStateComplete(EventArgs e)
        {
            Response.Write("OnSaveStateComplete <br />");
            base.OnSaveStateComplete(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            Response.Write("Render <br />");
            base.Render(writer);
        }

        protected override void OnUnload(EventArgs e)
        {
            // Response.Write("OnUnload <br />");
            // generates Exception:
            // Response is not available in this context.
            base.OnUnload(e);
        }
    }
}


Print Code in jquery

 
function CallPrint(strid) {
            var prtContent = document.getElementById(strid);
            var WinPrint =
window.open('', '', 'letf=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,sta­tus=0');
            WinPrint.document.write(prtContent.innerHTML);
            WinPrint.document.close();
            WinPrint.focus();
            WinPrint.print();
            WinPrint.close();
            prtContent.innerHTML = strOldOne;
        }


 <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="javascript:CallPrint('divPrint');" />

Javascript for calculating age


Javascript for calculating age



<script type="text/javascript">
       function showAge() {
          
           var d = document.getElementById('<%= txtDateOfBirth.ClientID %>').value.split('/');
           var today = new Date();
           var bday = new Date(d[2], d[1], d[0]);
           var by = bday.getFullYear();
           var bm = bday.getMonth() - 1;
           var bd = bday.getDate();
           var age = 0; var dif = bday;
           while (dif <= today) {
               var dif = new Date(by + age, bm, bd);
               age++;
           }
           age += -2;
           document.getElementById("<%=txtCurrentAge.ClientID %>").value = age;
           alert('You are ' + age + ' years old')
       }
</script>

//On page load ..
this.txtDateOfBirth.Attributes.Add("OnBlur", "javascript:return  showAge();");