A personal repository of technical notes. - CSC

Transfer DataTable with HTTP Response

Problem
Need a simple way to transfer data with an HTTP web request/response.

Solution
Convert a DataTable to XML, transfer with HTTP, convert XML back to DataTable.

Note: This was tested with .NET 4

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

SimpleDataTableExport.aspx.cs
using System;
using System.Data;
using System.Xml;

/// <summary>
/// Simple web page to export a DataTable through an HTTP response.
/// </summary>
public partial class SimpleDataTableExport : System.Web.UI.Page
{
       protected void Page_Load(object sender, EventArgs e)
       {
              // Start response
              Response.ClearHeaders();
              Response.ClearContent();

              DataTable dataTable = null;
              try
              {
                     dataTable = GetDataTable();
              }
              catch (Exception ex)
              {
                     dataTable = null;
                     Response.StatusCode = 500;
                     Response.StatusDescription = ex.Message;
                     Response.Write(String.Format("Error message: {0}", ex.Message));
              }
              finally
              {
                     if (dataTable != null)
                     {
                           // DataTable is converted to XML and sent to the output stream.
                           XmlWriter xmlWriter = XmlWriter.Create(Response.OutputStream);
                           dataTable.WriteXml(xmlWriter, XmlWriteMode.WriteSchema);
                     }
              }

              // Complete response
              Response.Flush();
              ApplicationInstance.CompleteRequest();
       }

       private DataTable GetDataTable()
       {
              // Validate input parameters passed in query string.
              if (String.IsNullOrEmpty(Request.QueryString["parm01"]))
              {
                     throw new ApplicationException("Required parameter 'parm01' is missing.");
              }

              // Generate DataTable
              DataTable table = new DataTable("MyDataTable");
              table.Columns.Add("Column01");
              table.Columns.Add("Column02");
              DataRow row = table.NewRow();
              row["Column01"] = String.Format("'parm01' is {0}", Request.QueryString["parm01"]);
              row["Column02"] = "Value for Column02";
              table.Rows.Add(row);

              return table;
       }
}

Console application to import DataTable

using System;
using System.Data;
using System.Net;
using System.Xml;

namespace SimpleDataTableImport
{
       /// <summary>
       /// Simple Console Application to import a DataTable through an HTTP request.
       /// </summary>
       class Program
       {
              static void Main(string[] args)
              {

                     DataTable dataTable = new DataTable();
                     string errorMessage = null;

                     HttpWebRequest httpWebRequest;
                     HttpWebResponse httpWebResponse = null;
                     try
                     {
                           httpWebRequest = WebRequest.Create("http://localhost/SimpleDataTableExport.aspx?parm01=helloworld") as HttpWebRequest;
                           httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
                           XmlReader xmlReader = XmlReader.Create(httpWebResponse.GetResponseStream());
                           dataTable.ReadXml(xmlReader);
                     }
                     catch (WebException webEx)
                     {
                           httpWebResponse = webEx.Response as HttpWebResponse;
                           errorMessage = String.Format("{0} - {1}", Convert.ToInt32(httpWebResponse.StatusCode).ToString(), httpWebResponse.StatusDescription);
                     }
                     catch (Exception ex)
                     {
                           errorMessage = ex.Message;
                     }
                     if (httpWebResponse != null)
                     {
                           httpWebResponse.Close();
                     }
                     if (errorMessage != null)
                     {
                           Console.WriteLine(errorMessage);
                     }

                     // Display DataTable
                     foreach (DataColumn column in dataTable.Columns)
                     {
                           Console.WriteLine(column.ColumnName);
                     }
                     foreach (DataRow row in dataTable.Rows)
                     {
                           Console.WriteLine(String.Format("{0},{1}", row["Column01"], row["Column02"]));
                     }

                     Console.ReadLine();
              }
       }
}

Results

No comments:

Post a Comment