Here's a snip of code that I use for serz'ing objects
public static string XmlString<X>(X obj, bool omitXmlDeclaration = false, bool omitNameSpace = false)
{
var xSer = new XmlSerializer(typeof(X));
var settings = new XmlWriterSettings() { OmitXmlDeclaration = omitXmlDeclaration, Indent = true, Encoding = new UTF8Encoding(false) };
using (var ms = new MemoryStream())
using (var writer = XmlWriter.Create(ms, settings))
{
if (!omitNameSpace)
{
xSer.Serialize(writer, obj);
}
else
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
xSer.Serialize(writer, obj, ns);
}
ms.Seek(0, 0);
return new UTF8Encoding(false).GetString(ms.GetBuffer(), 0, (int)ms.Length);
}
}
There are times when you MAY want to omit un-necessary text to save space when storing XML in large quantities so this allows you to omit the xml declaration and namespace.
Notice the use of the using statements stacking which I would like to use as a segue to another suggestion about your connection opening.
Here is a template that I've found very useful when using straight ADO.NET
using(var conn=new SqlConnection(""))
using(var cmd=new SqlCommand("[sqltext||sproc]",conn)){
//setup cmd with type of sql to execute
//establish a data reader
conn.Open();//at the latest possible moment
using(var dr=cmd.ExecuteReader()){
//do assignments
}
}
This is just a piece of scaffolding. You'll have to fill in the particulars and adjust the reader execution as needed.
Finally, you should mark your class as Serializable if you plan on doing any binary serialization or use of sessions out of proc such as with ASP.NET sessions backed with SQL Server.