Stuck with serialization in C #

I have a class that handles serialization in C # called Serializer. Implementation below:

public class Serializer
{
    public void SerializeRulesManager(string filename, RulesManager rulesManager)
    {
        Stream stream = File.Open(filename, FileMode.Create);        
        try
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(stream, rulesManager);             
        }
        finally
        {
            stream.Close();
        }                
    }

    public RulesManager DeserializeRulesManager(string filename)
    {
        RulesManager rulesManager = null;
        Stream stream = File.Open(filename, FileMode.Open);
        try
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            rulesManager = (RulesManager)binaryFormatter.Deserialize(stream);                
        }
        finally
        {
            stream.Close();                
        }                       
        return rulesManager;
    }
}    

      

Quite simple stuff and it works great with all of my unit tests. The governor is properly ordered and deserialized, so I know the graph is good.

The problem is related to the following code:

public void Save(string filename)
{
    Cursor.Current = Cursors.WaitCursor;
    try
    {
        _serializer.SerializeRulesManager(filename, _rulesManager);
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.Message);
    }            
    finally
    {
        Cursor.Current = Cursors.Default;
    }
}

      

This function is part of the Manager class. The Manager class is created on MainForm. MainForm uses SaveFileDialog to prompt the user for the file name and location they want to save, and then makes the following call:

saveFileDialog.InitialDirectory = Path.GetDirectoryName(Application.ExecutablePath);
if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
{
    _manager.Save(saveFileDialog.FileName);
}

      

So the function call is above. When this happens, I get the following exception in Serialize.SerializeRulesManager on the binaryFormatter.Serialize (stream, rulesManager) line:

Enter "TestHarness.MainForm" in Assembly 'TestHarness, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = null' is not marked serializable.

Why should MainForm be marked Serializable? Just for kicks, I put the Serializable attribute on MainForm and it just moved the exception one level to say Windows.Form was not marked Serializable. What gives?

+2


source to share


1 answer


The RulesManager probably has a link to the MainForm. If so, mark it as not serialized with NonSerializedAttrbibute



+5


source







All Articles