Serialize .NET objects to store and retrieve them from a file or
viewstate in ASP.NET
Everything is .NET is an object. But sometimes you need to store an object to a
file, ASP.NET's viewstate etc. then get it back
from the file or viewstate and continue to use it as the object it originally
was.
The process of doing this in .NET is called serialization.
Serializing an object is like deflating it. Once it is serialized it can
be written out to a stream such as a file. Then, it can be read back in
and de-serialized or inflated and used just like it was stored in memory
the entire time.
Why else serialize an object? Suppose we have a PayeeData object that has
no methods but holds all the data for a particular payee. If we want to save
all the payee's data across multiple requests for the same ASP.NET web page, we
can add the PayeeData object to the page's viewstate. But to do this it must
first be serialized.
.NET lets you serialize an object simply be decorating its class with a
serializable attribute. After that, .NET handles everything for you.
Making a class serializable in VB.NET:
<Serializable()> _
Public Class PayeeData
...
End Class
Making a class serializable in C#:
[Serializable]_
public class PayeeData
{
...
}
Another example. Say you log errors in your application then display them on a
web page. You can create a LogEntry object to hold the error information.
Serializable LogEntry class using VB.NET:
<Serializable()> _
Public Class LogEntry
Private _EntryDate As String = ""
Private _EntryTime As String = ""
...
Public Property EntryDate() As String
Get
Return _EntryDate
End Get
Set(ByVal Value As String)
_EntryDate = Value
End Set
End Property
...
End Class
In your application you can collect error info by populating the LogEntry object
with information on each error and store these entries in an array.
Dim aryEntryList As ArrayList = New ArrayList
Entry = New LogEntry
Entry.EntryDate = ...
Entry.EntryTime = ...
...
aryEntryList.Add(Entry)
Now you have a list of errors and you want to display them. You can use a
Repeater control on your ASP.NET web page.
HTML snippet showing Repeater control:
<TABLE>
<asp:Repeater id="LogRepeater" runat="server">
<ItemTemplate>
<TR><TD>
Entry Date: <%# DataBinder.Eval(Container.DataItem, "EntryDate") %><br>
Entry Time: <%# DataBinder.Eval(Container.DataItem, "EntryTime") %>
...
</TD></TR>
</ItemTemplate>
</asp:Repeater>
</TABLE>
The Repeater control gets bound to a datasource and repeats the HTML code for
each entry in the datasource. To understand the DataBinder.Eval
statement, see my DataBinder page. So, back to
serialization. We can use the aryEntryList array of errors as
our datasource for the Repeater control provided it is serializable.
LogRepeater.DataSource = aryEntryList
LogRepeater.DataBind()
|