Thursday, July 5, 2012
Merry Ghandi
Ghandi, an extremely spirtual person, who walked barefoot to the extent that he had heavy callouses on his feet, and whose poor diet resulted in extremely bad breath, soon became known as the super callous fragile mystic, plagued with hallatosis.
Thursday, February 9, 2012
My slogan pitch to the folks who make Trojan Condoms
"...with great pleasure, comes great responsibility."
Friday, February 3, 2012
How to Serialize and Deserialize a class containing DateTimeOffset members in C#
The proper way to serialize and deserialize DateTimeOffset in XML is to use the DataContractSerializer instead of the standard XmlSerializer. The reason is that the XMLSerializer does not support certain aspects of the DateTimeOffset structure (don't ask me what they are, but that's what Microsoft states is their reasoning for not supporting it). I tend to try and code using generics whenever possible, especially when it's stuff like this.
Thus, here's an example of how to serialize any class using it (I'm using UTF8 encoding here, but you can use whatever you like):
Thus, here's an example of how to serialize any class using it (I'm using UTF8 encoding here, but you can use whatever you like):
public static string SerializeObject<T>(T instance) where T : class
{
try
{
MemoryStream stream = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(stream, instance);
return new UTF8Encoding().GetString(stream.ToArray());
}
catch(Exception ex)
{
...
}
}
And here's how to deserialize it again:
public static T DeserializeObject<T>(string data) where T : class
{
try
{
MemoryStream memoryStream = new MemoryStream(new UTF8Encoding().GetBytes(data));
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(memoryStream);
}
catch
{
...
}
}
Subscribe to:
Posts (Atom)