Export (0) Print
Expand All

Custom Type State Management Example

This example shows how to enable a complex property (a property whose type is a class that itself has properties) to participate in ASP.NET view state by implementing the IStateManager interface. As described in Server Control Properties Example, you can use your control's ViewState property to manage the state of simple properties. However, to provide state management for a collection property or a property that has subproperties, you must implement the property as a read-only property, and as part of the property type you typically implement IStateManager.

The StateManagedAuthor type defined in this example demonstrates how to implement IStateManager. The StateManagedAuthor class is a complex type that itself has subproperties such as FirstName and LastName. The Author property of the BookNew control described in Custom Property State Management Example is of type StateManagedAuthor.

The implementation of the IStateManager interface in StateManagedAuthor is described in the "Code Discussion" section later in this topic.


// StateManagedAuthor.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.Web.UI;

namespace Samples.AspNet.CS.Controls
{
    [
    TypeConverter(typeof(StateManagedAuthorConverter))
    ]
    public class StateManagedAuthor : IStateManager
    {
        private bool _isTrackingViewState;
        private StateBag _viewState;

        public StateManagedAuthor()
            :
            this(String.Empty, String.Empty, String.Empty)
        {
        }

        public StateManagedAuthor(string first, string last)
            :
            this(first, String.Empty, last)
        {
        }

        public StateManagedAuthor(string first, string middle, string last)
        {
            FirstName = first;
            MiddleName = middle;
            LastName = last;
        }

        [
        Category("Behavior"),
        DefaultValue(""),
        Description("First name of author"),
        NotifyParentProperty(true)
        ]
        public virtual String FirstName
        {
            get
            {
                string s = (string)ViewState["FirstName"];
                return (s == null) ? String.Empty : s;
            }
            set
            {
                ViewState["FirstName"] = value;
            }
        }

        [
        Category("Behavior"),
        DefaultValue(""),
        Description("Last name of author"),
        NotifyParentProperty(true)
        ]
        public virtual String LastName
        {
            get
            {
                string s = (string)ViewState["LastName"];
                return (s == null) ? String.Empty : s;
            }
            set
            {
                ViewState["LastName"] = value;
            }
        }

        [
        Category("Behavior"),
        DefaultValue(""),
        Description("Middle name of author"),
        NotifyParentProperty(true)
        ]
        public virtual String MiddleName
        {
            get
            {
                string s = (string)ViewState["MiddleName"];
                return (s == null) ? String.Empty : s;
            }
            set
            {
                ViewState["MiddleName"] = value;
            }
        }

        protected virtual StateBag ViewState
        {
            get
            {
                if (_viewState == null)
                {
                    _viewState = new StateBag(false);

                    if (_isTrackingViewState)
                    {
                        ((IStateManager)_viewState).TrackViewState();
                    }
                }
                return _viewState;
            }
        }


        public override string ToString()
        {
            return ToString(CultureInfo.InvariantCulture);
        }

        public string ToString(CultureInfo culture)
        {
            return TypeDescriptor.GetConverter(
                GetType()).ConvertToString(null, culture, this);
        }

        #region IStateManager implementation
        bool IStateManager.IsTrackingViewState
        {
            get
            {
                return _isTrackingViewState;
            }
        }

        void IStateManager.LoadViewState(object savedState)
        {
            if (savedState != null)
            {
                ((IStateManager)ViewState).LoadViewState(savedState);
            }
        }

        object IStateManager.SaveViewState()
        {
            object savedState = null;

            if (_viewState != null)
            {
                savedState =
                   ((IStateManager)_viewState).SaveViewState();
            }
            return savedState;
        }

        void IStateManager.TrackViewState()
        {
            _isTrackingViewState = true;

            if (_viewState != null)
            {
                ((IStateManager)_viewState).TrackViewState();
            }
        }
        #endregion

        internal void SetDirty()
        {
            _viewState.SetDirty(true);
        }
    }
}


The StateManagedAuthor class illustrates the pattern for implementing the IStateManager interface commonly used by ASP.NET complex types. StateManagedAuthor defines a property named ViewState stored in a private variable of type StateBag and named viewState in C# and viewStateValue in Visual Basic. The ViewState property mimics the ViewState property of the Control class. StateManagedAuthor stores its properties in its ViewState dictionary just as a control stores its simple properties in the Control class's ViewState dictionary.

The IStateManager interface has one property, IsTrackingViewState, and three methods: TrackViewState, SaveViewState, and LoadViewState. The members of the IStateManager interface have the same semantics as the corresponding methods in the Control class.

The IsTrackingViewState property enables a type that implements IStateManager to coordinate with state tracking in the control in which the type is used. The StateManagedAuthor class uses a private Boolean field (isTrackingViewState in C# and isTrackingViewStateValue in Visual Basic) to store this property. In its implementation of TrackViewState, StateManagedAuthor sets isTrackingViewState or isTrackingViewStateValue to true. It also invokes the IStateManager.TrackViewState method of the private viewState or viewStateValue field corresponding to the ViewState property. The TrackViewState method starts the tracking of changes to items stored in the ViewState property. This means that if an item in the ViewState dictionary is set after TrackViewState is invoked on ViewState, the item is automatically marked as modified.

In its implementation of the SaveViewState method, StateManagedAuthor invokes only the corresponding method of its private viewState or viewStateValue field. Similarly, in its implementation of the LoadViewState method, StateManagedAuthor invokes only the corresponding method of its ViewState property. As described in Server Control Properties Example, the StateBag type of the ViewState property implements IStateManager and is a dictionary with state management built into it.

When you use a type that implements IStateManager in your control, you rely on the type to maintain its own state and invoke the type's state management methods from the TrackViewState, SaveViewState, and LoadViewState methods of your control. Thus, the BookNew control described in Custom Property State Management Example invokes the TrackViewState, SaveViewState, and LoadViewState methods of StateManagedAuthor from its own implementation of these methods.

The StateManagedAuthorConverter in the following code listing is the type converter associated with StateManagedAuthor by means of the TypeConverterAttribute attribute. The StateManagedAuthorConverter class enables conversions from the String type to the StateManagedAuthor type and vice versa as described in the Type Converter Example. The StateManagedAuthorConverter is used in this example to print the author's full name in the Render method of the BookNew class.

NoteNote

The StateManagedAuthor type does not need a type converter for state management. StateManagedAuthorConverter is provided as an optional utility class that provides string-to-value conversions. When you implement a type converter for a custom type you should override the ToString method of your type to invoke the type converter and return a string representation, as shown in the code listing for StateManagedAuthor.


// StateManagedAuthorConverter.cs
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Reflection;

namespace Samples.AspNet.CS.Controls
{
    public class StateManagedAuthorConverter :
        ExpandableObjectConverter
    {
        public override bool CanConvertFrom(
            ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

        public override bool CanConvertTo(
            ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return true;
            }
            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertFrom( 
            ITypeDescriptorContext context,
            CultureInfo culture, object value)
        {
            if (value == null)
            {
                return new StateManagedAuthor();
            }

            if (value is string)
            {
                string s = (string)value;
                if (s.Length == 0)
                {
                    return new StateManagedAuthor();
                }

                string[] parts = s.Split(' ');

                if ((parts.Length < 2) || (parts.Length > 3))
                {
                    throw new ArgumentException(
                        "Name must have 2 or 3 parts.", "value");
                }

                if (parts.Length == 2)
                {
                    return new StateManagedAuthor(parts[0], parts[1]);
                }

                if (parts.Length == 3)
                {
                    return new StateManagedAuthor(parts[0], 
                         parts[1], parts[2]);
                }
            }

            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context,
            CultureInfo culture, object value, Type destinationType)
        {
            if (value != null)
            {
                if (!(value is StateManagedAuthor))
                {
                    throw new ArgumentException(
                        "Name must have 2 or 3 parts.", "value");
                }
            }

            if (destinationType == typeof(string))
            {
                if (value == null)
                {
                    return String.Empty;
                }

                StateManagedAuthor auth = (StateManagedAuthor)value;

                if (auth.MiddleName != String.Empty)
                {
                    return String.Format("{0} {1} {2}",
                        auth.FirstName,
                        auth.MiddleName,
                        auth.LastName);
                }
                else
                {
                    return String.Format("{0} {1}",
                        auth.FirstName,
                        auth.LastName);
                }
            }

            return base.ConvertTo(context, culture,
                value, destinationType);
        }
    }
}


Compile the StateManagedAuthor and StateManagedAuthorConverter classes listed in this topic with the BookNew control listed in Custom Property State Management Example and with the BookType enumeration listed in Server Control Properties Example.

For more information about compiling and using the custom control examples, see Building the Custom Server Control Examples.

Community Additions

ADD
Show:
© 2014 Microsoft