|
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.
Very nice! It does raise the question though why that setting is in there
and what loopholes you open up by toggling that switch.
Its not like you're opening loopholes, really. That type of pattern of
"secure by default" is a best practice when building safe software. You
never want your code to be able to do anything potentially harmful unless
you specifically know what you're doing. In other words, by default you
want all of your Azure stuff to run untrusted. If you absolutely have to
trust your code (in order to access things like the binary serializer,
which accesses Reflection, which requires security permissions) then you
are required to manually flip the switch ... which is sort of a tacit
admission that you know what the hell you're doing :)