using System;
using System.Web.UI.Design;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Reflection;

namespace DPLib
{
    /// <summary>
    /// A UrlEditor implementation from the solution from my Microsoft support incident.
    /// Originally named MyUrlEditor by MS support, I renamed it to more accurately 
    /// describe it.  The sole function of the custom UrlEditor is to assign the 
    /// DesignerSite value to the ClientScript being edited if the ClientScript.Site
    /// is null.
    /// </summary>
    public class MyHundredDollarUrlEditor : UrlEditor
    {
        public MyHundredDollarUrlEditor():base()
        {
        }

        public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            IComponent component;
            object[] objects;
            
            component = null;
            if (context.Instance as IComponent != null)
                component = (IComponent) context.Instance;
            else if (context.Instance as object[] != null) 
            {
                objects = (object[]) context.Instance;
                if (objects[0] as IComponent != null)
                    component = (IComponent) objects[0];
            }                    
            if (component != null && component.Site == null) {
                IDesignerHost designerHost = provider.GetService(typeof(IDesignerHost)) as IDesignerHost;
                Type type = Type.GetType("Microsoft.VisualStudio.Designer.Host.DesignSite, Microsoft.VisualStudio, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                ConstructorInfo constructorInfo = type.GetConstructor(new Type[] {designerHost.GetType(),typeof(string)});
                MethodInfo methodInfo = type.GetMethod("SetComponent");
                object designerSite = constructorInfo.Invoke(new object[] {designerHost,((ClientScript)component).ID});
                methodInfo.Invoke(designerSite,new object[]{component});
                component.Site = (ISite)designerSite;
            }

            //return value;
            return base.EditValue (context, provider, value);
        }
    }
}