Click here to Skip to main content
12,079,202 members (26,140 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C# 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 3: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 22-Mar-12 13:08pm
   
Good point :)
SAKryukov 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.
SAKryukov 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.
SAKryukov 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
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web04 | 2.8.160212.1 | Last Updated 22 Mar 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100