Pregunta

I have a list of objects defined. I am wanting to populate them from a stored procedure and then serialize them to pass to an XML file. I am stuck on how to accomplish this. Here is what I have so far. I do not want to use LINQ.

In a Library class I have this:

public class Person
{
    public static string First_Name { get; set; }
    public static string Last_Name { get; set; }    
    public static string Address1 { get; set; }
    public static string Address2 { get; set; }
}

In a Database class I have this:

conn = new SqlConnection(ConfigurationManager.AppSettings["DatabaseConnection"]);

            using (var cmd = new SqlCommand())
            {
                conn.Open();
                cmd.Connection = conn;
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.CommandText = "sp_GetInfo";

                cmd.Parameters.Add(CreateParameter("@Id", SqlDbType.Int, Id));

                SqlDataReader dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                    string First_Name = dr.GetString(0);
                    string Last_Name = dr.GetString(1);
                    string Address1 = dr.GetString(2);
                    string Address2 = dr.GetString(3);                      

                    dr.Close();
                    dr.Dispose();
                }

To Serialize I plan to use this:

public static string Serialize(object obj)
    {
        XmlSerializer xs = new XmlSerializer(obj.GetType());
        MemoryStream buffer = new MemoryStream();
        xs.Serialize(buffer, obj);
        return ASCIIEncoding.ASCII.GetString(buffer.ToArray());
    }

Am I on the correct path or do I need to look at this a different way?

¿Fue útil?

Solución

You're on the right path. Note that when you're reading the data from the stored proc (avoid "sp_" prefix by the way; this is convention is for MS stored procs), you'll need to creating the Person object you listed.

In terms of serialization, a simpler version is to use the StringWriter class:

        public static string Serialize(object obj)
        {
            XmlSerializer xs = new XmlSerializer(obj.GetType());
            using (StringWriter textWriter = new StringWriter())
            {
                xs.Serialize(textWriter, obj);
                return textWriter.ToString();
            }
        }

Note the use of the using statement, which enforces the call to Dispose() on IDisposable objects.

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top