[dba-VB] C# serialization

Michael Maddison michael at ddisolutions.com.au
Mon Oct 12 22:29:00 CDT 2009


Hi John,

I did this a few years ago and the project got canned so beware :-). It
only works with a single class at a time IIRC.

Maybe LINQ to XML might be the way to go for building nested related
objects? Just struggling through some of this myself, but I'm working
from existing XML data.
Look at creating XML trees.
http://msdn.microsoft.com/en-us/library/bb387068.aspx

good luck

Michael M

using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml.Serialization;

    /// <summary>
    /// Serializes and deserializes Layout objects
    /// </summary>
    public class Serializer<T>
    {
        public Serializer( )
        {
        }

        /// <summary>
        /// Serializes the Layout object
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="source"></param>
        public void SerializeNow( string filePath, T source,
SerializationFormat format )
        {
            if ( source == null ) throw new ArgumentNullException(
"source", "Invalid object to serialize" );
            if ( string.IsNullOrEmpty( filePath ) ) throw new
ArgumentException( "Invalid path" );

                    switch ( format )
                    {
                        case SerializationFormat.Xml:
                            // Insert code to set properties and fields
of the object.
                            XmlSerializer mySerializer = new
XmlSerializer( typeof( T ) );
                            // To write to a file, create a StreamWriter
object.
                            using ( 
                                StreamWriter myWriter = new
StreamWriter( "PedalMap.xml" ) )
                            {
                                mySerializer.Serialize( myWriter, source
);
                                myWriter.Close( );

                            }
                            break;

                        case SerializationFormat.Binary:
                            using (
                                FileStream fs = new FileStream(
filePath, FileMode.OpenOrCreate, FileAccess.Write ) )
                            {
                                BinaryFormatter b = new BinaryFormatter(
);
                                b.Serialize( fs, source );
                            }
                            break;
                    }                
        }

        /// <summary>
        /// Deserializes the Layout object
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public T DeSerializeNow( string filePath, SerializationFormat
format )
        {
            if ( string.IsNullOrEmpty( filePath ) ) throw new
ArgumentException( "Invalid path" );

            switch ( format)
            {
                case SerializationFormat.Binary:
                    using (
                        FileStream fs = new FileStream( filePath,
FileMode.Open, FileAccess.Read ) )
                    {
                        BinaryFormatter b = new BinaryFormatter( );
                        try
                        {
                            return ( T ) b.Deserialize( fs );
                        }
                        catch
                        {
                            return default( T );
                        }
                    }

                case SerializationFormat.Xml:

                    XmlSerializer mySerializer = new  XmlSerializer(
typeof( T ) );
                    using
                        (
                        StreamReader myReader = new StreamReader(
filePath )
                        )
                        return ( T ) mySerializer.Deserialize( myReader
);

                    
            }
            return default( T );
        }
    }

The object to serialize, add the Serializable( ) attribute to the class.

    [Serializable( )]    //Set this attribute to all the classes that
want to serialize    
    public class PedalMap
    {

        public PedalMap( )
        {

        }
	//Add your properties here
	}

You call it like so...

	Serializer<PedalMap> s = new Serializer<PedalMap>( );
      s.SerializeNow( Application.ExecutablePath, _pmap,
SerializationFormat.Xml );




-----Original Message-----
From: dba-vb-bounces at databaseadvisors.com
[mailto:dba-vb-bounces at databaseadvisors.com] On Behalf Of jwcolby
Sent: Tuesday, 13 October 2009 1:35 PM
To: VBA
Subject: [dba-VB] C# serialization

I have a homework project in which I collect grades in clsgrade
instances, in collection in 
clsGrades instances.  I need to serialize / deserialize the clsGrade
instances in the collection in 
each clsGrades instance.

I actually did this a year or so ago in VB.Net but am not finding
anything that results in a similar 
structure in c#.  I managed to serialize a bunch but the results looked
like:

<?xml version="1.0" encoding="utf-8"?>

<clsGrade xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <Grade>100</Grade>
   <GradeType>1</GradeType>
</clsGrade><?xml version="1.0" encoding="utf-8"?>

<clsGrade xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <Grade>99</Grade>
   <GradeType>1</GradeType>
</clsGrade><?xml version="1.0" encoding="utf-8"?>


As you can see I am getting a ton of header crap for each grade.  I
don't even have the code any more.

Does anyone have simple code for serializing a strongly typed list full
of class instances without 
serializing each instance manually?  Then wrapping that in a higher
level as well (the supervisor 
clsGrades)?

TIA

-- 
John W. Colby
www.ColbyConsulting.com
_______________________________________________
dba-VB mailing list
dba-VB at databaseadvisors.com
http://databaseadvisors.com/mailman/listinfo/dba-vb
http://www.databaseadvisors.com





More information about the dba-VB mailing list