Exporting datatables to CSV

One thing I often find myself doing is writing code allowing data to be exported to CSV files so that clients can download it, and create reports using an application like Excel. Here’s a small class to make the process a little easier, which I thought might be helpful to other developers.

public class Exporter
{
 private DataTable m_DataTable;
 private string m_Filename;
 public Exporter()
 {
 }
 public DataTable Source
 {
  set { m_DataTable = value; }
 }
 public string Filename
 {
  set { m_Filename = value;  }
  get { return m_Filename;   }
 }
 public void Export()
 {
  if (m_DataTable == null) throw (new NullReferenceException("Datasource"));
  if (m_Filename == null) throw (new NullReferenceException("Filename"));
  string Header = string.Format("attachment;filename={0}", m_Filename);
  string Data = ConvertToCSV();
  System.Web.HttpContext.Current.Response.ClearHeaders();
  System.Web.HttpContext.Current.
     Response.AddHeader("Content-disposition", Header);
  System.Web.HttpContext.Current.Response.Write(Data);
  System.Web.HttpContext.Current.Response.End();
 }
 private string ConvertToCSV()
 {
  StringBuilder SB = new StringBuilder();
  foreach (DataColumn column in m_DataTable.Columns)
  {
   SB.Append(string.Format("{0},", column.ColumnName));
  }
  SB.Append("\n");
  foreach (DataRow row in m_DataTable.Rows)
  {
   foreach (DataColumn column in m_DataTable.Columns)
   {
    SB.Append(string.Format("\"{0}\",", row[column].ToString()));
   }
   SB.Append("\n");
  }
  SB.Append("\n");
  return (SB.ToString());
 }
}

Usage:

Exporter CSVExporter = new Exporter();
CSVExporter.Source = myDataTable;
CSVExporter.Filename = "ExportedData.CSV";
CSVExporter.Export();

Http Authentication for IIS

Protecting web content in IIS can be a hassle, requiring setting up windows user accounts, permissions, etc, to allow authorised parties to access restricted web content.

IIS Mods have an IIS Authentication Filter for IIS which supports authenticating users against a text file or database. However, the product is awkward to set-up, feels incomplete, and documentation is poor.

A cheaper alternative is IISPassword by Troxo. This great utility is easy to install and manage. Coupled with the fact that it’s free, makes it even more attractive.

If you’re looking to secure web content in IIS using Http authentication, then this tool is essential.