Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing an ISerializable object, that contains other ISerializable-objects

I'm currently working on saving larger object structures which contain all the data needed for a 'project' in the application I'm working on. The data are things such as pictures, flowdocuments as well as the more basic datatypes.

Now, my current approach has been implementing ISerializable on all classes that are contained within the object that I need saving. However, when:

public class Profile : ISerializable
{
    public ObservableCollection<Trade> Trades { get; set; }

    public Profile() {}

    public Profile(SerializationInfo info, StreamingContext context)
            : this()
        {    
            foreach (SerializationEntry entry in info)
            {
                if (entry.Name.StartsWith("trade"))
                {
                    Type t = entry.ObjectType;
                    Trades.Add(entry.Value as Trade);
                }
            }
        }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            int i = 0;
            foreach (Trade t in Trades)
            {
                info.AddValue("trade" + i, t, t.GetType());
                i++;
            }
        }
}

it poses a problem. The Trade-class that is what populates my List also implements ISerializable. So what I'm wonder is: is this a good approach? Does it even work? The code I've written so far doesn't work, and I'm still trying to work out the kinks.

More specifically will the info.AddValue("trade" + i, t, t.GetType()); use the Trade-class' ISerializable-methods? Or perhaps this interface wasn't even meant to deal with these types of classes.

So if anyone would be so kind, and take a little look and maybe point me in the correct direction when it comes to Serialization of things such as these.

Thanks!

like image 670
vesz Avatar asked Nov 06 '22 06:11

vesz


1 Answers

Not sure what the problem here is exactly (if you can post the Trade class and details on what exactly is not working it would be helpful), but in general if the Trade class is serializable, you should be able to just add the [Serializable] attribute to the Profile class and do not need to do custom serialization by implementing ISerializable.

Usually you only need to implement ISerializable when you need to do custom serialization (e.g. when your data members are not serializable).

Edit: Just realized you are using an ObservableCollection so my previous comment of just using [Serializable] attribute is not correct. See here for info on serializing ObservableCollection: http://kentb.blogspot.com/2007/11/serializing-observablecollection.html or you should also be able to use ObservableCollection.CopyTo() to get a Trade[] instance and add that directly to the SerializationInfo.

like image 193
SpeksETC Avatar answered Nov 09 '22 17:11

SpeksETC