Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0
Hello,

I am having an application in C# which is having a singleton class.
Class definition is given below
[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
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 22-Mar-12 2:38am

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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
  Permalink  
Comments
Espen Harlinn at 22-Mar-12 13:08pm
   
Good point :)
SAKryukov at 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 at 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.
SAKryukov at 22-Mar-12 14:26pm
   
Yes, the code sample clearly shows things. Thank you. --SA
wizardzz at 22-Mar-12 13:55pm
   
Must be homework season.
SAKryukov at 22-Mar-12 15:26pm
   
:-) Students flow low -- expect heavy rain soon... :-) --SA

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

  Print Answers RSS
Your Filters
Interested
Ignored
     
0 Sergey Alexandrovich Kryukov 437
1 sanket saxena 355
2 thatraja 240
3 Abhinav S 216
4 CPallini 215
0 Sergey Alexandrovich Kryukov 8,784
1 OriginalGriff 5,025
2 Peter Leow 3,839
3 Maciej Los 3,535
4 Er. Puneet Goel 3,107


Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 22 Mar 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Use
Layout: fixed | fluid