using System;
using System.ComponentModel;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ServerControl.CS
{
    [ToolboxData("<{0}:ServerControl40 runat=server></{0}:ServerControl40>")]
    public class ServerControl40 : WebControl
    {
        [TypeConverter(typeof(NameConverter))]
        public Name Name
        {
            get
            {
                Name n = (Name)ViewState["Name"];
                return ((n == null) ? new Name() { First = "Jan", Last = "Kowalski" } : n);
            }
            set
            {
                ViewState["Name"] = value;
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write(string.Format("{0} {1}", Name.First, Name.Last));
        }
    }

    public class Name
    {
        public string First { get; set; }
        public string Last { get; set; }
    }

    public class NameConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context,
           Type sourceType)
        {

            if (sourceType == typeof(string))
            {
                return true;
            }
            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context,
           CultureInfo culture, object value)
        {
            if (value is string)
            {
                string[] v = ((string)value).Split(new char[] { ' ' });
                return new Name() { First=v[0], Last=v[1] };
            }
            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context,
           CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return ((Name)value).First + " " + ((Name)value).Last;
            }
            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}