Breaking News

Editors Picks

Friday, June 29, 2012

Downloading file using asp.net and C#


Default .aspx  page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Downloading file using asp.net and C# title>
head>
<body>
    <form id="form1" runat="server">
    <div>
   If file is in the same web server where web application or website is running:
        <br />
    <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Downloads/Downloads.zip">Downloadasp:HyperLink>
        <br />
        OR
        <br />
        <asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="http://sitename/Download/Downloads.zip">Downloadasp:HyperLink>
        <br />
        <br />
        programmatically downloading a file from web server to client
        <br />
        <asp:LinkButton ID="Downloadfile" runat="server" OnClick="Downloadfile_Click">Downloadasp:LinkButton>
    div>
    form>
body>
html>

Default .aspx.cs  page

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Downloadfile_Click(object sender, EventArgs e)
    {
        HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create("http://sitename/Download/Downloads.zip");
        HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
        int bufferSize = 1;
        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.AppendHeader("Content-Disposition:", "attachment; filename=Sample.zip");
        Response.AppendHeader("Content-Length", objResponse.ContentLength.ToString());
        Response.ContentType = "application/download";
        byte[] byteBuffer = new byte[bufferSize + 1];
        MemoryStream memStrm = new MemoryStream(byteBuffer, true);
        Stream strm = objRequest.GetResponse().GetResponseStream();
        byte[] bytes = new byte[bufferSize + 1];
        while (strm.Read(byteBuffer, 0, byteBuffer.Length) > 0)
        {
            Response.BinaryWrite(memStrm.ToArray());
            Response.Flush();
        }
        Response.Close();
        Response.End();
        memStrm.Close();
        memStrm.Dispose();
        strm.Dispose();
    }
}


Read more ...

Thursday, June 28, 2012

Multiply Time in C#


  string a = "8:25";
  int n = 2;//multiply by
  string[] time = a.Split(':');
  string output = string.Empty;
  int c = (int.Parse(time[0]) * 60 + int.Parse(time[1])) * n;
  if (c % 60 == 0)
     { output = (c / 60).ToString(); }
  else
     output = (c / 60).ToString() + ":" + (c % 60).ToString();                
Read more ...

Thursday, June 21, 2012

How to export aspx page to excel


protected void Button1_Click(object sender, EventArgs e)
{ 
   string attachment = "attachment; filename=filename.xls";
   Response.ClearContent();
   Response.AddHeader("content-disposition", attachment);
   Response.ContentType = "application/ms-excel";
}
Read more ...

Tuesday, June 19, 2012

export to excel in asp.net multiple sheets



public void dataexport()
{
  ToExcel(ds, "filename.xls", Page.Response);
}

private static string getWorkbookTemplate()
{
var sb = new StringBuilder(818);
sb.AppendFormat(@"{0}", Environment.NewLine);
sb.AppendFormat(@"{0}", Environment.NewLine);
sb.AppendFormat(@", Environment.NewLine);
sb.AppendFormat(@" xmlns:o=""urn:schemas-microsoft-com:office:office""{0}", Environment.NewLine);
sb.AppendFormat(@" xmlns:x=""urn:schemas-microsoft-com:office:excel""{0}", Environment.NewLine);
sb.AppendFormat(@" xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""{0}", Environment.NewLine);
sb.AppendFormat(@" xmlns:html=""http://www.w3.org/TR/REC-html40"">{0}", Environment.NewLine);
sb.AppendFormat(@" {0}", Environment.NewLine);
sb.AppendFormat(@"  {0}", Environment.NewLine);
sb.AppendFormat(@"  {0}", Environment.NewLine);
sb.AppendFormat(@"  {0}", Environment.NewLine);
sb.AppendFormat(@" {0}", Environment.NewLine);
sb.Append(@"{0}\r\n");
return sb.ToString();
}

private static string replaceXmlChar(string input)
{
  input = input.Replace("&", "&amp");
  input = input.Replace("<", "<");
  input = input.Replace(">", ">");
  input = input.Replace("\"", """);
  input = input.Replace("'", "'");
  return input;
}

private static string getCell(Type type, object cellData)
{
var data = (cellData is DBNull) ? "" : cellData;
if (type.Name.Contains("Int") || type.Name.Contains("Double") || type.Name.Contains("Decimal")) return string.Format("{0}", data);
if (type.Name.Contains("Date") && data.ToString() != string.Empty)
{
return string.Format("{0}", Convert.ToDateTime(data).ToString("yyyy-MM-dd"));
}
return string.Format("{0}", replaceXmlChar(data.ToString()));
}
private static string getWorksheets(DataSet source)
{
var sw = new StringWriter();
if (source == null || source.Tables.Count == 0)
{
sw.Write("\r\n
\r\n\r\n
\r\n");
return sw.ToString();
}
foreach (DataTable dt in source.Tables)
{
if (dt.Rows.Count == 0)
sw.Write(" + replaceXmlChar(dt.TableName) + "\">\r\n
\r\n  ss:StyleID=\"s62\">\r\n
\r\n");
else
{
//write each row data
var sheetCount = 0;
for (int i = 0; i < dt.Rows.Count; i++)
{
if ((i % rowLimit) == 0)
{
//add close tags for previous sheet of the same data table
if ((i / rowLimit) > sheetCount)
{
sw.Write("\r\n\r\n");
sheetCount = (i / rowLimit);
}
sw.Write("\r\n + replaceXmlChar(dt.TableName) +
(((i / rowLimit) == 0) ? "" : Convert.ToString(i / rowLimit)) + "\">\r\n
");
//write column name row
sw.Write("\r\n");
foreach (DataColumn dc in dt.Columns)
sw.Write(string.Format("{0}", replaceXmlChar(dc.ColumnName)));
sw.Write("");
}
sw.Write("\r\n");
foreach (DataColumn dc in dt.Columns)
sw.Write(getCell(dc.DataType, dt.Rows[i][dc.ColumnName]));
sw.Write("");
}
sw.Write("\r\n
\r\n");
}
}

return sw.ToString();
}
public static string GetExcelXml(DataTable dtInput, string filename)
{
  var excelTemplate = getWorkbookTemplate();
  var ds = new DataSet();
  ds.Tables.Add(dtInput.Copy());
  var worksheets = getWorksheets(ds);
  var excelXml = string.Format(excelTemplate, worksheets);
  return excelXml;
}

public static string GetExcelXml(DataSet dsInput, string filename)
{
  var excelTemplate = getWorkbookTemplate();
  var worksheets = getWorksheets(dsInput);
  var excelXml = string.Format(excelTemplate, worksheets);
  return excelXml;
}

public static void ToExcel(DataSet dsInput, string filename, HttpResponse response)
{
  var excelXml = GetExcelXml(dsInput, filename);

  response.Clear();
  response.Buffer = true;
  response.BufferOutput = true;
  response.Charset = "UTF-8";
  response.ContentEncoding = System.Text.Encoding.UTF8;
  response.AppendHeader("Content-Type", "application/vnd.ms-excel");
  response.AppendHeader("Content-disposition", "attachment; filename=" +   filename);
  response.Write(excelXml);
  response.Flush();
  response.End();

}

public static void ToExcel(DataTable dtInput, string filename, HttpResponse response)
{
  var ds = new DataSet();
  ds.Tables.Add(dtInput.Copy());
  ToExcel(ds, filename, response);
}
Read more ...

Contact Us

Name

Email *

Message *