When you think ASP, think...
Recent Articles
All Articles
ASP.NET Articles [1.x] [2.0]
ASPFAQs.com
Message Board
Related Web Technologies
User Tips!
Coding Tips
Search

Sections:
Book Reviews
Sample Chapters
Commonly Asked Message Board Questions
Headlines from ASPWire.com
JavaScript Tutorials
MSDN Communities Hub
Official Docs
Security
Stump the SQL Guru!
Web Hosts
XML Info
Information:
Advertise
Feedback
Author an Article
Technology Jobs



















internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
ASP ASP.NET ASP FAQs Message Board Feedback ASP Jobs
Print this page.

Software Development Lead (.NET)
Professional Technical Resources
US-CA-Roseville

Justtechjobs.com Post A Job | Post A Resume

Published: Wednesday, January 23, 2002

XML Serialization in ASP.NET
By Anthony Hart


Introduction
In the past, maintaining the state of an object in ASP often required some very inventive and painstaking code. In the brave new world of .NET, however, Object Serialization offers us a comparatively easy way to do just that, as well as some other useful tasks.

- continued -

As a kid, I remember waking up on many a cold morning and stumbling into the kitchen with my eyes half-closed, looking forward to whatever Mom had prepared for breakfast, only to find an anticlimactic bowl of steaming hot just-add-boiling-water instant oatmeal waiting for me on the table. At least I wasn't like the more unfortunate kids whose mothers force-fed them that white silt of death, powdered milk. I am absolutely certain that something must go seriously awry in the dehydration process of milk because upon rehydration, that stuff is just plain nasty.

Be that as it may, I think that at least one of the developers involved in creating the .NET Framework must have been one of those abused children. I see powdered milk fingerprints all over some of the new data management techniques in .NET. Then again, in an age of dehydrated/rehydrated food products, what could be more logical than dehydrated/rehydrated data?

Object Serialization
The technique to which I refer is called "Object Serialization". Object Serialization is a process through which an object's state is transformed into some serial data format, such as XML or a binary format, in order to be stored for some later use. In other words, the object is "dehydrated" and put away until we need to use it again. Let's look at an example to clarify this idea a little further. Suppose we have an object defined and instantiated as shown below:

Public Class Person
  private m_sName as string
  private m_iAge as integer
  
  public property Name() as string
    get
      return m_sName
    end get
    set(byval sNewName as string)
      m_sName = sNewName
    end set
  end property
    
  public property Age() as integer
    get
      return m_iAge
    end get
    set(byval iNewAge as integer)
      m_iAge = iNewAge
    end set
  end property
End Class

dim oPerson as New Person()
oPerson.Name = "Powdered Toast Man"
oPerson.Age = "38"

Let's say that for some reason, we wanted to save a copy of this object just as it is at this very moment. We could serialize it as an XML document that would look something like this:

<Person>
	<Name>Powdered Toast Man</Name>
	<Age>38</Age>
</Person>

Then, at some later time when we needed to use the object again, we could just deserialize ("rehydrate") it and have our object restored to us just as it was at the moment we serialized it.

Why All This Dried Food?
"This serialization and deserialization is all well and good," you may be saying at this point, "but what can it be used for in real world web applications?" Very good question. What would be the sense of dehydrating a glass of milk just to rehydrate it and then dehydrate it again without drinking any? Never mind that it'll probably taste like the inside of your little brother's sock drawer (maybe I should have come up with a more tasty dehydrated food for this analogy). Some good uses for serialization/deserialization include:

  • Storing user preferences in an object.
  • Maintaining security information across pages and applications.
  • Modification of XML documents without using the DOM.
  • Passing an object from one application to another.
  • Passing an object from one domain to another.
  • Passing an object through a firewall as an XML string.

These are only a few of the many possibilities that serialization opens up for us.

The Dehydration Process
"Okay, okay, I get the picture," you may be muttering now, "but how do I do it?" I'm going to walk you through a simple example of serializing an object to be saved to disk as an XML file. Keep in mind that in .NET we can serialize objects into a binary format or SOAP format as well as into XML, but we will focus solely on XML for this article for the sake of brevity. Also, the object in the example is obviously very simplistic and wouldn't be practical in the real world, but it will serve as a means to clearly illustrate how to serialize an object. The same principles used in this example can then be applied to more complicated tasks. Note that all the code used for this example is available for download at the end of this article; also a live demo is available).

First of all, let's take a look at the class that is the blueprint for our object (this snippet can be found in the file, xmlser.aspx).

<XMLRoot(ElementName:="Class_Person")> _
public class Person
  private m_sName as string
  private m_iAge as integer

  <XMLElement(ElementName:="Property_Name")> _
  public property Name() as string
    get
      return m_sName
    end get
    set(byval sNewName as string)
      m_sName = sNewName
    end set
  end property

  <XMLElement(ElementName:="Property_Age")> _
  public property Age() as integer
    get
      return m_iAge
    end get
    set(byval iNewAge as integer)
      m_iAge = iNewAge
    end set
  end property

  public function Hello() as string
    dim s as string
    s = "Hi! My name is " & Name & " and I am " & Age & " years old."
    return s
  end function

  public function Goodbye() as string
    return "So long!"
  end function
end class

This looks pretty similar to the class we saw earlier but with a few adjustments. First of all, notice the lines that say, <XMLRoot... and <XMLElement.... These are .NET attributes and tell the serializer where the various members of this object will appear in the XML document and what they will be named. Without these, serialization cannot take place. The next difference you will notice is that there are two methods declared in the class called, Hello() and Goodbye(). These really have no bearing on the serialization that will take place, but we will use them later to demonstrate the state of the object at a given point in the serialization process.

Next let's look at the code that actually instantiates the object and then serializes it.

dim oXS as XMLSerializer = new XMLSerializer(GetType(Person))
dim oLucky as new Person()
dim oStmW as StreamWriter

'Set properties
oLucky.Name = "Lucky Day"
oLucky.Age = 52

'Display property values
Response.Write("Hello() = " & oLucky.Hello() & "<br />")
Response.Write("Goodbye() = " & oLucky.Goodbye() & "<br />")

'Serialize object to XML and write it to XML file
oStmW = new StreamWriter(Server.MapPath("lucky.xml"))
oXS.Serialize(oStmW, oLucky)
oStmW.Close()
[View a live demo!]

First of all, we declare and instantiate an XMLSerializer object. You'll notice that we had to tell it right from the onset, using the GetType() function, what type of object it's going to be serializing. Next you see that we assign values to the Name and Age properties of the Person object we instantiated. Then we output to the ASP.NET page what the properties are set to by calling the Hello() and Goodbye() methods of the Person object. Remember that this is only so that we can see what's happening with the object during this process. Next comes the good stuff: We instantiate a StreamWriter object and tell it that it will be writing to a file called, lucky.xml. We then call the Serialize() method of the XMLSerializer object and send it our Person object to be serialized as well as the StreamWriter object so it will write the resulting XML to the file specified. Then we close the StreamWriter, thereby closing the file.

That's it. If everything works correctly, an XML file (lucky.xml) will be written to disk. It should look like this:

<?xml version="1.0" encoding="utf-8"?>
<Class_Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Property_Age>52</Property_Age>
  <Property_Name>Lucky Day</Property_Name>
</Class_Person>

Notice that the names of the XML elements are exactly as we specified in the <XMLRoot()> and <XMLElement()> attributes in the class earlier. In Part 2 we'll examine how to "rehydrate" our XML into an object instance.

  • Read Part 2!


    Windows Internet Technology | ASP.NET [1.x] [2.0] | ASPMessageboard.com | ASPFAQs.com | Advertise | Feedback | Author an Article

  • internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info

    Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

    Whitepapers and eBooks

    Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
    IBM Solutions Brief: Go Green With IBM System xTM And Intel
    HP eBook: Simplifying SQL Server Management
    IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
    Microsoft PDF: Top 10 Reasons to Move to Server Virtualization with Hyper-V
    Microsoft PDF: Six Reasons Why Microsoft's Hyper-V Will Overtake Vmware
    Microsoft Step-by-Step Guide: Hyper-V and Failover Clustering
    Intel PDF: Quad-Core Impacts More Than the Data Center
    Intel PDF: Virtualization Delivers Data Center Efficiency
    Go Parallel Article: PDC 2008 in Review
    Microsoft PDF: Top 11 Reasons to Upgrade to Windows Server 2008
    Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
    Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
      PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
    Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
    Go Parallel Article: Q&A with a TBB Junkie
    IBM Whitepaper: Innovative Collaboration to Advance Your Business
    Internet.com eBook: Real Life Rails
    IBM eBook: The Pros and Cons of Outsourcing
    Internet.com eBook: Best Practices for Developing a Web Site
    IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
    Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
    IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
    Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
    HP eBook: Guide to Storage Networking
    MORE WHITEPAPERS, EBOOKS, AND ARTICLES