473,729 Members | 2,353 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can viewstate serialize this class?

I've created a class that I need to store in ViewState. However when I try
to store it in ViewState, I get the following error:

"The type 'solution.pe2' must be marked as Serializable or have a
TypeConverter other than ReferenceConver ter to be put in viewstate."

I've included the <Serializable() > attribute, but I'm still getting the same
error.

The class is below ... as you can see it contains a Collection, two
Hashtables and an Enum.

How can I make this class and all of its contents serializable so ViewState
can store it??

TIA, Ben

-----------------------------------------

<Serializable() > Public Class pe2
Implements IEnumerable

Private m_colChildren As New Collection
Public Style As New Hashtable
Public Attributes As New Hashtable
Private m_strID As String
Private m_enumElementTy pe As ElementType

Public Enum ElementType
Span
Div
Image
End Enum

Public Function GetEnumerator() As _
System.Collecti ons.IEnumerator Implements _
System.Collecti ons.IEnumerable .GetEnumerator

Return m_colChildren.G etEnumerator

End Function

End Class
Nov 19 '05 #1
7 3541
Yes, the SDK is a bit ambiguous with regards to the "marked as Serialzable"
references that seem to pop up in it from time to time. They are misleading.
In fact, either adding a Serializable attribute or not adding one does
nothing to make a class more or less serialzable. It is important, however,
in some cases, as the .Net platform has mechanisms for doing serialization
by using reflection.

Serialization, in this case, refers to converting data to a stream of text.
It can also refer to converting it to a binary stream, but that's not the
issue here, as we're talking about ViewState, which is text in an HTML
document. Some existing .Net classes are serialzable "straight out of the
box" (as it were). These include primtives and value types, integers,
strings, dates, you know what I'm talking about. Basically, any type that
has a ToString() method implemented which converts it to a string
representation of its Data is serializable. A few more complext types are
also "natively" serializable, including arrays of the previous types, some
Collections, and conveniently, DataSets and DataTables. These are types that
implement the ISerializable interface. For most other types, and custom
types, you will probably have to implement your own custom Serialization.
This is not necessarily difficult, however, with the Serialization classes
in the Framework, depending upon exactly what you want to serialize, and how
you want to serize and deserialize it.

One of the best (and easiest) ways to serialize a class is using the
System.Xml.Seri alization NameSpace. Serializtion to and from XML is not only
one of the easiest things to do in .Net, but it also happens to be possibly
the best way to serialize data to text. XML is powerful stuff. An XML
document can be transformed on the fly to any format you wish, using XSLT,
and can include any type of data as well. It is cross-platform compatible,
and a highly popular world-wide standard.

The main class that you employ in the System.Xml.Seri alization namespace is
the XmlSerializer. This class is used for both serialization and
deserialization , and has a really nice API. In most cases, you can serialize
an object by simply creating an instance of the XmlSerializer class, and
calling the Serialize method. All public fields, and public properties that
implement a setter and a getter are serialized automatically, using
Reflection. Methods are not. Note that the class must implement a
parameterless constructor to be able to do this. However, you can certainly
overload the constructor to your heart's content.

The methods are restored when you deserialize the class. You can read more
about XML serialization at:

http://msdn.microsoft.com/library/de...ialization.asp

You can read more about serialization without XML at:

http://msdn.microsoft.com/library/de...bjserializ.asp

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.

"Ben Amada" <be*@REpoMOweVE rpick.com> wrote in message
news:ee******** *****@TK2MSFTNG P15.phx.gbl...
I've created a class that I need to store in ViewState. However when I
try to store it in ViewState, I get the following error:

"The type 'solution.pe2' must be marked as Serializable or have a
TypeConverter other than ReferenceConver ter to be put in viewstate."

I've included the <Serializable() > attribute, but I'm still getting the
same error.

The class is below ... as you can see it contains a Collection, two
Hashtables and an Enum.

How can I make this class and all of its contents serializable so
ViewState can store it??

TIA, Ben

-----------------------------------------

<Serializable() > Public Class pe2
Implements IEnumerable

Private m_colChildren As New Collection
Public Style As New Hashtable
Public Attributes As New Hashtable
Private m_strID As String
Private m_enumElementTy pe As ElementType

Public Enum ElementType
Span
Div
Image
End Enum

Public Function GetEnumerator() As _
System.Collecti ons.IEnumerator Implements _
System.Collecti ons.IEnumerable .GetEnumerator

Return m_colChildren.G etEnumerator

End Function

End Class

Nov 19 '05 #2
Kevin Spencer wrote:
Yes, the SDK is a bit ambiguous with regards to the "marked as
Serialzable" references that seem to pop up in it from time to time. They
are misleading. In fact, either adding a Serializable attribute or not
adding one does nothing to make a class more or less serialzable. It is
important, however, in some cases, as the .Net platform has mechanisms
for doing serialization by using reflection.

Serialization, in this case, refers to converting data to a stream of
text. It can also refer to converting it to a binary stream, but that's
not the issue here, as we're talking about ViewState, which is text in an
HTML document. Some existing .Net classes are serialzable "straight out
of the box" (as it were). These include primtives and value types,
integers, strings, dates, you know what I'm talking about. Basically, any
type that has a ToString() method implemented which converts it to a
string representation of its Data is serializable. A few more complext
types are also "natively" serializable, including arrays of the previous
types, some Collections, and conveniently, DataSets and DataTables. These
are types that implement the ISerializable interface. For most other
types, and custom types, you will probably have to implement your own
custom Serialization. This is not necessarily difficult, however, with
the Serialization classes in the Framework, depending upon exactly what
you want to serialize, and how you want to serize and deserialize it.

One of the best (and easiest) ways to serialize a class is using the
System.Xml.Seri alization NameSpace. Serializtion to and from XML is not
only one of the easiest things to do in .Net, but it also happens to be
possibly the best way to serialize data to text. XML is powerful stuff.
An XML document can be transformed on the fly to any format you wish,
using XSLT, and can include any type of data as well. It is
cross-platform compatible, and a highly popular world-wide standard.

The main class that you employ in the System.Xml.Seri alization namespace
is the XmlSerializer. This class is used for both serialization and
deserialization , and has a really nice API. In most cases, you can
serialize an object by simply creating an instance of the XmlSerializer
class, and calling the Serialize method. All public fields, and public
properties that implement a setter and a getter are serialized
automatically, using Reflection. Methods are not. Note that the class
must implement a parameterless constructor to be able to do this.
However, you can certainly overload the constructor to your heart's
content.
The methods are restored when you deserialize the class. You can read more
about XML serialization at:

http://msdn.microsoft.com/library/de...ialization.asp

You can read more about serialization without XML at:

http://msdn.microsoft.com/library/de...bjserializ.asp


Hi Kevin,

Your reply has been very helpful. I started looking at the XmlSerializer
class in addition to XML as a way of persisting data. I discovered a couple
of problems however:

(1) I must have a parameterless constructor which you mentioned in your
reply - however, my class doesn't have one. This is not a big problem
however.

(2) My class contains two hashtables which it appears from some archived
posts that I found is not serializable via the XmlSerializer class. There
are some other classes that do support serialization of hashtables however.
I also got the feeling that it's possible that a future version of the .NET
framework (possibly v2.0) might support hashtable serialization via the
XmlSerializer class.

One rather large concern that I have is because I will be instantiating a
bunch of these classes (my classes), even if I do succeed in serializing the
classes, ViewState might become very bloated.

Fortunately, I'm just starting this project and nothing is set in stone --
so I'm still keeping an open mind on how to make this project work in an
efficient way.

Eventually, I'm going to have to store all of my class data in a SQL
database. I haven't even created or designed the database yet, but at this
point, I'm considering only using the class I created to a limited degree
and possibly reading and writing to the database on each postback to
retrieve and persist data instead of storing it in ViewState to keep the
amount of data sent to the client to a minimum.

Again, thanks for your suggestions -- I learned something new again!

Ben
Nov 19 '05 #3
Let me recommend that if you are going to use XML serialization, create one
instance of XmlSerializer and cache it for reuse. Each time that the
constructor for XmlSerializer is called, a new dynamic assembly is
generated. These assemblies are small (~12k or so), but they will be
scattered throughout system memory, thereby causing fragmentation. If you
get enough of them, you'll end up seeing OutOfMemoryExce ptions due to an
inability to allocate large contiguous blocks of memory to grow the managed
heap.

If you cache a single instance of XmlSerializer, you avoid this issue. By
caching it, you can take advantage of cache trimming in cases where memory
pressure increases.

--
Jim Cheshire
JIMCO Software
http://www.jimcosoftware.com


Nov 19 '05 #4
ViewState does not support Xml object Serialization, it uses the
LosFormatter for serialization. You should use a BinaryFormatter with
a TypeConverter. You might be able to use the GenericTypeConv erter by
adding this attribute to your class:
<TypeConverter( typeof(GenericT ypeConverter))>
I've seen implementations with this, but I haven't tried it myself. It
will be much faster if you implement your own.

Take a look at this blog:

http://weblogs.asp.net/vga/archive/2...eMoreTime.aspx

Given the number of collections you have in your class, I don't think
that ViewState serialization is wise. You will create a very large
viewstate field on the client and will create performance problems that
you have no control over. Consider serializing to Session (which will
accept XmlSerializatio n), Cache, or storing your stringId parameter and
hydrating the class from that value.

Nov 19 '05 #5
> ViewState does not support Xml object Serialization, it uses the

I should have thought of that. Of course, one could always add an
HtmlEncode() to the mix, but I'm sure the method you've outlined is better!

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.
"john_teagu e" <jc******@gmail .com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
ViewState does not support Xml object Serialization, it uses the
LosFormatter for serialization. You should use a BinaryFormatter with
a TypeConverter. You might be able to use the GenericTypeConv erter by
adding this attribute to your class:
<TypeConverter( typeof(GenericT ypeConverter))>
I've seen implementations with this, but I haven't tried it myself. It
will be much faster if you implement your own.

Take a look at this blog:

http://weblogs.asp.net/vga/archive/2...eMoreTime.aspx

Given the number of collections you have in your class, I don't think
that ViewState serialization is wise. You will create a very large
viewstate field on the client and will create performance problems that
you have no control over. Consider serializing to Session (which will
accept XmlSerializatio n), Cache, or storing your stringId parameter and
hydrating the class from that value.

Nov 19 '05 #6
John
Your post is very informative. Being a relatively new comer to the .net
platform , I was trying to save my custom business object collection in
viewstate abd stumbled upon the error "....Collec tion must be marked as
Serializable or have a TypeConverter other than ReferenceConver ter to be
put in viewstate"...
When searching on the web for this error, I saw numerous posts suggesting to
write a Typeconvertor and use it with the typeconverter attribute for the
collection as well as the custom object contained in the collection.
But I do see many posts discouraging from using view state as we might take a
performance hit. So, would it be better altogether to use the session to
store the custom collection? If so use the session, then I guess I will not
get this error when stoing this collection.
Also, can you elaborate a little more on the third option - "storing your
stringId parameter and hydrating the class from that value" ? I quite dont
understand it.

Thanks
john_teague wrote:
ViewState does not support Xml object Serialization, it uses the
LosFormatter for serialization. You should use a BinaryFormatter with
a TypeConverter. You might be able to use the GenericTypeConv erter by
adding this attribute to your class:
<TypeConverter (typeof(Generic TypeConverter)) >
I've seen implementations with this, but I haven't tried it myself. It
will be much faster if you implement your own.

Take a look at this blog:

http://weblogs.asp.net/vga/archive/2...eMoreTime.aspx

Given the number of collections you have in your class, I don't think
that ViewState serialization is wise. You will create a very large
viewstate field on the client and will create performance problems that
you have no control over. Consider serializing to Session (which will
accept XmlSerializatio n), Cache, or storing your stringId parameter and
hydrating the class from that value.

--
Message posted via http://www.dotnetmonster.com
Nov 19 '05 #7
I was assuming (perhaps incorrectly) that the data for your object
represented data in a persistent data store (database, file, etc) and
that m_strID was a lookup key. In that case, you could save just the
string id and then retrieve your data using it. Obviously this is much
slower than saving the object in session and if that is an option I
would do that first.

Nov 19 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2820
by: Craig Buchanan | last post by:
I am trying to serialize a class called Order to the ViewState. Order has one property called LineItems, which is an ArrayList. The ArrayList holds instances of a class named LineItem. Bother Order and LineItem are marked with the <Serializable> attribute. When I attempt to serialize the class using this code: Dim xs As XmlSerializer = New XmlSerializer(GetType(Order)) Dim sw As New StringWriter()
5
1648
by: Craig Buchanan | last post by:
I'm using a viewstate key/value to store a serialized instance of a class. If I redirect to another aspx page, the viewstate is lost. Is this the intended behavior of the viewstate? Is there a work around? Cookies, I suppose. Thanks, Craig Buchanan
0
1463
by: S.Sigal | last post by:
Hello: I've been trying to 'organize' the layout of my larger controls by moving variables into instances of subclasses...but it just dawned on me that I might be opening a real can of worms due to StateBag serialization... If ViewState serialization is optimized for Int32, Bool, String, Color, and arrays thereof... what happens when I want to serialize the instance of a class that contains an Int32, Bool String, or Color?
3
2098
by: MattC | last post by:
With respect to Peter Bromberg's article ( http://www.eggheadcafe.com/articles/20040613.asp ) I wish to store my viewstate info in the Session object rather than the cache (as it is per user info). I have tried the following but am unable to serialize the viewstate?? protected override void SavePageStateToPersistenceMedium(object viewState) { string str = "VIEWSTATE_" + Request.UserHostAddress + "_" + DateTime.Now.Ticks.ToString();
2
7982
by: ce | last post by:
Being a newbie regarding serialization and memorystreams, I was trying to see if i could improve page performance (avoiding going to the db on a postback) by saving my serialized business object in viewstate and getting it back from the client on a postback. But the last line of the sample code below throws a "Stream was not readable" error when i'm trying to get the serialized object back out of the viewstate and memorystream. Any...
1
1403
by: John | last post by:
I'm having problems controlling viewstate size in ASP.NET 2.0. I have a repeater, which contains a gridview, which contains another gridview. All this is databound to produce a 100page report (for printing). No postback needed, no viewstate needed. I've set EnableViewState="false" on everything I can see, including all the controls, the form and the page itself. But the viewstate is still 10 lines in notepad (without wrapping!). I...
1
3042
by: Irene | last post by:
Hello all! I'm creating a web site in ASP.NET (VB.NET). One of the requirements was to allow users to create orders going through several steps. A must have is to have an option to save the work in any phase (any step) and to be able to continue later. My idea was to create several pages as steps (no, wizard control is not suitable for several reasons) and to allow users to save any step to the database, that is, a ViewState of the...
3
2262
by: Mark | last post by:
I'm consuming a webservice that makes a simple object available. The object class is marked in the web service as . I have a web application that consumes and uses this web service's class. When I receive the object from the web service, I'm interested in storing that object in ViewState in the web application, but I receive the error below. I'm not shocked that the web application can't serialize the object as the attribute isn't...
5
3153
by: =?Utf-8?B?V2ViQnVpbGRlcjQ1MQ==?= | last post by:
I can very simple save a serilized class to a server, but i don't know how to serilize an object (here a business object) to a variable so that it can be saved to viewstate or passed to another page? here is my to disk version: private void ser() { var fs = new FileStream(@"e:\websites\SerializedClassData", FileMode.Create);
0
8917
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8148
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6022
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4525
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2163
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.