Click here to Skip to main content
15,885,869 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

I am having an application in C# which is having a singleton class.
Class definition is given below
C#
[Serializable]
    public sealed class GenSetup : ISerializable
    {
        private static readonly  GenSetup GenSetupObj = new GenSetup ();

        public static GenSetup GetInstance
        {
            get
            {
                return GenSetupObj;
            }
        }
   
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.SetType(typeof(SingletonSerializationHelper));
        }

     public void Serialize()
        {
            FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
            try
            {
                // Construct a BinaryFormatter and use it  //to serialize the data to the stream.
                BinaryFormatter formatter = new BinaryFormatter();                
                formatter.Serialize(fs, GenSetup.GetInstance);                
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Failed to serialize. Reason: " + e.Message);
                throw;
            }
            finally
            {
                fs.Close();
            }
        }

        public void DeSerialize()
        {
            FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
            try
            {
                // Construct a BinaryFormatter and use it  //to serialize the data to the stream.
                BinaryFormatter formatter = new BinaryFormatter();                                
                GenSetup pGenSetup = (GenSetup)formatter.Deserialize(fs);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("Failed to serialize. Reason: " + e.Message);
                throw;
            }
            finally
            {
                fs.Close();
            }
        }
     }

[Serializable]
    internal sealed class SingletonSerializationHelper : IObjectReference
    {
        // This object has no fields (although it could).

        // GetRealObject is called after this object is deserialized.
        public Object GetRealObject(StreamingContext context)
        {
            // When deserialiing this object, return a reference to 
            // the Singleton object instead.
            return GenSetup.GetInstance;
        }
    }


Now the problem is when Serialize() function is getting called, GenSetup.Getinstance is having all the updated data.
But while calling deSerialize() function it doesn't return saved values.

If i change the above GetObjectData function and add new constructor as
C#
public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Sequencer", m_IsSequencer, typeof(bool));
            info.AddValue("Strength", m_bIsStrength, typeof(bool));
        }

        public GenSetup(SerializationInfo info, StreamingContext context)
        {
            m_IsSequencer = info.GetBoolean("Sequencer");
            m_bIsStrength = info.GetBoolean("Strength");
        }

then its working fine.But i don't want to add all variables as i am having lots of data.

I am not getting where the code is going wrong.

Please help me to rectify my code

Thanks in Advanced.
Posted

1 solution

The right approach here is using Data Contract. This way of serialization is the most non-intrusive. You only mark types and members you want to be a part of contract with appropriate attributes, so, first, you do not modify your data model, do not implement any interfaces, second, you mark only the members you need to persist in a contract. Also, it has nothing to do with access specifiers: members of the contracts can be public or non-public. Also, you can make the data format world unique using your company or personal URL for namespace; and you can make provisions for versioning and future backup compatibility of persistent data.

Please see:
http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

See also my past answers where I advocate this approach:
How can I utilize XML File streamwriter and reader in my form application?[^],
Creating property files...[^].

—SA
 
Share this answer
 
Comments
Espen Harlinn 22-Mar-12 13:08pm    
Good point :)
Sergey Alexandrovich Kryukov 22-Mar-12 13:11pm    
Thank you, Espen.
Funny, this is a second question on serialization of the singleton object in a row, from different people. The first one implemented all the "singleton" as one static class (!) and tried to serialize it (oops!) :-)
Still did not resolve the problem even after the fix...
--SA
Espen Harlinn 22-Mar-12 13:25pm    
The sample code on MSDN for BinaryFormatter provides a detailed example on how it should be done.
http://msdn.microsoft.com/en-us/library/b85344hz.aspx

Access to the object can be done using the singleton pattern, but what OP is doing with the SingletonSerializationHelper looks pretty odd - if he'd just put the poor thing out of it's missery he should be up and running in no time - as it is he is overcomplicating his solution.
Sergey Alexandrovich Kryukov 22-Mar-12 14:26pm    
Yes, the code sample clearly shows things.
Thank you.
--SA
wizardzz 22-Mar-12 13:55pm    
Must be homework season.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900