Ah, the ASP.NET LosFormatter – it’s a wonderful thing. I’m working on this resource provider and one of the things it has to do is deal with resources other than strings. There are a examples in several places that do a really half assed job of dealing with object resources that either don’t work or are horrendously complex.
But using the LosFormatter is a great way to do this easily with just a few lines of code. The really nice thing about the LosFormatter is that it encodes the type information right into the formatted output. So you don’t need to deal with figuring out exactly what type the object is and instantiating it. The LosFormatter takes care of this…
So to serialize a value like a Bitmap code like this can be used:
LosFormatter output = new LosFormatter();
StringWriter writer = new StringWriter();
Value = writer.ToString();
The LosFormatter formats the output into a Hex string, which is perfect for storage in the database as well even if it’s a bit more verbose than the equivalent binary code that the plain old Binary Serializer would produce.
To get the value back out is even easier:
string StringValue = reader["Value"] as string;
LosFormatter Formatter = new LosFormatter();
object Result = Formatter.Deserialize( StringValue );
One of the reasons I like this approach over the binary serialization is that all code can now run pretty much a single datapath to get the data out of the database rather than having to check whether it’s dealing with strings or ‘other types’. This greatly reduces the complexity of the code for the various read and write operations.
There’s a caveat with this though just as there is with binary serialization: It requires full trust or that the assembly is in the GAC. I’ve taken to running my Web apps in dev mode in Medium trust to see where things go wrong and this was one of them.
Incidentally Serialization is one of the big problems for medium trust applications – I have lots of places where I use Serialization for persistence in various places and it all falls in Medium Trust. Not just in Web apps – Serialization is also severely restricted in low rights desktop apps. Bummer…
Other Posts you might also like