Solved

Serializing a Windows.From object

Posted on 2008-06-22
9
268 Views
Last Modified: 2013-11-07
Hello,

I have a windows app and I want to serialize a Windows.Form object. I tried to serialize it using BinaryFormatter but I got SerializationException because the Windows.Form class is not marked as serializable
I've found a solution at www.codeproject.com/KB/dotnet/Surrogate_Serialization.aspx . But it requires a lot of code to be written and it doesn't seem a good way.

So, is there a way to solve this problem or another approach to save the object permanently in HD


thanks in advance.
0
Comment
Question by:bur3001
  • 4
  • 3
9 Comments
 
LVL 18

Expert Comment

by:vbturbo
Comment Utility
Have you tried to mark/tag the Form object as serializeable ?

    [Serializable]
    class Form1
{


}

I havent tried to serialize a Form object but here is how you do it with a class

vbturbo
using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Runtime.Serialization;

using System.Runtime.Serialization.Formatters.Binary;
 

namespace Serialize_People

{

    // A simple program that accepts a name, year, month date,

    // creates a Person object from that information, 

    // and then displays that person's age on the console.

    class Program

    {

        static void Main(string[] args)

        {

            if (args.Length == 0)

            {

                // If they provide no arguments, display the last person

                Person p = Deserialize();

                Console.WriteLine(p.ToString());

            }

            else

            {

                try

                {

                    if (args.Length != 4)

                    {

                        throw new ArgumentException("You must provide four arguments.");

                    }
 

                    DateTime dob = new DateTime(Int32.Parse(args[1]), Int32.Parse(args[2]), Int32.Parse(args[3]));

                    Person p = new Person(args[0], dob);

                    Console.WriteLine(p.ToString());
 

                    Serialize(p);

                }

                catch (Exception ex)

                {

                    DisplayUsageInformation(ex.Message);

                }

            }

        }
 

        private static void DisplayUsageInformation(string message)

        {

            Console.WriteLine("\nERROR: Invalid parameters. " + message);

            Console.WriteLine("\nSerialize_People \"Name\" Year Month Date");

            Console.WriteLine("\nFor example:\nSerialize_People \"Tony\" 1922 11 22");

            Console.WriteLine("\nOr, run the command with no arguments to display that previous person.");

        }
 

        private static void Serialize(Person sp)

        {

            // Create file to save the data to

            FileStream fs = new FileStream("Person.Dat", FileMode.Create);
 

            // Create a BinaryFormatter object to perform the serialization

            BinaryFormatter bf = new BinaryFormatter();
 

            // Use the BinaryFormatter object to serialize the data to the file

            bf.Serialize(fs, sp);
 

            // Close the file

            fs.Close();

        }
 

        private static Person Deserialize()

        {

            Person dsp = new Person();
 

            // Open file to read the data from

            FileStream fs = new FileStream("Person.Dat", FileMode.Open);
 

            // Create a BinaryFormatter object to perform the deserialization

            BinaryFormatter bf = new BinaryFormatter();
 

            // Use the BinaryFormatter object to deserialize the data to from file

            dsp = (Person)bf.Deserialize(fs);
 

            // Close the file

            fs.Close();
 

            return dsp;

        }

    }
 
 

//***********************************************************************************************
 

    [Serializable]

    class Person : IDeserializationCallback

    {

        public string name;

        public DateTime dateOfBirth;

        [NonSerialized]

        public int age;
 

        public Person(string _name, DateTime _dateOfBirth)

        {

            name = _name;

            dateOfBirth = _dateOfBirth;

            CalculateAge();

        }
 

        public Person()

        {

        }
 

        public override string ToString()

        {

            return name + " was born on " + dateOfBirth.ToShortDateString() + " and is " + age.ToString() + " years old.";

        }
 

        private void CalculateAge()

        {

            age = DateTime.Now.Year - dateOfBirth.Year;
 

            // If they haven't had their birthday this year, 

            // subtract a year from their age

            if (dateOfBirth.AddYears(DateTime.Now.Year - dateOfBirth.Year) > DateTime.Now)

            {

                age--;

            }

        }
 

        void IDeserializationCallback.OnDeserialization(Object sender)

        {

            // After deserialization, calculate the age

            CalculateAge();

        }

    }

}

Open in new window

0
 

Author Comment

by:bur3001
Comment Utility
thanks vbturbo,

I marked the class that inherits from Windows.Forms.From as [Serializable] but no success, because I can't mark the base class.
0
 
LVL 18

Expert Comment

by:vbturbo
Comment Utility
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:bur3001
Comment Utility

ok, if i can't serialize a From object, is there another approach to save the object?
0
 
LVL 18

Expert Comment

by:vbturbo
Comment Utility
Depends on the context!

If you want to save time building up the window again and againg with the same static data you could
Cache the object instead.

http://www.codeproject.com/KB/cs/cacheinwinformapps.aspx

vbturbo
0
 

Author Comment

by:bur3001
Comment Utility
First of all, I'm sorry for my late response.
What I understood from the web page you pointed out about cashing is that cash class can be used to save an object in memory NOT in HD and I want the object to be saved in a file not in memory.

Thanks.
0
 
LVL 18

Accepted Solution

by:
vbturbo earned 500 total points
Comment Utility
perhaps this approach could be an idea

http://www.codeproject.com/KB/menus/XMLMenu.aspx

Building up your form with controls saved in a xml file

vbturbo
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Whether you've completed a degree in computer sciences or you're a self-taught programmer, writing your first lines of code in the real world is always a challenge. Here are some of the most common pitfalls for new programmers.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now