HOW TO: Serialize Web Server Controls by Using Visual C# .NET

Summary

This step-by-step article describes how to serialize the Items property of an ASP.NET ListBox Web server control.

When you develop an ASP.NET Web application, you may want to store properties of a Web server control to a persistent storage device. By creating custom classes that extend the functionality of the standard ASP.NET Web Controls library, you can serialize public properties of a Web server control.

Requirements

  • Microsoft .NET Framework
  • Microsoft Windows 2000 or Microsoft Windows XP
  • Microsoft Internet Information Services (IIS) 5.0 or later

Create a Class to Serialize the Properties of a Web Server Control

This section describes how to create a class that can serialize and deserialize the Items property of a ListBox Web server control (System.Web.UI.WebControls.ListBox control):
  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, click
    New, and then click Project.
  3. Under Project Types, select Visual C# Projects. Under Templates, select Class Library.
  4. Name the project SerializableControls, and then click
    OK. By default, a class file (Class1.cs) is created and added to the project.
  5. Add a reference to System.Web.dll. To do this, follow these steps:
    1. On the Project menu in the Visual Studio .NET IDE, click Add Reference.
    2. On the .NET tab, locate
      System.Web.dll, and then click
      Select.
    3. Click OK in the Add References dialog box to accept your selections. If you receive a prompt to generate wrappers for the libraries that you selected, click
      Yes.
  6. Rename the Class1.cs class file to SerialListBox.cs. To do this, right-click Class1.cs in Solution Explorer, and then click
    Rename. Type SerialListBox.cs, and then press ENTER.
  7. In the SerialListBox.cs file, replace the existing code with:
    using System;
    using System.Runtime.Serialization;
    using System.Web.UI.WebControls;

    namespace SerializableControls
    {
    [Serializable]
    public class SerialListBox : System.Web.UI.WebControls.ListBox , System.Runtime.Serialization.ISerializable
    {
    public SerialListBox()
    {
    }

    // Deserialization constructor
    public SerialListBox(SerializationInfo info, StreamingContext context)
    {
    string strItem;
    string strValue;

    // Obtain the list of item keys.
    string itemList = info.GetString("ItemList");
    string [] items = itemList.Split(new Char[] {';'});

    // Create a new list item for each key in the ItemList.
    for(int nCount = 0; nCount < (items.Length - 1); nCount++)
    // use (items.Length - 1) due to terminating ';' delimiter
    {
    // list item Text property
    strItem = items[nCount];

    // list item Value property
    strValue = info.GetString("Item-Value-" + strItem);

    this.Items.Add(new System.Web.UI.WebControls.ListItem(strItem, strValue));
    }
    }

    // Serialization function (see ISerializable)
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
    string itemList = "";

    foreach(ListItem item in this.Items)
    {
    // Add a ';' delimited list of item keys using the Text property of the item.
    itemList += item.Text + ";";

    // Add a Key/Value pair to the SerializationInfo object.
    // Use the "Item-Value-<KEY>" format to distingush item-value properties
    // from other properties stored in the SerializationInfo object.
    info.AddValue("Item-Value-" + item.Text, item.Value);
    }

    info.AddValue("ItemList", itemList);
    }
    }
    }
  8. On the Build menu, click Build Solution to build the solution. Alternatively, press CTRL+SHIFT+B.

Create an ASP.NET WebForm to Test the Serializable Web Server Control

  1. In Microsoft Visual Studio .NET, click Newon the File menu, and then click
    Project.
  2. Under Projects, select Visual C# Projects. Under Templates, select ASP.NET Web Application.
  3. In the Location box, replace the default name with SerializationTest. If you are using the local server, you can leave the server name as http://localhost. The resulting
    Location box appears as follows:
    http://localhost/SerializationTest
    By default, the WebForm1.aspx file is created and added to the project.
  4. Add a reference to SerializableControls class library. To do this, follow these steps:
    1. On the Project menu in the Visual Studio .NET Integrated Development Environment (IDE), click Add Reference.
    2. On the .NET tab, select
      Browse.
    3. In the Open dialog box, locate the
      SerializableControls.dll file, click Open, and then click OK.

      NOTE: The SerializableControls.dll file will be located in the Bin folder under the project folder for the class library project that you have just created.
  5. In the lower left corner of the Web form designer, click
    HTML to switch to the HTML view for WebForm1.aspx. Replace the existing code with:
    <%@ Register TagPrefix="cc1" Namespace="SerializableControls" Assembly="SerializableControls" %>
    <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="SerializationTest.WebForm1" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
    <HTML>
    <HEAD>
    <title>WebForm1</title>
    <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
    <meta name="CODE_LANGUAGE" Content="C#">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">
    <cc1:SerialListBox id="lstSerListBox" style="Z-INDEX: 101; LEFT: 85px; POSITION: absolute; TOP: 23px"
    runat="server" Width="172px" Height="121px" EnableViewState="False" AutoPostBack="True">
    <asp:ListItem Value="1">First Item</asp:ListItem>
    <asp:ListItem Value="2">Second Item</asp:ListItem>
    <asp:ListItem Value="3">Third Item</asp:ListItem>
    </cc1:SerialListBox>
    <asp:Button id="btnLoad" style="Z-INDEX: 105; LEFT: 17px; POSITION: absolute; TOP: 111px"
    runat="server" Text="Load"></asp:Button>
    <asp:Button id="btnSave" style="Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 26px"
    runat="server" Text="Save"></asp:Button>
    <asp:Label id="lblValue" style="Z-INDEX: 106; LEFT: 270px; POSITION: absolute; TOP: 25px"
    runat="server" Width="68px" Height="22px">Value: </asp:Label>
    </form>
    </body>
    </HTML>
    NOTE: When you paste code in the HTML window, paste the code segments as HTML. To do this, select Paste as HTML on the
    Edit menu.

    This code does the following:

    • Adds a Button Web server control to the Web form. The ID of the control is set to btnLoad, and the Text property is set to Load.
    • Adds a Button Web server control to the Web form. The ID of the control is set to btnSave, and the Text property is set to Save.
    • Adds a Label control to the Web form.
    • Adds the SerialListBox custom control with three list items. The ID is set to lstSerListBox. To use this control, you must add a reference to the top of the Web page. This defines the namespace and tag that is used in the HTML.
  6. In the lower left corner of the IDE, click
    Design to switch to the Design view of WebForm1.aspx. Double-click btnSave. This starts the btnSave_Click() event handler in the code-behind Visual C# .NET (WebForm1.aspx.cs) file. Replace the existing code with the following:
    private void btnSave_Click(object sender, System.EventArgs e)
    {
    Stream stream = new FileStream(@"c:\Test\MyListBox.bin", FileMode.Create, FileAccess.Write, FileShare.None);

    // Serialize the object, and close the TextWriter.
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, lstSerListBox);
    stream.Close();

    // Clear all SerialListBox items.
    lstSerListBox.Items.Clear();
    lblValue.Text = "";
    }
    NOTE: In this code, C:\Test is a folder that you must create. This folder holds the file that has the properties of the Web server control. Make sure that this folder has Write permissions for the account that the ASP.NET code is running under. By default, ASP.NET applications in version 1.0 of the .NET Framework run under the ASPNET account.
  7. In Solution Explorer, right-click the
    WebForm1.aspx file, and then click View Designer to switch back to Design view for the WebForm1.aspx file. In Design view, double-click the btnLoad button. This opens the Visual C# .NET code for the btnLoad_Click() event handler. Replace the existing code with the following code:
    private void btnLoad_Click(object sender, System.EventArgs e)
    {
    // Open the FileStream to read from.
    Stream stream = File.OpenRead(@"C:\Test\MyListBox.bin");

    // Deserialize the object, and close the TextReader.
    BinaryFormatter formatter = new BinaryFormatter();
    lstSerListBox = (SerializableControls.SerialListBox)(formatter.Deserialize(stream));
    stream.Close();
    }
  8. Switch back to the WebForm1.aspx Design view, and then double-click the lstSerListBox list box control. This opens the Visual C# .NET code for the lstSerListBox_SelectedIndexChanged() event handler. Replace the existing code with the following:
    private void lstSerListBox_SelectedIndexChanged(object sender, System.EventArgs e)
    {
    lblValue.Text = "Value: " + lstSerListBox.SelectedItem.Value.ToString();
    }
  9. In the WebForm1.aspx.cs file, add the following code at the top of the file to import these namespaces :
    using System.IO;
    using System.Runtime.Serialization;
    using System.Runtime.Serialization.Formatters.Binary;
  10. On the Build menu, click Build Solution to build the solution. Alternatively, press CTRL+SHIFT+B.

Test the WebForm

  1. In Solution Explorer, right-click the
    WebForm1.aspx file, and then click View in Browser.
  2. When you see a Web forms page that contains a
    Load button, a Save button, a list box, and a label, click any item in the list box. The label control displays the value of the selected list box item.
  3. Click Save. The contents of the list box are serialized and saved to the disk. The contents of the list box disappear.
  4. Click Load. The serialized data is read from the disk and a new ListBox control is instantiated with the serialized data. The contents of the list box are restored to the previous state.

References

For additional information, click the article number below to view the article in the Microsoft Knowledge Base:
306459 INFO: ASP.NET Server Controls Overview
For more information about saving the properties of controls, visit the following Microsoft Developer Network (MSDN) Web site:
Propriedades

ID do Artigo: 328547 - Última Revisão: 24 de mar de 2009 - Revisão: 1

Comentários