Blog Pages

Friday, November 19, 2010

Silverlight compressed binary serialization

So... I did my first Silverlight app - very good fun (although there was a fair amount of head scratching too!)

As part of this app I needed to send some fairly chunky bits of data to the client. To do this I used http://whydoidoit.com/silverlight-serializer/ and http://slsharpziplib.codeplex.com/

On the server (in an offline process) the code that generated my compressed files looked like:

            using (var f = File.Create(zipFileName))
            {
                using (var zipOut = new ZipOutputStream(f))
                {
                    ZipEntry entry = new ZipEntry("stuff");
                    var toStore = Serialization.SilverlightSerializer.Serialize(myClass);
                    entry.DateTime = DateTime.Now;
                    entry.Size = toStore.Length;
                    zipOut.PutNextEntry(entry);
                    zipOut.Write(toStore, 0, toStore.Length);
                    zipOut.Finish();
                    zipOut.Close();
                }
            }

And in the Silverlight client the code looked like:

        public void LoadFrom(Uri url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.BeginGetResponse(new AsyncCallback(ReadCallback), request);
        }

        private void ReadCallback(IAsyncResult asynchronousResult)
        {
            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            using (ZipInputStream zipIn = new ZipInputStream(response.GetResponseStream()))
            {
                ZipEntry entry;
                if ((entry = zipIn.GetNextEntry()) != null)
                {
                    var myClass = Serialization.SilverlightSerializer.Deserialize<TheClass>(zipIn);
                    if (myClass == null)
                    {
                        MessageBox.Show("Some error has occurred - unable to read data - sorry!");
                        return;
                    }

                    Dispatcher.BeginInvoke(() =>
                        {
                           // do stuff with myClass here
                        });
                }
            }
        }

It all worked surprisingly well :)

No comments:

Post a Comment