.NET: Passing a DataSet through the ExtendedProperties of another DataSet

 Sometimes you find the need to pass more than one DataSet as the result of a routine/function.  Although you can use reference parameters for doing so, there's another approach.

You can pass additional DataSets by adding them to the ExtendedProperties property of the "main" DataSet.  ExtendedProperties is defined as being of type PropertyCollection, which inherits from the Hashtable type, so its limit depends on the amount of memory that the host machine has.

A limitation that becomes apparent when using .NET remoting is that the values stored in the ExtendedProperties should be of type string in order to be persistent when it crosses the application domains between the server and the client.  With this limitation in mind, the steps are roughly as follows:

1.   Convert the "additional" DataSet to string.
2.   Store the result of step 1 in the ExtendedProperties of the "main" DataSet.
3.   Pass/return the "main" DataSet to the calling process.
4.   Convert the string representation of the "additional" DataSet back.

Essential routines/information:
Step 1:
The DataSet class has a GetXml method that returns the XML representation of the DataSet.

Steps 2 & 3:
Self explanatory.

Step 4:
The DataSet class has a ReadXml method for initalizing a DataSet based on XML.

Combining all the information, the code can look something like this:
==== START OF SAMPLE CODE ====
// SAMPLE FUNCTION (SampleFunction())
....
using System.Data;
....
DataSet dsMain;
DataSet dsSub;
....
// Populate the DataSets here
...
string dsSubAsString;
dsSubAsString = dsSub.GetXml();
dsMain.ExtendedProperties.Add("dsSub", dsSubAsString);
...
// Pass dsMain to calling routine/function


// CALLING FUNCTION
...
using System.Data;
using System.IO;
...
DataSet dsMainReturn;
DataSet dsSubReturn;

// Call function to retrieve the DataSets
// and convert dsSub
...
dsMainReturn = SampleFunction();
dsSubReturn = new DataSet();

string dsSubReturnAsString = (string) dsMainReturn.ExtendedProperties["dsSub"];

using (System.IO.StringReader sr = new StringReader(dsSubReturnAsString))
{
    dsSubReturn.ReadXml(sr, XmlReadMode.InferSchema);
}

...
// Use dsSubReturn as required
...
==== END OF SAMPLE CODE ====


And there you have it.  Taking it a step further, the code for conversion from XML/string to DataSet can be wrapped as a function in a helper class, so as not to affect programmer productivity. :)

Published 05-30-2007 3:41 PM by raistlin
Filed under: , ,