473,435 Members | 1,653 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,435 software developers and data experts.

Serializing Button class

siddnair54
I'm trying to serialize a button created at runtime.
But it throws an exception regarding the serializable attribute.
Is there any other way, how I can save the state of the Button?
Apr 13 '10 #1

✓ answered by Fr33dan

Gary I'm afraid your solution won't work either because the button will still have to be serialized. By default in binary serialization (I've never worked with XML serialization) by all members public or private must will be serialized to store the object and then deserialized to recreate it.

In order to serialize a object like this properly you must write a subclass that implements the ISerializable interface. The ISerializable interface that allows you to define which members to serialize in a object and how to recreate the object from the serialized data (via a special constructor):
Expand|Select|Wrap|Line Numbers
  1. [Serializable]
  2.     class MyButton:Button, ISerializable
  3.     {
  4.         public MyButton()
  5.             : base()
  6.         {
  7.         }
  8.  
  9.         protected MyButton(SerializationInfo info, StreamingContext context):base()
  10.         {
  11.             this.Text = info.GetString("Text");
  12.             this.Location = (Point)info.GetValue("Location",typeof(Point));
  13.         }
  14.  
  15.         [SecurityPermissionAttribute(SecurityAction.Demand, 
  16.         SerializationFormatter =true)]
  17.         public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
  18.         {
  19.             info.AddValue("Text", this.Text);
  20.             info.AddValue("Location", this.Location);
  21.         }
  22.  
  23.     }
  24.  
I've only serialized the text and location here but you can modify this to serialize whatever data you need to store (as long as what you store is serializable). Then you can use the now serializable MyButton class in place of the normal button.

More information on binary serialization is available here (The concepts I've expressed here are available under Custom Serialization): http://msdn.microsoft.com/en-us/libr...=VS.80%29.aspx

11 6067
GaryTexmo
1,501 Expert 1GB
Hmm, I can you post more details? I'm only really familiar with XML serialization, so if you're not doing that I'm not sure how much I can help, but I'll try.

Need more information though... a code snippet and the exception text would do nicely.
Apr 13 '10 #2
Actually i'm using Binary serialization.
Forget about the type of serialization. The real problem i'm facing is to make the Button class serializable.

The scenario is that, i'm creating a button at runtime. Inorder to save its state I have to serialize it. The code goes like this....

Expand|Select|Wrap|Line Numbers
  1.             try
  2.             {
  3.                 Button b1 = new Button();
  4.                 this.Controls.Add(b1);
  5.  
  6.                 FileStream fs = new FileStream("C:\\Serialize.binary",        FileMode.CreateNew);
  7.                 BinaryFormatter bf = new BinaryFormatter();
  8.                 bf.Serialize(fs, b1);
  9.             }
  10.             catch (Exception ex)
  11.             {
  12.                 MessageBox.Show(ex.Message);
  13.             }
  14.  
When i run this code, it throws this exception...

Type 'System.Windows.Forms.Button' in Assembly 'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable


I tried creating usercontrol but even that didn't work. it gives the same exception.
Apr 14 '10 #3
GaryTexmo
1,501 Expert 1GB
Hmm, the error message "not marked as serializable" seems to be the key. When you make something serializable for XML, you need the [Serializable] tag (or something similar) so perhaps that's it.

I just did some tests and it seems you need the [Serializable] tag to serialize things in this fashion. Button must not have that. I did try adding the tag to a new class that inherits from button, but that doesn't work either.

I'm not sure how you can do this... maybe you could make a wrapper class that exposed a string property that was a string representation of a button (like, name="blah";size="blah") and when set, it instantiated the correct button. There's gotta be a better way to do it though! I'll see if I can figure something out, or maybe someone else will have some insight. Google wasn't terribly helpful, but I might not have searched correctly.
Apr 14 '10 #4
GaryTexmo
1,501 Expert 1GB
I found this...

http://forum.codecall.net/c-programm...y-created.html

... it looks like they went with the wrapper solution.

Sorry I couldn't be of better help. Good luck!
Apr 14 '10 #5
@GaryTexmo
Its ok..

Even i tried wid the Wrapper class... but wid no results.
Created a custom class too...but it gives the same exception..
Please do reply if you get any insights to this.
Thanks.
Apr 15 '10 #6
GaryTexmo
1,501 Expert 1GB
By wrapper class, I mean mean a brand new class that doesn't expose the button as a public member, so it won't be serialized. Something like this...

Expand|Select|Wrap|Line Numbers
  1. [Serializable]
  2. public class MyButton : UserControl
  3. {
  4.   private Button m_button = new Button();
  5.  
  6.   public class MyButton() { };
  7.  
  8.   // Expose public properties on m_button that you wish exposed
  9.  
  10.   public string ButtonProperties
  11.   {
  12.     get
  13.     {
  14.       return String.Format("Name={0};Text={1}, ...", m_button.Name, m_button.Text, ...);
  15.     }
  16.  
  17.     set
  18.     {
  19.       // parse "value"
  20.       // set properties on m_button depending on the data obtained from "value"
  21.     }
  22.   }
  23. }
That's kind of what I meant. The actual button object is private and won't be serialized, but the public string will be, which will define a button via a text string. This should let you get button properties back, though honestly I'm not sure how this would work for events.

I feel like there *has* to be a better way to do this, but I honestly don't know. Hopefully that helps you at least in some way.
Apr 15 '10 #7
Fr33dan
57
Gary I'm afraid your solution won't work either because the button will still have to be serialized. By default in binary serialization (I've never worked with XML serialization) by all members public or private must will be serialized to store the object and then deserialized to recreate it.

In order to serialize a object like this properly you must write a subclass that implements the ISerializable interface. The ISerializable interface that allows you to define which members to serialize in a object and how to recreate the object from the serialized data (via a special constructor):
Expand|Select|Wrap|Line Numbers
  1. [Serializable]
  2.     class MyButton:Button, ISerializable
  3.     {
  4.         public MyButton()
  5.             : base()
  6.         {
  7.         }
  8.  
  9.         protected MyButton(SerializationInfo info, StreamingContext context):base()
  10.         {
  11.             this.Text = info.GetString("Text");
  12.             this.Location = (Point)info.GetValue("Location",typeof(Point));
  13.         }
  14.  
  15.         [SecurityPermissionAttribute(SecurityAction.Demand, 
  16.         SerializationFormatter =true)]
  17.         public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
  18.         {
  19.             info.AddValue("Text", this.Text);
  20.             info.AddValue("Location", this.Location);
  21.         }
  22.  
  23.     }
  24.  
I've only serialized the text and location here but you can modify this to serialize whatever data you need to store (as long as what you store is serializable). Then you can use the now serializable MyButton class in place of the normal button.

More information on binary serialization is available here (The concepts I've expressed here are available under Custom Serialization): http://msdn.microsoft.com/en-us/libr...=VS.80%29.aspx
Apr 15 '10 #8
GaryTexmo
1,501 Expert 1GB
Excellent, thanks for posting that!

I didn't realize the binary serializer also serialized private members (the XML one does not), so good to know. I knew there had to be a better way to do it ;)
Apr 15 '10 #9
@Fr33dan
Ya..true....
But will this help to serialize other vital properties like the height, width, location etc. of the button?
Because when the user reruns the application, the button has to be recreated on the form. So these properties must be available.
Apr 16 '10 #10
Fr33dan
57
Yes this can be used to store whatever information you deem vital.

In my example I called info.AddValue to add the text of the button and the location and text but you could include width, height or color or absolutely anything you think should be preserved in serialization.

All you have to do is add it to the SerializationInfo object in the GetObjectData method and then pull it back out of the SerializationInfo object in the second constructor.

If you look in my example I call "info.AddData("Text",this.Text)" with tells the system that you want to store this.Text linked to the string "Text". Then in my constructor I used info.GetString("Text") to pull the information back out and set it on the recreated instance.

The only limitation of this is if you try to add an object that is not serializable to the SerializationInfo. But if you really needed it to work you could go in and do the same thing your doing for the Button to that object.
Apr 16 '10 #11
@Fr33dan
Hey thanks..
I'll try this out and get back to you.
Thanks for your response.
Apr 17 '10 #12

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Aleksei Guzev | last post by:
Imagine one writing a class library CL1 for data storage. He defines classes ‘DataItem’ and ‘DataRecord’ so that the latter contains a collection of the former. And he derives class ‘IntItem’ from...
0
by: Ante Smolcic | last post by:
Hi all, I have an ArrayList that contains items of type A. I declared the XmlArrayItem atribute for that type. Now I have an derived type B (from A) also contained in the ArrayList but I get...
4
by: Wayne Wengert | last post by:
I am still stuck trying to create a Class to use for exporting and importing array data to/from XML. The format of the XML that I want to import/export is shown below as is the Class and the code I...
1
by: Ivo Bronsveld | last post by:
All, I have quite a challenging task ahead of me. I need to write an object model (for code access) based on a schema, which cannot be made into a dataset because of it's complexity. So I...
2
by: Tobias Zimmergren | last post by:
Hi, just wondering what serializing really is, and howto use it? Thanks. Tobias __________________________________________________________________ Tobias ICQ#: 55986339 Current ICQ status: +...
1
by: Derrick | last post by:
Hello all; I seem to be having some trouble serializing a class to XML. This code is a cut & paste from a project which used it perfectly, but all of a sudden I'm getting an error that the "dll...
4
by: Jason Shohet | last post by:
We are thinking of serializing an object & passing it toseveral functions on web service. This will happen about 35 times as the page loads. The class has about 20 attributes. We're not sure...
8
by: Joe | last post by:
Hello All: Say I have a solution with two projects (Project1 and Project2) and each project contains a class (Project1 contains Class1 and Project2 contains Class2). The projects don't...
3
by: Tom | last post by:
I am having trouble serializing a color property. Basically, it is not serializing the value. For instance, in the following: <Serializable()> _ Public Class TestColor Private _MyColor As...
7
by: fjlaga | last post by:
I have written an Office Add-in for Excel using VB.NET and the .NET 1.1 Framework (I have Visual Studio 2003 .NET ). All works great. I want to add a User Settings/Prefereneces dialog and allow...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.