Friday, January 6, 2012

Binding dynamic XML objects to Silverlight Grids

Recently we had an requirement to bind the content of dynamic XML to Silverlight Grids.This is straightforward in ASP.NET with the help of DataSet. But we do not have DataSet in Silverlight or WPF. To achieve this we used the following approach;


The code is self-explanatory with the comments explaining each step;


public string Result
{
get
{
return _result;
}
set
{
System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//Load the xml string to XDocument
XDocument doc = XDocument.Load(new StringReader(value));
MemoryStream str = new System.IO.MemoryStream();
doc.Save(str);


//Finding the Name of the class
string objName = doc.Descendants().First().Name.LocalName.Replace("ArrayOf", "");


//Making it a fully qualified name by appending the corresponding
//namespace
objName = "MyCompany.MyApplication." + objName;


//Loading the assembly that contains the Entity which
//we are trying to de-serialize
//NOTE: To be able to do the below 3 steps, you need to ensure that
//the entities dll reference is added in Deployment.Parts of the
//App Manifest file
StreamResourceInfo sri = Application.GetResourceStream(new Uri("MyApplication.SL.Entities.dll",UriKind.Relative));
AssemblyPart myPart = new AssemblyPart();
System.Reflection.Assembly assm = myPart.Load(sri.Stream);


//Using reflection to build the List<T>
var pageToShowType = assm.GetType(objName);
Type t = typeof(List<>);
Type [] args = {pageToShowType};
Type r = t.MakeGenericType(args);


//De-serializing and assigning to the property to show in the grid
str.Position = 0;
DataContractSerializer serializer = new DataContractSerializer(r);
//Bind the ResultObject to the SL Grid
//NOTE: Ensure that SL Grid has AutoGenerateColumns = TRUE
ResultObject = serializer.ReadObject(str);
str.Close();


});


}


}