Edit

Share via


StateManagedCollection Class

Definition

Provides a base class for all strongly typed collections that manage IStateManager objects.

C#
public abstract class StateManagedCollection : System.Collections.IList, System.Web.UI.IStateManager
Inheritance
StateManagedCollection
Derived
Implements

Examples

The following code example demonstrates how to derive a strongly typed collection class from StateManagedCollection to contain IStateManager objects. In this example, the CycleCollection is derived to contain instances of the abstract Cycle class, which can be either Bicycle or Tricycle objects. The Cycle class implements the IStateManager interface because it stores the value of the CycleColor property in view state.

C#
namespace Samples.AspNet.CS.Controls {

    using System;
    using System.Security.Permissions;
    using System.Collections;
    using System.ComponentModel;
    using System.Drawing;           
    using System.Web;
    using System.Web.UI;            
    //////////////////////////////////////////////////////////////
    //
    // The strongly typed CycleCollection class is a collection
    // that contains Cycle class instances, which implement the
    // IStateManager interface.
    //
    //////////////////////////////////////////////////////////////
    [AspNetHostingPermission(SecurityAction.Demand, 
        Level=AspNetHostingPermissionLevel.Minimal)]
    public sealed class CycleCollection : StateManagedCollection {
        
        private static readonly Type[] _typesOfCycles 
            = new Type[] { typeof(Bicycle), typeof(Tricycle) };

        protected override object CreateKnownType(int index) {
            switch(index) {
                case 0:
                    return new Bicycle();
                case 1:
                    return new Tricycle();                    
                default:
                    throw new ArgumentOutOfRangeException("Unknown Type");
            }            
        }

        protected override Type[] GetKnownTypes() {
            return _typesOfCycles;
        }

        protected override void SetDirtyObject(object o) {
            ((Cycle)o).SetDirty();
        }
    }
    //////////////////////////////////////////////////////////////
    //
    // The abstract Cycle class represents bicycles and tricycles.
    //
    //////////////////////////////////////////////////////////////
    public abstract class Cycle : IStateManager {

        protected internal Cycle(int numWheels) : this(numWheels, "Red"){ }
        
        protected internal Cycle(int numWheels, String color) {    
            numberOfWheels = numWheels;
            CycleColor = color;
        }
        
        private int numberOfWheels = 0;
        public int NumberOfWheels {
            get { return numberOfWheels; }
        }
        
        public string CycleColor {
            get { 
                object o = ViewState["Color"];
                return (null == o) ? String.Empty : o.ToString() ;
            }
            set {
                ViewState["Color"] = value;            
            }        
        }

        internal void SetDirty() {
            ViewState.SetDirty(true);
        }
        
        // Because Cycle does not derive from Control, it does not 
        // have access to an inherited view state StateBag object.
        private StateBag viewState;
        private StateBag ViewState {
            get {
                if (viewState == null) {
                    viewState = new StateBag(false);
                    if (isTrackingViewState) {
                        ((IStateManager)viewState).TrackViewState();
                    }
                }
                return viewState;
            }
        }

        // The IStateManager implementation.
        private bool isTrackingViewState;
        bool IStateManager.IsTrackingViewState {
            get {
                return isTrackingViewState;
            }
        }

        void IStateManager.LoadViewState(object savedState) {
            object[] cycleState = (object[]) savedState;
            
            // In SaveViewState, an array of one element is created.
            // Therefore, if the array passed to LoadViewState has 
            // more than one element, it is invalid.
            if (cycleState.Length != 1) {
                throw new ArgumentException("Invalid Cycle View State");
            }
            
            // Call LoadViewState on the StateBag object.
            ((IStateManager)ViewState).LoadViewState(cycleState[0]);
        }

        // Save the view state by calling the StateBag's SaveViewState
        // method.
        object IStateManager.SaveViewState() {
            object[] cycleState = new object[1];

            if (viewState != null) {
                cycleState[0] = ((IStateManager)viewState).SaveViewState();
            }
            return cycleState;
        }

        // Begin tracking view state. Check the private variable, because 
        // if the view state has not been accessed or set, then it is not  
        // being used and there is no reason to store any view state.
        void IStateManager.TrackViewState() {
            isTrackingViewState = true;
            if (viewState != null) {
                ((IStateManager)viewState).TrackViewState();
            }
        }        
    }

    public sealed class Bicycle : Cycle {
    
        // Create a red Cycle with two wheels.
        public Bicycle() : base(2) {}    
    }
    
    public sealed class Tricycle : Cycle {
    
        // Create a red Cycle with three wheels.
        public Tricycle() : base(3) {}
    }
}

Remarks

The StateManagedCollection class is the base class for all strongly typed collections that store IStateManager elements, including DataControlFieldCollection, ParameterCollection, StyleCollection, TreeNodeBindingCollection, and others. The StateManagedCollection collection manages its own state as well as the state of the elements it contains. Therefore, a call to IStateManager.SaveViewState saves the state of the collection and the state of all the elements currently contained by the collection.

The most important methods to consider when deriving from the StateManagedCollection class are CreateKnownType, GetKnownTypes, OnValidate, SetDirty, and SetDirtyObject. The CreateKnownType and GetKnownTypes methods are used to store an index in view state for the type of a contained element. Storing an index rather than a fully qualified type name improves performance. The OnValidate method is called whenever elements of the collection are manipulated, and validates the elements according to business rules. Currently, the implementation of the OnValidate method prohibits null objects from being stored in the collection; however, you can override this method to define your own validation behavior in a derived type. The SetDirty method forces the entire collection to be serialized to view state, rather than just serializing changes made to state since the last time it was loaded. The SetDirtyObject method is an abstract method you can implement to perform this same behavior at the element level.

Important

StateManagedCollection stores assembly-qualified type names of the collection items in view state. A site visitor could decode the view state and retrieve the type name. If this scenario creates a security concern in your Web site, you can manually encrypt the type name before placing it in the view state.

Constructors

StateManagedCollection()

Initializes a new instance of the StateManagedCollection class.

Properties

Count

Gets the number of elements contained in the StateManagedCollection collection.

Methods

Clear()

Removes all items from the StateManagedCollection collection.

CopyTo(Array, Int32)

Copies the elements of the StateManagedCollection collection to an array, starting at a particular array index.

CreateKnownType(Int32)

When overridden in a derived class, creates an instance of a class that implements IStateManager. The type of object created is based on the specified member of the collection returned by the GetKnownTypes() method.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator()

Returns an iterator that iterates through the StateManagedCollection collection.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetKnownTypes()

When overridden in a derived class, gets an array of IStateManager types that the StateManagedCollection collection can contain.

GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
OnClear()

When overridden in a derived class, performs additional work before the Clear() method removes all items from the collection.

OnClearComplete()

When overridden in a derived class, performs additional work after the Clear() method finishes removing all items from the collection.

OnInsert(Int32, Object)

When overridden in a derived class, performs additional work before the IList.Insert(Int32, Object) or IList.Add(Object) method adds an item to the collection.

OnInsertComplete(Int32, Object)

When overridden in a derived class, performs additional work after the IList.Insert(Int32, Object) or IList.Add(Object) method adds an item to the collection.

OnRemove(Int32, Object)

When overridden in a derived class, performs additional work before the IList.Remove(Object) or IList.RemoveAt(Int32) method removes the specified item from the collection.

OnRemoveComplete(Int32, Object)

When overridden in a derived class, performs additional work after the IList.Remove(Object) or IList.RemoveAt(Int32) method removes the specified item from the collection.

OnValidate(Object)

When overridden in a derived class, validates an element of the StateManagedCollection collection.

SetDirty()

Forces the entire StateManagedCollection collection to be serialized into view state.

SetDirtyObject(Object)

When overridden in a derived class, instructs an object contained by the collection to record its entire state to view state, rather than recording only change information.

ToString()

Returns a string that represents the current object.

(Inherited from Object)

Explicit Interface Implementations

ICollection.Count

Gets the number of elements contained in the StateManagedCollection collection.

ICollection.IsSynchronized

Gets a value indicating whether the StateManagedCollection collection is synchronized (thread safe). This method returns false in all cases.

ICollection.SyncRoot

Gets an object that can be used to synchronize access to the StateManagedCollection collection. This method returns null in all cases.

IEnumerable.GetEnumerator()

Returns an iterator that iterates through the StateManagedCollection collection.

IList.Add(Object)

Adds an item to the StateManagedCollection collection.

IList.Clear()

Removes all items from the StateManagedCollection collection.

IList.Contains(Object)

Determines whether the StateManagedCollection collection contains a specific value.

IList.IndexOf(Object)

Determines the index of a specified item in the StateManagedCollection collection.

IList.Insert(Int32, Object)

Inserts an item into the StateManagedCollection collection at the specified index.

IList.IsFixedSize

Gets a value indicating whether the StateManagedCollection collection has a fixed size. This method returns false in all cases.

IList.IsReadOnly

Gets a value indicating whether the StateManagedCollection collection is read-only.

IList.Item[Int32]

Gets the IStateManager element at the specified index.

IList.Remove(Object)

Removes the first occurrence of the specified object from the StateManagedCollection collection.

IList.RemoveAt(Int32)

Removes the IStateManager element at the specified index.

IStateManager.IsTrackingViewState

Gets a value indicating whether the StateManagedCollection collection is saving changes to its view state.

IStateManager.LoadViewState(Object)

Restores the previously saved view state of the StateManagedCollection collection and the IStateManager items it contains.

IStateManager.SaveViewState()

Saves the changes to the StateManagedCollection collection and each IStateManager object it contains since the time the page was posted back to the server.

IStateManager.TrackViewState()

Causes the StateManagedCollection collection and each of the IStateManager objects it contains to track changes to their view state so they can be persisted across requests for the same page.

Extension Methods

Cast<TResult>(IEnumerable)

Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

Enables parallelization of a query.

AsQueryable(IEnumerable)

Converts an IEnumerable to an IQueryable.

Applies to

Product Versions
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

See also