Logo
PREGNANCY
Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
 
 
Windows XP

Microsoft ASP.NET 4 : Caching and State Management - Session State and More Complex Data

6/23/2011 11:39:47 AM
The ASP.NET Session object can store any (serializable) object running in the CLR. That goes for larger data—not just small strings or other scalar types. One of the most common uses for the Session object is for implementing features such as shopping carts or any other data that has to go with a particular client. For example, in a commerce-oriented site where customers can purchase products, you would probably implement a central database representing your inventory. Then, as users sign on, they have the opportunity to select items from your inventory and place them in a temporary holding area associated with the session they're running. In ASP.NET, that holding area is typically the Session object.

A number of different collections are useful for managing shopping cart–like scenarios. Probably the easiest to use is the good ole ArrayList, an automatically sizing array that supports both random access and the IList interface. However, for other scenarios you might use a small DataTable, a DataSet, or some other more complex type. Keep in mind that DataTable and DataSet have more features than necessary for some situations, which could lead to bloated session state if you're not careful.

You also work with the DataTable in depth. The example illustrates using ADO.NET objects, data-bound controls, and session state to transfer items from an inventory (represented as a DataList) to a collection of selected items (represented as a GridView).

Using session state, ADO.NET objects, and data-bound controls

  1. Create a new page on the SessionState site named UseDataList.aspx.

    Add DataList to the page by copying the following code between the <div> tags on the generated page. The DataList will display the elements in the .NET References .

    <asp:DataList ID="DataList1"
    runat="server" BackColor="White" BorderColor="#E7E7FF"
    BorderStyle="None" BorderWidth="1px" CellPadding="3"
    GridLines="Horizontal"
    Style="z-index: 100; left: 8px; position: absolute; top: 16px"
    OnItemCommand="DataList1_ItemCommand" Caption="Items in Inventory" >
    <FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
    <SelectedItemStyle BackColor="#738A9C"
    Font-Bold="True" ForeColor="#F7F7F7" />
    <AlternatingItemStyle BackColor="#F7F7F7" />
    <ItemStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
    <ItemTemplate>
    ID:
    <asp:Label ID="IDLabel"
    runat="server" Text='<%# Eval("ID") %>'></asp:Label><br />
    Title:
    <asp:Label ID="TitleLabel"
    runat="server" Text='<%# Eval("Title") %>'></asp:Label><br />
    AuthorLastName:
    <asp:Label ID="AuthorLastNameLabel"
    runat="server" Text='<%# Eval("AuthorLastName")
    %>'></asp:Label><br />
    AuthorFirstName:
    <asp:Label ID="AuthorFirstNameLabel"
    runat="server" Text='<%# Eval("AuthorFirstName")
    %>'></asp:Label><br />
    Topic:
    <asp:Label ID="TopicLabel" runat="server"
    Text='<%# Eval("Topic") %>'></asp:Label><br />
    Publisher:
    <asp:Label ID="PublisherLabel"
    runat="server"

    Text='<%# Eval("Publisher") %>'></asp:Label><br />
    <br />

    <asp:Button ID="SelectItem"

    runat="server" Text="Select Item" />

    &nbsp;
    </ItemTemplate>
    <HeaderStyle BackColor="#4A3C8C" Font-Bold="True"
    ForeColor="#F7F7F7" />
    </asp:DataList>


    The Microsoft Visual Studio Designer should appear like this when you finish:



  2. Stub out a shell for the Select Item button on the ItemCommand handler. Select DataList1 on the page. Look at the Properties pane in Visual Studio. Click the lightning bolt button to view the available events you can handle. In the edit box next to the ItemCommand event, notice the name of the command: DataList1_ItemCommand. Double-click inside the edit box and Visual Studio will produce an item command handler. The button's handler will be named DataList1_ItemCommand to match the identifier in the DataList1. You use it shortly to move items from the inventory to the selected items table.

    public partial class UseDataList : System.Web.UI.Page
    {

    protected void DataList1_ItemCommand(object source,
    DataListCommandEventArgs e)
    {
    }

    }

  3. Go back to the code for the page and add some code to open a database and populate the DataList. Name the function GetInventory. The example that comes with this book includes a SQL Server database named AspNetStepByStep4 that will work. Add the database to the App_Data folder of this project. You can obtain the connection string by viewing the database in Server Explorer after you have added it to the project. You can find the connection string in the Properties pane after you select the database in Server Explorer.

    using System.Data;
    Using System.Data.Common;

    public partial class UseDataList : System.Web.UI.Page
    {

    protected DataTable GetInventory()
    {
    string strConnection =
    @"Data Source=
    .\SQLEXPRESS;
    AttachDbFilename=|DataDirectory|\ASPNETStepByStep4.mdf;
    Integrated Security=True;
    User Instance=True";

    DbProviderFactory f =
    DbProviderFactories.GetFactory("System.Data.SqlClient");

    DataTable dt = new DataTable();
    using (DbConnection connection = f.CreateConnection())
    {
    connection.ConnectionString = strConnection;
    connection.Open();
    DbCommand command = f.CreateCommand();
    command.CommandText = "Select * from DotNetReferences";
    command.Connection = connection;

    IDataReader reader = command.ExecuteReader();
    dt.Load(reader);
    reader.Close();
    connection.Close();
    }
    return dt;
    }


    protected DataTable BindToinventory()
    {
    DataTable dt;
    dt = this.GetInventory();
    this.DataList1.DataSource = dt;
    this.DataBind();
    return dt;
    }


    // More goes here...
    }


  4. Now add a method named CreateSelectedItemsData. This is a table into which selected items are placed. The method takes a DataTable object that describes the schema of the data in the live database (you see how to get that soon). You can create an empty DataTable by constructing it and then adding Columns to the column collection. The schema coming from the database will have the column name and the data type.

    public partial class UseDataList : System.Web.UI.Page
    {

    protected DataTable CreateSelectedItemsTable(DataTable tableSchema)
    {

    DataTable tableSelectedItemsData = new DataTable();

    foreach(DataColumn dc in tableSchema.Columns)
    {
    tableSelectedItemsData.Columns.Add(dc.ColumnName,
    dc.DataType);
    }
    return tableSelectedItemsData;

    }
    }

  5. Add code to the Page_Load handler. When the initial request to a page is made (that is, if the request is not a postback), Page_Load should call BindToInventory, which returns the DataTable snapshot of the DotNetReferences table. Use the DataTable as the schema on which to base the selected items table. That is, declare an instance of a DataTable and assign it the result of CreateSelectedItemsTable. Then, store the (now empty) table in the Session object using the key tableSelectedItems.

    public partial class UseDataList : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    if (!IsPostBack)
    {
    DataTable dt = BindToinventory();
    DataTable tableSelectedItems =
    this.CreateSelectedItemsTable(dt);
    Session["tableSelectedItems"] = tableSelectedItems;
    }
    }
    }

    Browse to the Web site to make sure that the database connects. It should look something like this:



  6. Now add a GridView to the page. It represents the table of selected items held in session state. Don't bother to give it a data source. You add that shortly. Make sure the AutoGenerateColumns property is set to true. The page appears this way because it's using absolute positioning:



  7. Finally, complete the handler for the SelectItem button. This method should move items from the inventory to the selected items table. You can get the selected item index from the DataListCommandEventArgs coming into the handler. Call BindToInventory to set up the DataList data source so that you can fetch the selected item. You can access the columns in the selected row using ordinal indices. From the values in each column, construct a new DataRow and add it to the selected items table. Store the modified table back in session state. Finally, apply the new selected items table to the DataSource in the GridView1 and bind the GridView1.

    public partial class UseDataList : System.Web.UI.Page
    {
    protected void DataList1_ItemCommand(object source,
    DataListCommandEventArgs e)
    {
    int nItemIndex = e.Item.ItemIndex;
    this.DataList1.SelectedIndex = nItemIndex;

    BindToinventory();

    // Order of the columns is:
    // ID, Title, FirstName, LastName, Topic, Publisher

    DataTable dt = (DataTable)DataList1.DataSource;
    String strID = (dt.Rows[nItemIndex][0]).ToString();
    String strTitle = (dt.Rows[nItemIndex][1]).ToString();
    String strAuthorLastName = (dt.Rows[nItemIndex][2]).ToString();
    String strAuthorFirstName = (dt.Rows[nItemIndex][3]).ToString();
    String strTopic = (dt.Rows[nItemIndex][4]).ToString();
    String strPublisher = (dt.Rows[nItemIndex][5]).ToString();

    DataTable tableSelectedItems;
    tableSelectedItems = (DataTable)Session["tableSelectedItems"];

    DataRow dr = tableSelectedItems.NewRow();
    dr[0] = strID;
    dr[1] = strTitle;
    dr[2] = strAuthorLastName;
    dr[3] = strAuthorFirstName;
    dr[4] = strTopic;
    dr[5] = strPublisher;

    tableSelectedItems.Rows.Add(dr);

    Session["tableSelectedItems"] = tableSelectedItems;

    this.GridView1.DataSource = tableSelectedItems;
    this.GridView1.DataBind();
    }
    }


  8. Run the site. When the page first appears, you should see only the inventory list on the left side of the page. Click the Select Item button on some of the items. You should see your browser post back to the server and render the DataList and the GridView with each newly added selected item.



Now you have a working application that uses session state. Next, look at the different ways in which you can configure ASP.NET session state.

Other -----------------
- Microsoft ASP.NET 4 : Caching and State Management - Introduction to Session State
- Installing and Configuring a Modem : Modifying the Modem’s Advanced Properties
- Installing and Configuring a Modem : Modifying the Modem’s General Properties
- Installing and Configuring a Modem : Working with Different Dialing Locations
- Installing and Configuring a Modem : Installing a Modem & Testing the Modem
- Getting Started with Modem Communications : Modem-to-Modem Communications
- Tuning Windows XP’s Performance : More Optimization Tricks
- Tuning Windows XP’s Performance : Optimizing Virtual Memory
- Tuning Windows XP’s Performance : Optimizing Applications
- Tuning Windows XP’s Performance : Optimizing Startup
- Monitoring Performance with System Monitor
- Monitoring Performance with Task Manager
- Administering Your Network - Broadcasting Console Messages
- Administering Your Network - Managing a Remote Computer
- Administering Your Network - Monitoring Performance on a Remote Computer
- Administering Your Network - Connecting to a Remote Registry & Connecting to Remote Group Policies
- Sharing Resources with the Network
- Accessing Network Resources - Mapping a Network Folder to a Local Drive Letter
- Accessing Network Resources - Adding a Network Place
- Accessing Network Resources - Using My Network Places
 
 
Most view of day
- Backup and Restore of Microsoft Lync Server 2010 : Backup Processes (part 2) - Backing Up the Central Management Store, Backing Up Lync Server Servers
- Microsoft Dynamics CRM 4 : Digital Phone Integration (part 1)
- Microsoft OneNore 2010 : Housecleaning in OneNote - Backing Up Notebooks Manually, Choosing How to Back Up Notebooks
- Windows Server 2012 : File Services and Storage - Configuring iSCSI storage (part 1) - Understanding iSCSI storage
- System Center Configuration Manager 2007 : Desired Configuration Management - Configurations
- Windows Server 2012 : Administering Active Directory using Windows PowerShell (part 2) - Finding Active Directory administration cmdlets
- Windows Server 2012 : Enabling Users to Work Anywhere (part 2) - RDS Web Access
- Working with the Windows Home Server Registry : Finding Registry Entries
- SharePoint 2010 : Configuring Search Settings and the User Interface - Search Keywords
- System Center Configuration Manager 2007 : Network Design - Troubleshooting Configuration Manager Network Issues (part 1)
Top 10
- Sharepoint 2013 : Working with the CSOM (part 6) - Working with the JavaScript client object model - Creating, reading, updating, and deleting in the JavaScript client object model
- Sharepoint 2013 : Working with the CSOM (part 5) - Working with the JavaScript client object model - Handling errors
- Sharepoint 2013 : Working with the CSOM (part 4) - Working with the JavaScript client object model - Returning collections
- Sharepoint 2013 : Working with the CSOM (part 3) - Working with the managed client object model - Creating, reading, updating, and deleting
- Sharepoint 2013 : Working with the CSOM (part 2) - Working with the managed client object model - Handling errors
- Sharepoint 2013 : Working with the CSOM (part 1) - Understanding client object model fundamentals
- Windows Phone 8 : Configuring Mailbox Settings (part 5) - Configuring Automatic Replies
- Windows Phone 8 : Configuring Mailbox Settings (part 4) - Lightening the Display,Changing the Mailbox Sync Settings
- Windows Phone 8 : Configuring Mailbox Settings (part 3) - Message Signatures, Blind CCing Yourself
- Windows Phone 8 : Configuring Mailbox Settings (part 2) - Unlinking Mailboxes, Conversation View
 
 
Windows XP
Windows Vista
Windows 7
Windows Azure
Windows Server
Windows Phone
2015 Camaro