Friday, January 4, 2008

Silverlight 2.0 Asset Enumeration

I did a post a while back about a cool trick to download bits in a zip file and save it all in an enumeration in the base application class that is built dynamically without knowing exactly what is in the zip. The earlier post was strickly Silverlight 1.0 javascript so here it is in Silverlight 2.0 C#.

So first I created some private properties in the base class:


private Downloader _DL = new Downloader();
private string _AssetEnumerationPath = "http://localhost:58377/TestSite/Assets.zip";
private AssetItem[] _AssetSourceEnum = null;
private string _Errors = string.Empty;
private Canvas _Item1 = null;
public Downloader AssetEnum = null;

So also instead of being industries and using JSON the index file is a CSV in the sample. So bascially I put a CSV file and three bits of xaml for the test project. Then in Page_Loaded we use a downloader, associate a few events and fire off the event at our zip file like this:


_DL.Open("GET", new Uri(_AssetEnumerationPath));
_DL.Completed += new EventHandler(_DL_Completed);
_DL.DownloadFailed += new ErrorEventHandler(_DL_DownloadFailed);
_DL.Send();

in our _DL_Completed then we pull out the index and we know what todo with whats in the file. In this case we save it at the root so it can be used or bound to things and we also can muck around with it in this case we pull out all the Xaml source and put it into an array. Anyway the entire mess can be downloaded as one zip and we don't have to muck with it. Each control we build can go grab what it needs out of the zip or out of some other array we cached at the root.


try
{
Downloader TempDL = sender as Downloader;
string[] NameArray = TempDL.GetResponseText("Assets/index.csv").Split(',');
_AssetSourceEnum = new AssetItem[NameArray.Length];
for (int x = 0; x < NameArray.Length; x++)
{
_AssetSourceEnum[x] = new AssetItem();
_AssetSourceEnum[x].Name = NameArray[x];
_AssetSourceEnum[x].Xaml = TempDL.GetResponseText("Assets/" + NameArray[x].ToString());
}
AssetEnum = TempDL;
}
catch (Exception E)
{
_Errors = E.Message;
}

simple nice and dirty.

No comments:

Post a Comment