Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing generic List<CustomObject> using ApplicationSettingsBase

I am trying to save a List<Foo> using ApplicationSettingsBase, however it only outputs the following even though the list is populated:

<setting name="Foobar" serializeAs="Xml">
    <value />
</setting>

Foo is defined as follows:

[Serializable()]
public class Foo
{
    public String Name;
    public Keys Key1;
    public Keys Key2;

    public String MashupString
    {
        get
        {
            return Key1 + " " + Key2;
        }
    }

    public override string ToString()
    {
        return Name;
    }
}

How can I enable ApplicationSettingsBase to store List<Foo>?

like image 249
Vegard Larsen Avatar asked May 15 '09 11:05

Vegard Larsen


2 Answers

Agreed with Thomas Levesque:

The following class was correctly saved/read back:

public class Foo
{
    public string Name { get; set; }

    public string MashupString { get; set; }

    public override string ToString()
    {
        return Name;
    }
}

Note: I didn't need the SerializableAttribute.

Edit: here is the xml output:

<WindowsFormsApplication1.MySettings>
    <setting name="Foos" serializeAs="Xml">
        <value>
            <ArrayOfFoo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                <Foo>
                    <Name>Hello</Name>
                    <MashupString>World</MashupString>
                </Foo>
                <Foo>
                    <Name>Bonjour</Name>
                    <MashupString>Monde</MashupString>
                </Foo>
            </ArrayOfFoo>
        </value>
    </setting>
</WindowsFormsApplication1.MySettings>

And the settings class I used:

sealed class MySettings : ApplicationSettingsBase
{
    [UserScopedSetting]
    public List<Foo> Foos
    {
        get { return (List<Foo>)this["Foos"]; }
        set { this["Foos"] = value; }
    }
}

And at last the items I inserted:

private MySettings fooSettings = new MySettings();

var list = new List<Foo>()
{
    new Foo() { Name = "Hello", MashupString = "World" },
    new Foo() { Name = "Bonjour", MashupString = "Monde" }
};

fooSettings.Foos = list;
fooSettings.Save();
fooSettings.Reload();
like image 137
odalet Avatar answered Nov 11 '22 03:11

odalet


In XML serialization :

  • Fields are not serialized, only properties
  • Only public properties are serialized
  • Read-only properties are not serialized either

So there is nothing to serialize in your class...

like image 3
Thomas Levesque Avatar answered Nov 11 '22 03:11

Thomas Levesque