CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 6 of 6
  1. #1
    Join Date
    May 2010
    Posts
    7

    [RESOLVED] Serializing an Enum

    Hi all,

    i need to backup a list filled with objects of this class:
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace XML2
    {
        public enum userLevel { Manager, Librarian, Reader };
        [Serializable]
        public class Users
        {
            public string _username { get; set; }
            public string _password { get; set; }
            public userLevel _level { get; set; }
            public Users()
            {
    
            }
            public Users(string name, string password, userLevel level)
            {
                _username = name;
                _password = password;
                _level = level;
            }
        }
    }
    This is my list class:
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml.Serialization;
    using System.IO;
    
    namespace XML2
    {
    
        [Serializable]
        public class userDB
        {
            List<Users> users = new List<Users>();
            public userDB()
            {
                
                users.Add(new Users("Administrator", "12345678", userLevel.Manager));
                users.Add(new Users("Librarian", "12345678", userLevel.Librarian));
                users.Add(new Users("Reader", "12345678", userLevel.Reader));
                save();
            }
            public void save()
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<Users>));
                using (FileStream fs = File.Open(@"users.xml", FileMode.Create))
                {
                    serializer.Serialize(fs, users);
                }
            }
        }
    }
    When i execute it without the Enum it works fine but with it it crashes.
    is there any solution for this?

    Thanx in advance.

    I'm using VS2008

  2. #2
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Serializing an Enum

    Quote Originally Posted by VitalyUr View Post
    When i execute it without the Enum it works fine but with it it crashes.
    In what way? Any error messages, any exceptions thrown? Or the file is not created properly, or what?
    Can you elaborate a bit more?
    Last edited by TheGreatCthulhu; October 14th, 2010 at 08:43 AM.

  3. #3
    Join Date
    May 2010
    Posts
    7

    Re: Serializing an Enum

    When i debug the program it says:
    "InvalidOperationException was unhandled"
    'There was an error reflecting type 'System.Collections.Generic.List' 1[Library.Users]".

    and it points on this line:
    Code:
    XmlSerializer serializer = new XmlSerializer(typeof(List<Users>));

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Serializing an Enum

    Here you go..

    Code:
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Xml.Serialization;
    
    namespace UserXml
    {
        [Serializable]
        public enum UserLevel { Manager, Librarian, Reader };
        
        [Serializable]
        public class User
        {
            [XmlAttribute ( AttributeName = "userName")]
            public string Username { get; set; }
            
            [XmlAttribute( AttributeName = "password" )]
            public string Password { get; set; }
            
            [XmlAttribute( AttributeName = "level" )]
            public UserLevel Level { get; set; }
        }
    
        [Serializable]
        [XmlType( AnonymousType = true )]
        [XmlRoot( ElementName = "userDb", Namespace = "", IsNullable = false )]
        public class UserDb
        {
            [XmlArray( ElementName= "users")]
            [XmlArrayItem( ElementName= "user")]
            public User[] Users
            {
                get { return _userList.ToArray(); }
    
                set
                {
                    if( _userList == null ) { _userList = new List<User>( ); }
    
                    if( value != null )
                    {
                        _userList.AddRange( value );
                    }
                }
            }
    
            public UserDb( )
            {
                _userList.Add( new User { Level = UserLevel.Manager, Username = "Administrator", Password = "12345678" } );
                _userList.Add( new User { Level = UserLevel.Librarian, Username = "Librarian", Password = "12345678" } );
                _userList.Add( new User { Level = UserLevel.Reader, Username = "Reader", Password = "12345678" } );
            }
    
            public void Save( string xmlFile )
            {
                var serializer = new XmlSerializer( typeof( UserDb ) );
                
                using ( var fs = File.Open( xmlFile, FileMode.Create ) )
                {
                    serializer.Serialize( fs, this );
                }
            }
    
            private List<User> _userList = new List<User>( );
        }
    
    
    
        class Program
        {
            static void Main( string [ ] args )
            {
                var userDb = new UserDb( );
                userDb.Save( "users.xml" );
            }
        }
    }
    Produces the output of (which may not be exactly what you need):

    Code:
    <?xml version="1.0"?>
    <userDb xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <users>
        <user userName="Administrator" password="12345678" level="Manager" />
        <user userName="Librarian" password="12345678" level="Librarian" />
        <user userName="Reader" password="12345678" level="Reader" />
      </users>
    </userDb>

  5. #5
    Join Date
    Mar 2004
    Location
    Prague, Czech Republic, EU
    Posts
    1,701

    Re: Serializing an Enum

    There is (or at least was) a glitch in serialization of generics. Try replace List<User> with User[].
    • Make it run.
    • Make it right.
    • Make it fast.

    Don't hesitate to rate my post.

  6. #6
    Join Date
    May 2010
    Posts
    7

    Re: [RESOLVED] Serializing an Enum

    Thank you all for the quick response

    Arjay, it works great, i know now that Enums should be serialized too.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured