Binary Serialization and Azure Web Applications

You might be thinking, pfft, I'm never going to need to use Binary Serialization...that's old school. And you might be right, but think about this: Azure Storage charges you by how much you're storing and some aspects of Azure also charge you based on the bandwidth consumed. Do you want to store/transmit a big-ass bloated pile of XML or do you want to store/transmit a condensed binary serialization of your object graph?

I'm using Blob and Queue storage for several things and I've actually got a couple of projects going right now where I'm using binary serialization for both Blobs and Queue messages. The problem shows up when you try and use the BinaryFormatter class' Serialize method. This method requires the Security privilege, which your code doesn't have when its running in the default Azure configuration.

So how do you fix this problem so that you can successfully serialize/deserialize binary object graphs and maybe save a buck or two? Easy! Turn on full-trust in your service definition for whichever role is going to be using the binary serialization (in my case both my worker and web roles will be using it...). To do this, open up your service definition file and look for the line that looks like this: 

<WebRole name="Foo.Web" enableNativeCodeExecution="false">

And change it to this:

<WebRole name="Foo.Web" enableNativeCodeExecution="true">

You'll have to do this for your WorkerRole as well if you want your worker role to be able to do this kind of serialization. That's it...Now when you run your application it will have sufficient privileges to perform the serialization/deserialization to keep your storage and transmission payloads as small as possible.

© 2008 SYS-CON Media