Serializing DataSets is a known problem in the development community. As everyone knows DataSet will be serialized only into xml irrespective of the formatter which is used.Due to the circular reference we can’t serialize and pass the DataTable to a web service in .Net 1.1(These issues have been solved in .Net 2.0). When we serialize a DataSet it will be serialized into the DiffGram format which is a very expensive scheme.
Mr.Ravindra vupula explained a method to effectively serialize the dataset with his DataSetSurrogate class.Mr.Dino Espisito introduced the concept of ghost serializer which dramatically reduces the complexities of Data Set .
Here I used a simple method to serialize Data Set. The class will be having one array list and two array members and it is marked as serializable.Serializing the class can be effectively done without any of the issues that is associated with Data Set.
[Serializable]
public class template
{
private ArrayList _data=new ArrayList();
private string[] _columns;
private string[] _types;
public ArrayList Data
{
get
{
return _data;
}
set{
_data = value;
}
}
public string[] Cols
{
set
{
_columns=value;
}
}
public string[] Types
{
set{
_ types=value;
}
}
}
Code for serialization is as follows.I used lzocompressor to compress the resultant binary data.lzocompressor is written in unmanaged code but is much faster than the available compressors written in managed code.
public byte[] SerializeData(DataTable dtInput)
{
template temp=new template();
object[][] jar=new object[dtInput.Rows.Count][];
BinaryFormatter bi=new BinaryFormatter();
for(int d=0;d<dtInput.Rows.Count;d++)
{
jar[d]=dtInput.Rows[d].ItemArray ;
temp.Data.Add(jar[d]);
}
int colCount=dtInput.Columns.Count;
string[] ColName=new string[colCount];
string[] ColType=new string[colCount];
int k=0;
foreach(DataColumn dc in dtInput.Columns)
{
ColName[k]=dc.ColumnName;
ColType[k]=dc.DataType.FullName ;
k++;
}
temp.aCols= ColName;
temp.aTypes=ColType;
byte[] retBytes;
using(MemoryStream ms1=new MemoryStream())
{
bi.Serialize(ms1,temp);
retBytes=ms1.GetBuffer();
}
return retBytes;
}
Deserialization is the reverse process of this and that we can do easily like this.