Home > C# on .NET > How to transfer DataTable Object, using HTTP POST parameter

How to transfer DataTable Object, using HTTP POST parameter

 

Sending client appliction data to a web server has multiple ways to make it. In many cases, just string objects can be enough, such as parm1=”abc”&parm2=”123” within POST or GET parameters.

However, when you have complex data, or multiple records with various data types, you’d better consider to use DataTable, and send it to web server directly without maniplating strings at a client, and server codes again and again.

This code is to show you how to send DataTable object to a web server with data to use in a server-side.

 

Creating DataTable in a client-side application


 

C# code to create a DataTable, and add rows with data

 

DataTable dtUserAge = new DataTable();

dtUserAge.Columns.Add(new DataColumn("Name", typeof(string)));
dtUserAge.Columns.Add(new DataColumn("Age", typeof(int)));

dtUserAge.Rows.Add("Jennifer", 21);
dtUserAge.Rows.Add("Mary", 31);
dtUserAge.Rows.Add("Joon", 41);
dtUserAge.Rows.Add("John", 51);

 

 

Now, we have a DataTable with data to send

 

Converting DatatTable to ByteArray to build (http) POST parameter


 

This code can be used to get byte-array from DataTable parameter

 

private Byte[] DataTableToBytes(DataTable dtInput)
{
    BinaryFormatter bformatter = new BinaryFormatter();
    MemoryStream stream = new MemoryStream();

       bformatter.Serialize(stream, dtInput);
    byte[] b = stream.ToArray();
    stream.Close();
    return b;

}

 

We have byte-array to prepare POST parameter

 

Sending DataTable to a web server, using webBrowser control in a client app


For this example, let me use System.Windows.Forms.WebBrowser to send DataTable with POST parameter

 

 

private void btnSendData_Click(object sender, EventArgs e)
{

     string strURL = “http://localhost:57560/GetDataTable.aspx”;
     webBrowser1.Navigate(strURL, string.Empty, DataTableToBytes(dtUserAge), "Content-Type: application/x-www-form-urlencoded");

     ….

}

 

In ASP.NET – IIS server


 

As mentioned above, GetDataTable.aspx is to receive POST parameter in a server, ‘Request.InputStream’ is including the object to read.

POST data will be transformed as follows,
Stream > ByteArray > DataTable (dtUserAge)

 

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        DataTable dtUserAge = new DataTable();
        dtUserAge = ReadUserData(Request.InputStream);
    }
}

private DataTable ReadUserData(Stream ClientPostedData)
{
    Byte[] bytePostedData = StreamToByteArray(ClientPostedData);
    return BytesToDataTable(bytePostedData);
}

 

Now, we need Stream to ByteArray, and ByteArray to DataTable functions in aspx

 

 

private byte[] StreamToByteArray(Stream input)
{
   
    byte[] buffer = new byte[input.Length];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

 

private DataTable BytesToDataTable(Byte[] byteArray)
{
    DataTable dtResult = new DataTable();

    BinaryFormatter bformatter = new BinaryFormatter();
    MemoryStream stream = new MemoryStream();

    bformatter = new BinaryFormatter();
    stream = new MemoryStream(byteArray);
    dtResult = (DataTable)bformatter.Deserialize(stream);

    return dtResult;

}

 

You also need to add following using statements to run above codes,

 

using System.Data.SqlClient;
using System.IO;
using System.Data;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net;

 

So, it’s ready to work with DataTable(dtUserAge) in ASP.NET

 

Technical notes


 

Your client side application, probably a WinForm application, can send a DataTable object to handle data in ASP.NET applications using POST parameter.

Using GET instead of POST parameter, is not a good idea because of 2 reasons,

1. GET parameter is appended in URL text
2. GET parameter has size limitation, much smaller than POST

Why not asmx?

Using a web service, a server-side web application (.asmx) can be more simple, and secure, it can send byte-array as just one of web service parameters. I use this sample for ChartFX application which requires response of HTML/DHTML with images from IIS, which can be more complicated I try this using asmx.

Sending multiple DataTable objects at once

I could make this work by using Dictionary as follows,

 

public Byte[] BuildHTTPPostParameters(DataTable dtChartData)
{
    var parms = new Dictionary<string, Byte[]>();
    parms.Add("CHART_SETTINGS", DataTableToBytes(dtChartSettings));
    parms.Add("MAIN_CHART_DATA", DataTableToBytes(dtChartData));

    return DictionaryToByteArray(parms);

}

private Byte[] DictionaryToByteArray(Object obj)
{

    var binFormatter = new BinaryFormatter();
    var mStream = new MemoryStream();
    binFormatter.Serialize(mStream, obj);
    return mStream.ToArray();

}

 

 

In this case – using Dictionary to send DataTables, this makes simple to send more than 2 DataTables for chart data including data for sub charts at once, and this type of data transfer may requires an aspx page option – validateRequest="false" to avoid a validation error of HTTP parameter.

 

Hope this helps,

Advertisements
Categories: C# on .NET
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: